From 2f7e4d6e38da454a8cfdc52b457215d7b010216e Mon Sep 17 00:00:00 2001 From: adil-aspose <83574456+adil-aspose@users.noreply.github.com> Date: Tue, 9 Dec 2025 11:49:25 +0500 Subject: [PATCH] Add 7 words net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: getting-started, images-and-shapes Source: AI Search API Tutorials: - tutorial - tutorial - tutorial - tutorial - tutorial - Add Shadow to Shape in a Word Document – Complete Aspose.Words Guide - tutorial Auto-generated by Professionalize.Tutorials Agent --- content/arabic/words/_index.md | 7 + content/arabic/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 266 +++++++++++++++++ content/chinese/words/_index.md | 7 + content/chinese/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 265 +++++++++++++++++ content/czech/words/_index.md | 7 + content/czech/words/net/_index.md | 7 + .../czech/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 249 ++++++++++++++++ content/dutch/words/_index.md | 7 + content/dutch/words/net/_index.md | 7 + .../dutch/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/english/words/_index.md | 7 + content/english/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 242 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 263 +++++++++++++++++ content/french/words/_index.md | 7 + content/french/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/german/words/_index.md | 7 + content/german/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 231 +++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/greek/words/_index.md | 7 + content/greek/words/net/_index.md | 7 + .../greek/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 230 +++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/hindi/words/_index.md | 7 + content/hindi/words/net/_index.md | 7 + .../hindi/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 246 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 250 ++++++++++++++++ content/hongkong/words/_index.md | 7 + content/hongkong/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 265 +++++++++++++++++ content/hungarian/words/_index.md | 7 + content/hungarian/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 250 ++++++++++++++++ content/indonesian/words/_index.md | 7 + content/indonesian/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/italian/words/_index.md | 7 + content/italian/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/japanese/words/_index.md | 7 + content/japanese/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 265 +++++++++++++++++ content/korean/words/_index.md | 7 + content/korean/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 266 +++++++++++++++++ content/polish/words/_index.md | 7 + content/polish/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/portuguese/words/_index.md | 7 + content/portuguese/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 266 +++++++++++++++++ content/russian/words/_index.md | 7 + content/russian/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/spanish/words/_index.md | 7 + content/spanish/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 250 ++++++++++++++++ content/swedish/words/_index.md | 7 + content/swedish/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 250 ++++++++++++++++ content/thai/words/_index.md | 7 + content/thai/words/net/_index.md | 7 + .../thai/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 247 ++++++++++++++++ content/turkish/words/_index.md | 7 + content/turkish/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/urdu/words/_index.md | 7 + content/urdu/words/net/_index.md | 7 + .../urdu/words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 231 +++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ content/vietnamese/words/_index.md | 7 + content/vietnamese/words/net/_index.md | 7 + .../words/net/getting-started/_index.md | 7 + .../net/getting-started/tutorial/_index.md | 247 ++++++++++++++++ .../words/net/images-and-shapes/_index.md | 7 + .../_index.md | 268 ++++++++++++++++++ 144 files changed, 12845 insertions(+) create mode 100644 content/arabic/words/_index.md create mode 100644 content/arabic/words/net/_index.md create mode 100644 content/arabic/words/net/getting-started/_index.md create mode 100644 content/arabic/words/net/getting-started/tutorial/_index.md create mode 100644 content/arabic/words/net/images-and-shapes/_index.md create mode 100644 content/arabic/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/chinese/words/_index.md create mode 100644 content/chinese/words/net/_index.md create mode 100644 content/chinese/words/net/getting-started/_index.md create mode 100644 content/chinese/words/net/getting-started/tutorial/_index.md create mode 100644 content/chinese/words/net/images-and-shapes/_index.md create mode 100644 content/chinese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/czech/words/_index.md create mode 100644 content/czech/words/net/_index.md create mode 100644 content/czech/words/net/getting-started/_index.md create mode 100644 content/czech/words/net/getting-started/tutorial/_index.md create mode 100644 content/czech/words/net/images-and-shapes/_index.md create mode 100644 content/czech/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/dutch/words/_index.md create mode 100644 content/dutch/words/net/_index.md create mode 100644 content/dutch/words/net/getting-started/_index.md create mode 100644 content/dutch/words/net/getting-started/tutorial/_index.md create mode 100644 content/dutch/words/net/images-and-shapes/_index.md create mode 100644 content/dutch/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/english/words/_index.md create mode 100644 content/english/words/net/_index.md create mode 100644 content/english/words/net/getting-started/_index.md create mode 100644 content/english/words/net/getting-started/tutorial/_index.md create mode 100644 content/english/words/net/images-and-shapes/_index.md create mode 100644 content/english/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/french/words/_index.md create mode 100644 content/french/words/net/_index.md create mode 100644 content/french/words/net/getting-started/_index.md create mode 100644 content/french/words/net/getting-started/tutorial/_index.md create mode 100644 content/french/words/net/images-and-shapes/_index.md create mode 100644 content/french/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/german/words/_index.md create mode 100644 content/german/words/net/_index.md create mode 100644 content/german/words/net/getting-started/_index.md create mode 100644 content/german/words/net/getting-started/tutorial/_index.md create mode 100644 content/german/words/net/images-and-shapes/_index.md create mode 100644 content/german/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/greek/words/_index.md create mode 100644 content/greek/words/net/_index.md create mode 100644 content/greek/words/net/getting-started/_index.md create mode 100644 content/greek/words/net/getting-started/tutorial/_index.md create mode 100644 content/greek/words/net/images-and-shapes/_index.md create mode 100644 content/greek/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/hindi/words/_index.md create mode 100644 content/hindi/words/net/_index.md create mode 100644 content/hindi/words/net/getting-started/_index.md create mode 100644 content/hindi/words/net/getting-started/tutorial/_index.md create mode 100644 content/hindi/words/net/images-and-shapes/_index.md create mode 100644 content/hindi/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/hongkong/words/_index.md create mode 100644 content/hongkong/words/net/_index.md create mode 100644 content/hongkong/words/net/getting-started/_index.md create mode 100644 content/hongkong/words/net/getting-started/tutorial/_index.md create mode 100644 content/hongkong/words/net/images-and-shapes/_index.md create mode 100644 content/hongkong/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/hungarian/words/_index.md create mode 100644 content/hungarian/words/net/_index.md create mode 100644 content/hungarian/words/net/getting-started/_index.md create mode 100644 content/hungarian/words/net/getting-started/tutorial/_index.md create mode 100644 content/hungarian/words/net/images-and-shapes/_index.md create mode 100644 content/hungarian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/indonesian/words/_index.md create mode 100644 content/indonesian/words/net/_index.md create mode 100644 content/indonesian/words/net/getting-started/_index.md create mode 100644 content/indonesian/words/net/getting-started/tutorial/_index.md create mode 100644 content/indonesian/words/net/images-and-shapes/_index.md create mode 100644 content/indonesian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/italian/words/_index.md create mode 100644 content/italian/words/net/_index.md create mode 100644 content/italian/words/net/getting-started/_index.md create mode 100644 content/italian/words/net/getting-started/tutorial/_index.md create mode 100644 content/italian/words/net/images-and-shapes/_index.md create mode 100644 content/italian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/japanese/words/_index.md create mode 100644 content/japanese/words/net/_index.md create mode 100644 content/japanese/words/net/getting-started/_index.md create mode 100644 content/japanese/words/net/getting-started/tutorial/_index.md create mode 100644 content/japanese/words/net/images-and-shapes/_index.md create mode 100644 content/japanese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/korean/words/_index.md create mode 100644 content/korean/words/net/_index.md create mode 100644 content/korean/words/net/getting-started/_index.md create mode 100644 content/korean/words/net/getting-started/tutorial/_index.md create mode 100644 content/korean/words/net/images-and-shapes/_index.md create mode 100644 content/korean/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/polish/words/_index.md create mode 100644 content/polish/words/net/_index.md create mode 100644 content/polish/words/net/getting-started/_index.md create mode 100644 content/polish/words/net/getting-started/tutorial/_index.md create mode 100644 content/polish/words/net/images-and-shapes/_index.md create mode 100644 content/polish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/portuguese/words/_index.md create mode 100644 content/portuguese/words/net/_index.md create mode 100644 content/portuguese/words/net/getting-started/_index.md create mode 100644 content/portuguese/words/net/getting-started/tutorial/_index.md create mode 100644 content/portuguese/words/net/images-and-shapes/_index.md create mode 100644 content/portuguese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/russian/words/_index.md create mode 100644 content/russian/words/net/_index.md create mode 100644 content/russian/words/net/getting-started/_index.md create mode 100644 content/russian/words/net/getting-started/tutorial/_index.md create mode 100644 content/russian/words/net/images-and-shapes/_index.md create mode 100644 content/russian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/spanish/words/_index.md create mode 100644 content/spanish/words/net/_index.md create mode 100644 content/spanish/words/net/getting-started/_index.md create mode 100644 content/spanish/words/net/getting-started/tutorial/_index.md create mode 100644 content/spanish/words/net/images-and-shapes/_index.md create mode 100644 content/spanish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/swedish/words/_index.md create mode 100644 content/swedish/words/net/_index.md create mode 100644 content/swedish/words/net/getting-started/_index.md create mode 100644 content/swedish/words/net/getting-started/tutorial/_index.md create mode 100644 content/swedish/words/net/images-and-shapes/_index.md create mode 100644 content/swedish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/thai/words/_index.md create mode 100644 content/thai/words/net/_index.md create mode 100644 content/thai/words/net/getting-started/_index.md create mode 100644 content/thai/words/net/getting-started/tutorial/_index.md create mode 100644 content/thai/words/net/images-and-shapes/_index.md create mode 100644 content/thai/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/turkish/words/_index.md create mode 100644 content/turkish/words/net/_index.md create mode 100644 content/turkish/words/net/getting-started/_index.md create mode 100644 content/turkish/words/net/getting-started/tutorial/_index.md create mode 100644 content/turkish/words/net/images-and-shapes/_index.md create mode 100644 content/turkish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/urdu/words/_index.md create mode 100644 content/urdu/words/net/_index.md create mode 100644 content/urdu/words/net/getting-started/_index.md create mode 100644 content/urdu/words/net/getting-started/tutorial/_index.md create mode 100644 content/urdu/words/net/images-and-shapes/_index.md create mode 100644 content/urdu/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md create mode 100644 content/vietnamese/words/_index.md create mode 100644 content/vietnamese/words/net/_index.md create mode 100644 content/vietnamese/words/net/getting-started/_index.md create mode 100644 content/vietnamese/words/net/getting-started/tutorial/_index.md create mode 100644 content/vietnamese/words/net/images-and-shapes/_index.md create mode 100644 content/vietnamese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md diff --git a/content/arabic/words/_index.md b/content/arabic/words/_index.md new file mode 100644 index 000000000..da9729292 --- /dev/null +++ b/content/arabic/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "arabic" +type: "family" +--- + +# Words Tutorials diff --git a/content/arabic/words/net/_index.md b/content/arabic/words/net/_index.md new file mode 100644 index 000000000..68ce0d754 --- /dev/null +++ b/content/arabic/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "arabic" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/arabic/words/net/getting-started/_index.md b/content/arabic/words/net/getting-started/_index.md new file mode 100644 index 000000000..18c09bf46 --- /dev/null +++ b/content/arabic/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "arabic" +type: "category" +--- + +# Getting Started diff --git a/content/arabic/words/net/getting-started/tutorial/_index.md b/content/arabic/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..0833f2959 --- /dev/null +++ b/content/arabic/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: ar +url: /arabic/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# اكتشاف الخطوط المفقودة في مستندات Aspose.Words – دليل كامل بلغة C# + +هل تساءلت يومًا كيف **تكتشف الخطوط المفقودة** عند تحميل ملف Word باستخدام Aspose.Words؟ في عملي اليومي، صادفت بعض ملفات PDF التي بدت غير صحيحة لأن المستند الأصلي استخدم خطًا لم يكن مثبتًا على جهازّي. الخبر السار؟ Aspose.Words يمكنه إخبارك بالضبط عندما يستبدل خطًا، ويمكنك التقاط هذه المعلومة عبر رد نداء تحذير بسيط. + +في هذا الدرس سنستعرض **مثالًا كاملاً قابلاً للتنفيذ** يوضح لك كيفية تسجيل كل استبدال للخط، ولماذا يُعد رد النداء مهمًا، وبعض الحيل الإضافية لاكتشاف الخطوط المفقودة بشكل موثوق. لا إطالة، فقط الشيفرة والمنطق الذي تحتاجه لتجعلها تعمل اليوم. + +--- + +## ما ستتعلمه + +- كيفية تنفيذ **رد نداء تحذير Aspose.Words** لالتقاط أحداث استبدال الخط. +- كيفية ضبط **LoadOptions في C#** بحيث يتم استدعاء رد النداء أثناء تحميل المستند. +- كيفية التحقق من أن اكتشاف الخط المفقود قد نجح، وما هو شكل مخرجات وحدة التحكم. +- تعديلات اختيارية للمعالجة على دفعات كبيرة أو في بيئات بدون واجهة رسومية. + +**المتطلبات المسبقة** – تحتاج إلى نسخة حديثة من Aspose.Words for .NET (تم اختبار الشيفرة مع الإصدار 23.12)، .NET 6 أو أحدث، وفهم أساسي للغة C#. إذا كان لديك ذلك، فأنت جاهز للبدء. + +--- + +## اكتشاف الخطوط المفقودة عبر رد نداء التحذير + +جوهر الحل هو تنفيذ `IWarningCallback`. تقوم Aspose.Words بإطلاق كائن `WarningInfo` للعديد من الحالات، لكننا نهتم فقط بـ `WarningType.FontSubstitution`. دعنا نرى كيف نربط ذلك. + +### الخطوة 1: إنشاء جامع تحذيرات الخطوط + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*لماذا هذا مهم*: من خلال تصفية `WarningType.FontSubstitution` نتجنب الفوضى الناتجة عن التحذيرات غير ذات الصلة (مثل الميزات المهجورة). يحتوي `info.Description` بالفعل على اسم الخط الأصلي والبديل المستخدم، مما يمنحك سجلًا واضحًا. + +--- + +## ضبط LoadOptions لاستخدام رد النداء + +الآن نخبر Aspose.Words باستخدام جامعنا عند تحميل ملف. + +### الخطوة 2: إعداد LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*لماذا هذا مهم*: `LoadOptions` هو المكان الوحيد الذي يمكنك فيه توصيل رد النداء، كلمات مرور التشفير، وسلوكيات التحميل الأخرى. إبقاء ذلك منفصلًا عن مُنشئ `Document` يجعل الشيفرة قابلة لإعادة الاستخدام عبر ملفات متعددة. + +--- + +## تحميل المستند والتقاط الخطوط المفقودة + +مع ربط رد النداء، الخطوة التالية هي ببساطة تحميل المستند. + +### الخطوة 3: تحميل ملف DOCX (أو أي تنسيق مدعوم) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +عند قيام مُنشئ `Document` بتحليل الملف، أي خط مفقود سيُفعّل `FontWarningCollector` الخاص بنا. ستظهر سطر في وحدة التحكم مثل: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +هذا السطر هو الدليل الملموس على أن **اكتشاف الخطوط المفقودة** قد نجح. + +--- + +## التحقق من المخرجات – ما المتوقع + +شغّل البرنامج من الطرفية أو من Visual Studio. إذا كان المستند الأصلي يحتوي على خط غير مثبت لديك، سترى على الأقل سطرًا واحدًا من “Font substituted”. إذا كان المستند يستخدم خطوطًا مثبتة فقط، سيبقى رد النداء صامتًا وستظهر لك رسالة “Document loaded successfully.” فقط. + +**نصيحة**: لتتأكد مرة أخرى، افتح ملف Word في Microsoft Word وانظر إلى قائمة الخطوط. أي خط يظهر في *Replace Fonts* ضمن مجموعة *Home → Font* هو مرشح محتمل للاستبدال. + +--- + +## متقدم: اكتشاف الخطوط المفقودة على نطاق واسع + +غالبًا ما تحتاج إلى فحص العشرات من الملفات. النمط نفسه يتوسع بسهولة: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +نظرًا لأن `FontWarningCollector` يكتب إلى وحدة التحكم في كل مرة يُستدعى فيها، ستحصل على تقرير لكل ملف دون أي تعقيدات إضافية. في سيناريوهات الإنتاج قد ترغب في تسجيل النتائج إلى ملف أو قاعدة بيانات – ما عليك سوى استبدال `Console.WriteLine` بمسجلك المفضل. + +--- + +## الأخطاء الشائعة & النصائح الاحترافية + +| المشكلة | لماذا يحدث | الحل | +|-------|----------------|-----| +| **عدم ظهور أي تحذيرات** | المستند في الواقع يحتوي فقط على خطوط مثبتة. | تحقق بفتح الملف في Word أو بإزالة خط عمدًا من نظامك. | +| **عدم استدعاء رد النداء** | لم يتم تعيين `LoadOptions.WarningCallback` أو تم استخدام كائن `LoadOptions` جديد لاحقًا. | احتفظ بكائن `LoadOptions` واحد وأعد استخدامه لكل عملية تحميل. | +| **الكثير من التحذيرات غير ذات صلة** | لم تقم بتصفية `WarningType.FontSubstitution`. | أضف شرط `if (info.Type == WarningType.FontSubstitution)` كما هو موضح. | +| **تباطؤ الأداء على ملفات ضخمة** | يعمل رد النداء على كل تحذير، وقد يكون عددها كبيرًا في المستندات الكبيرة. | عطل أنواع التحذيرات الأخرى عبر `LoadOptions.WarningCallback` أو حدد `LoadOptions.LoadFormat` لنوع محدد إذا كنت تعرفه. | + +--- + +## مثال كامل جاهز للنسخ واللصق + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**مخرجات وحدة التحكم المتوقعة** (عند مواجهة خط مفقود): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +إذا لم يحدث استبدال، سترى فقط سطر النجاح. + +--- + +## الخلاصة + +أصبح لديك الآن **طريقة كاملة وجاهزة للإنتاج لاكتشاف الخطوط المفقودة** في أي مستند يعالجه Aspose.Words. من خلال الاستفادة من **رد نداء التحذير في Aspose.Words** وضبط **LoadOptions في C#**، يمكنك تسجيل كل استبدال للخط، حل مشاكل التخطيط، وضمان أن ملفات PDF تحتفظ بالمظهر المقصود. + +من ملف واحد إلى دفعة ضخمة، يبقى النمط هو نفسه—نفّذ `IWarningCallback`، اربطه بـ `LoadOptions`، ودع Aspose.Words يتولى الجزء الصعب. + +هل أنت مستعد للخطوة التالية؟ جرّب دمج هذا مع **تضمين الخطوط** أو **عائلات الخطوط الاحتياطية** لإصلاح المشكلة تلقائيًا، أو استكشف واجهة **DocumentVisitor** لتحليل أعمق للمحتوى. برمجة سعيدة، ولتظل خطوطك دائمًا في مكانها المتوقع! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/arabic/words/net/images-and-shapes/_index.md b/content/arabic/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..50146b459 --- /dev/null +++ b/content/arabic/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "arabic" +type: "category" +--- + +# Images And Shapes diff --git a/content/arabic/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/arabic/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..99d4fcbd5 --- /dev/null +++ b/content/arabic/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2025-12-08 +description: أضف ظلًا إلى الشكل بسرعة باستخدام Aspose.Words. تعلّم كيفية إنشاء مستند + Word باستخدام Aspose، وكيفية إضافة ظل للشكل، وتطبيق شفافية الظل في C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: ar +og_description: إضافة ظل إلى الشكل في ملف Word باستخدام Aspose.Words. يوضح هذا الدليل + خطوة بخطوة كيفية إنشاء مستند، إضافة شكل، وتطبيق شفافية الظل. +og_title: إضافة ظل إلى الشكل – دليل Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: إضافة ظل إلى الشكل في مستند Word – دليل Aspose.Words الكامل +url: /arabic/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# إضافة ظل إلى الشكل – دليل Aspose.Words الكامل + +هل احتجت يومًا إلى **إضافة ظل إلى الشكل** في ملف Word لكن لم تكن متأكدًا من أي استدعاءات API تستخدم؟ لست وحدك. يواجه العديد من المطورين صعوبة عندما يحاولون لأول مرة إعطاء مستطيل أو أي عنصر رسم ظلًا مناسبًا، خاصةً عندما يعملون مع Aspose.Words لـ .NET. + +في هذا الدرس سنستعرض كل ما تحتاج معرفته: من **إنشاء مستند Word باستخدام Aspose** إلى تكوين الظل، تعديل الضبابية، المسافة، الزاوية، وحتى **تطبيق شفافية الظل**. في النهاية ستحصل على برنامج C# جاهز للتنفيذ ينتج ملف `.docx` يحتوي على مستطيل مظلل بشكل جميل—دون الحاجة إلى تعديل يدوي في Word. + +--- + +## ما ستتعلمه + +- كيفية إعداد مشروع Aspose.Words في Visual Studio. +- الخطوات الدقيقة **لإنشاء مستند Word باستخدام Aspose** وإدراج شكل. +- **كيفية إضافة ظل إلى الشكل** مع تحكم كامل في الضبابية، المسافة، الزاوية، والشفافية. +- نصائح لاستكشاف الأخطاء الشائعة (مثل: فقدان الترخيص، الوحدات غير الصحيحة). +- عينة كود كاملة قابلة للنسخ واللصق يمكنك تشغيلها اليوم. + +> **المتطلبات المسبقة:** .NET 6+ (أو .NET Framework 4.7.2+)، ترخيص Aspose.Words صالح (أو النسخة التجريبية المجانية)، ومعرفة أساسية بـ C#. + +--- + +## الخطوة 1 – إعداد مشروعك وإضافة Aspose.Words + +أولًا، افتح Visual Studio، أنشئ تطبيق **Console App (.NET Core)** جديد، وأضف حزمة NuGet الخاصة بـ Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **نصيحة احترافية:** إذا كان لديك ملف ترخيص (`Aspose.Words.lic`)، انسخه إلى جذر المشروع وحمّله عند بدء التشغيل. هذا يمنع ظهور العلامة المائية في وضع التقييم المجاني. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## الخطوة 2 – إنشاء مستند فارغ جديد + +الآن سنقوم فعليًا **بإنشاء مستند Word باستخدام Aspose**. هذا الكائن سيعمل كقماش لأشكالنا. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +فئة `Document` هي نقطة الدخول لكل شيء آخر—الفقرات، الأقسام، وبالطبع كائنات الرسم. + +--- + +## الخطوة 3 – إدراج شكل مستطيل + +مع جاهزية المستند، يمكننا إضافة شكل. هنا نختار مستطيلًا بسيطًا، لكن نفس المنطق يعمل مع الدوائر، الخطوط، أو المضلع المخصص. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **لماذا الشكل؟** في Aspose.Words يمكن لكائن `Shape` أن يحمل نصًا أو صورًا أو يعمل كعنصر زخرفي فقط. إضافة ظل إلى الشكل أسهل بكثير من محاولة تعديل إطار الصورة. + +--- + +## الخطوة 4 – تكوين الظل (إضافة ظل إلى الشكل) + +هذا هو جوهر الدرس—**كيفية إضافة ظل إلى الشكل** وضبط مظهره بدقة. خاصية `ShadowFormat` تمنحك تحكمًا كاملاً. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### ما الذي تفعله كل خاصية + +| الخاصية | التأثير | القيم النموذجية | +|----------|--------|----------------| +| **Visible** | تشغيل أو إيقاف الظل. | `true` / `false` | +| **Blur** | ينعم حواف الظل. | `0` (قاسي) إلى `10` (ناعم جدًا) | +| **Distance** | ينقل الظل بعيدًا عن الشكل. | `1`–`5` نقاط شائعًا | +| **Angle** | يتحكم في اتجاه الإزاحة. | `0`–`360` درجة | +| **Transparency** | يجعل الظل شبه شفاف. | `0` (معتم) إلى `1` (غير مرئي) | + +> **حالة خاصة:** إذا ضبطت `Transparency` على `1`، يختفي الظل تمامًا—مفيد لتبديله برمجيًا. + +--- + +## الخطوة 5 – إضافة الشكل إلى المستند + +نقوم الآن بربط الشكل بالفقرة الأولى في جسم المستند. يقوم Aspose بإنشاء فقرة تلقائيًا إذا لم توجد. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +إذا كان المستند يحتوي بالفعل على محتوى، يمكنك إدراج الشكل في أي عقدة باستخدام `InsertAfter` أو `InsertBefore`. + +--- + +## الخطوة 6 – حفظ المستند + +أخيرًا، اكتب الملف إلى القرص. يمكنك اختيار أي تنسيق مدعوم (`.docx`, `.pdf`, `.odt`, إلخ)، لكن لهذا الدرس سنبقى على تنسيق Word الأصلي. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +افتح الملف الناتج `ShadowedShape.docx` في Microsoft Word، وسترى مستطيلًا بظل ناعم بزاوية 45 درجة وشفافية 30 %—تمامًا ما قمنا بتكوينه. + +--- + +## مثال كامل يعمل + +فيما يلي البرنامج **الكامل القابل للنسخ واللصق** الذي يجمع جميع الخطوات السابقة. احفظه باسم `Program.cs` وشغّله باستخدام `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**الناتج المتوقع:** ملف باسم `ShadowedShape.docx` يحتوي على مستطيل واحد بظل خفيف شبه شفاف مائل بزاوية 45°. + +--- + +## تنويعات ونصائح متقدمة + +### تغيير لون الظل + +بشكل افتراضي يرث الظل لون تعبئة الشكل، لكن يمكنك تعيين لون مخصص: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### أشكال متعددة بظلال مختلفة + +إذا احتجت إلى عدة أشكال، كرّر خطوات الإنشاء والتكوين. تذكر إعطاء كل شكل اسمًا فريدًا إذا كنت تخطط للإشارة إليه لاحقًا. + +### تصدير إلى PDF مع الحفاظ على الظلال + +يحافظ Aspose.Words على تأثيرات الظل عند الحفظ إلى PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### مشكلات شائعة + +| العَرَض | السبب المحتمل | الحل | +|---------|--------------|-----| +| الظل غير مرئي | ترك `ShadowFormat.Visible` على `false` | ضبطه إلى `true`. | +| الظل يبدو قاسيًا جدًا | ضبط `Blur` على `0` | زيادة `Blur` إلى 3–6. | +| الظل يختفي في PDF | استخدام نسخة قديمة من Aspose.Words (< 22.9) | الترقية إلى أحدث مكتبة. | + +--- + +## الخلاصة + +غطّينا **كيفية إضافة ظل إلى الشكل** باستخدام Aspose.Words، من تهيئة المستند إلى ضبط الضبابية، المسافة، الزاوية، و**تطبيق شفافية الظل**. المثال الكامل يوضح نهجًا نظيفًا وجاهزًا للإنتاج يمكنك تكييفه مع أي شكل أو تخطيط مستند. + +هل لديك أسئلة حول **إنشاء مستند Word باستخدام Aspose** لسيناريوهات أكثر تعقيدًا—مثل الجداول ذات الظلال أو الأشكال الديناميكية المستندة إلى البيانات؟ اترك تعليقًا أدناه أو اطلع على الدروس ذات الصلة حول معالجة الصور في Aspose.Words وتنسيق الفقرات. + +برمجة سعيدة، واستمتع بإضفاء لمسة بصرية إضافية على مستندات Word الخاصة بك! + +--- + +![مثال على إضافة ظل إلى الشكل](shadowed_shape.png "مثال على إضافة ظل إلى الشكل") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/chinese/words/_index.md b/content/chinese/words/_index.md new file mode 100644 index 000000000..78f5a39d0 --- /dev/null +++ b/content/chinese/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "chinese" +type: "family" +--- + +# Words Tutorials diff --git a/content/chinese/words/net/_index.md b/content/chinese/words/net/_index.md new file mode 100644 index 000000000..9bf0c455d --- /dev/null +++ b/content/chinese/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "chinese" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/chinese/words/net/getting-started/_index.md b/content/chinese/words/net/getting-started/_index.md new file mode 100644 index 000000000..d2e8e3c45 --- /dev/null +++ b/content/chinese/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "chinese" +type: "category" +--- + +# Getting Started diff --git a/content/chinese/words/net/getting-started/tutorial/_index.md b/content/chinese/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..07126e624 --- /dev/null +++ b/content/chinese/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: zh +url: /chinese/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# 检测 Aspose.Words 文档中缺失的字体 – 完整 C# 指南 + +有没有想过在使用 Aspose.Words 加载 Word 文件时 **检测缺失的字体**?在我的日常工作中,我遇到过一些 PDF 看起来怪怪的,因为原始文档使用了我系统中未安装的字体。好消息是?Aspose.Words 可以准确告知何时替换了字体,并且你可以通过一个简单的警告回调捕获这些信息。 + +在本教程中,我们将演示一个 **完整、可运行的示例**,展示如何记录每一次字体替换、回调为何重要,以及一些额外的技巧,以实现稳健的缺失字体检测。没有废话,只提供代码和你今天就能使用的思路。 + +--- + +## 你将学到 + +- 如何实现 **Aspose.Words 警告回调** 来捕获字体替换事件。 +- 如何配置 **LoadOptions C#** 使回调在加载文档时被触发。 +- 如何验证缺失字体检测是否真正生效,以及控制台输出的样子。 +- 大批量或无头环境下的可选调整。 + +**先决条件** – 需要最近版本的 Aspose.Words for .NET(代码在 23.12 版本上测试通过),.NET 6 或更高版本,以及基本的 C# 认识。如果你满足这些条件,就可以开始了。 + +--- + +## 使用警告回调检测缺失字体 + +解决方案的核心是实现 `IWarningCallback`。Aspose.Words 会为多种情况抛出 `WarningInfo` 对象,但我们只关心 `WarningType.FontSubstitution`。下面看看如何挂接它。 + +### 步骤 1:创建字体警告收集器 + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*为什么重要*:通过过滤 `WarningType.FontSubstitution`,我们可以避免来自不相关警告(如已弃用功能)的噪音。`info.Description` 已经包含了原始字体名称和使用的回退字体,为你提供清晰的审计轨迹。 + +--- + +## 配置 LoadOptions 使用回调 + +现在告诉 Aspose.Words 在加载文件时使用我们的收集器。 + +### 步骤 2:设置 LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*为什么重要*:`LoadOptions` 是唯一可以插入回调、加密密码以及其他加载行为的地方。将其与 `Document` 构造函数分离,使代码能够在多个文件之间复用。 + +--- + +## 加载文档并捕获缺失字体 + +回调已经接好,接下来只需加载文档。 + +### 步骤 3:加载你的 DOCX(或任何受支持的格式) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +当 `Document` 构造函数解析文件时,任何缺失的字体都会触发我们的 `FontWarningCollector`。控制台会显示类似下面的行: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +这行就是 **检测缺失字体** 成功的具体证据。 + +--- + +## 验证输出 – 预期结果 + +在终端或 Visual Studio 中运行程序。如果源文档使用了系统未安装的字体,你会看到至少一行 “Font substituted”。如果文档只使用已安装的字体,回调保持沉默,你只会看到 “Document loaded successfully.” 的信息。 + +**小技巧**:双重检查时,在 Microsoft Word 中打开该文件并查看字体列表。任何出现在 *Replace Fonts*(替换字体)下的 *Home → Font* 组中的字体,都可能被替换。 + +--- + +## 高级:批量检测缺失字体 + +通常需要扫描数十个文件。同样的模式可以很好地扩展: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +因为 `FontWarningCollector` 每次被调用时都会写入控制台,你可以在不额外编写代码的情况下获得每个文件的报告。对于生产环境,你可能希望将日志写入文件或数据库——只需把 `Console.WriteLine` 换成你喜欢的日志记录器即可。 + +--- + +## 常见陷阱与专业提示 + +| 问题 | 为什么会出现 | 解决方案 | +|------|--------------|----------| +| **没有出现任何警告** | 文档实际上只包含已安装的字体。 | 通过在 Word 中打开文件或故意从系统中移除某个字体进行验证。 | +| **回调未被调用** | 未为 `LoadOptions.WarningCallback` 赋值,或后续使用了新的 `LoadOptions` 实例。 | 保持使用同一个 `LoadOptions` 对象,并在每次加载时复用它。 | +| **出现太多无关警告** | 未对 `WarningType.FontSubstitution` 进行过滤。 | 按示例添加 `if (info.Type == WarningType.FontSubstitution)` 条件。 | +| **在超大文件上性能下降** | 回调会在每个警告上执行,对于大型文档可能数量庞大。 | 通过 `LoadOptions.WarningCallback` 禁用其他警告类型,或在已知格式时设置 `LoadOptions.LoadFormat` 为特定类型。 | + +--- + +## 完整可运行示例(复制粘贴即用) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**预期的控制台输出**(当遇到缺失字体时): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +如果没有发生替换,你只会看到成功提示行。 + +--- + +## 结论 + +现在你拥有了一套 **完整、可投入生产的缺失字体检测方案**,适用于任何使用 Aspose.Words 处理的文档。通过利用 **Aspose.Words 警告回调** 并配置 **LoadOptions C#**,你可以记录每一次字体替换,排查布局问题,确保生成的 PDF 保持预期的外观。 + +从单个文件到大批量处理,模式保持不变——实现 `IWarningCallback`,将其插入 `LoadOptions`,让 Aspose.Words 完成繁重的工作。 + +准备好下一步了吗?尝试将其与 **字体嵌入** 或 **回退字体族** 结合,自动修复问题,或探索 **DocumentVisitor** API 进行更深层次的内容分析。祝编码愉快,愿所有字体都如你所愿! + +--- + +![检测 Aspose.Words 中缺失字体的控制台输出截图](https://example.com/images/detect-missing-fonts.png "检测缺失字体的控制台输出") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/chinese/words/net/images-and-shapes/_index.md b/content/chinese/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..79ef88b3e --- /dev/null +++ b/content/chinese/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "chinese" +type: "category" +--- + +# Images And Shapes diff --git a/content/chinese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/chinese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..fdb7f9cec --- /dev/null +++ b/content/chinese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2025-12-08 +description: 使用 Aspose.Words 快速为形状添加阴影。了解如何使用 Aspose 创建 Word 文档、如何为形状添加阴影以及如何在 C# + 中应用阴影透明度。 +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: zh +og_description: 使用 Aspose.Words 为 Word 文件中的形状添加阴影。本分步指南展示了如何创建文档、添加形状以及应用阴影透明度。 +og_title: 为形状添加阴影 – Aspose.Words C# 教程 +tags: +- Aspose.Words +- C# +- Word Automation +title: 在 Word 文档中为形状添加阴影 – 完整的 Aspose.Words 指南 +url: /chinese/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# 为形状添加阴影 – 完整 Aspose.Words 指南 + +是否曾经需要在 Word 文件中 **add shadow to shape**,但不确定该使用哪些 API 调用?你并不孤单。许多开发者在首次尝试为矩形或任何绘图元素添加合适的投影时会遇到障碍,尤其是在使用 Aspose.Words for .NET 时。 + +在本教程中,我们将逐步讲解您需要了解的所有内容:从 **create Word document using Aspose** 到配置阴影、调整模糊程度、距离、角度,甚至 **apply shadow transparency**。结束时,您将拥有一个可直接运行的 C# 程序,生成带有精美阴影矩形的 `.docx` 文件——无需在 Word 中手动操作。 + +--- + +## 您将学习的内容 + +- 如何在 Visual Studio 中设置 Aspose.Words 项目。 +- 使用 Aspose **create Word document using Aspose** 并插入形状的确切步骤。 +- **How to add shape shadow**,并全面控制模糊、距离、角度和透明度。 +- 常见陷阱的故障排除技巧(例如,缺少许可证、单位错误)。 +- 一个完整的、可直接复制粘贴的代码示例,您今天即可运行。 + +> **先决条件:** .NET 6+(或 .NET Framework 4.7.2+),有效的 Aspose.Words 许可证(或免费试用),以及对 C# 的基本了解。 + +--- + +## 第一步 – 设置项目并添加 Aspose.Words + +首先,打开 Visual Studio,创建一个新的 **Console App (.NET Core)**,并添加 Aspose.Words NuGet 包: + +```bash +dotnet add package Aspose.Words +``` + +> **专业提示:** 如果您有许可证文件 (`Aspose.Words.lic`),请将其复制到项目根目录并在启动时加载。这可以避免免费评估模式下出现的水印。 + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## 第二步 – 创建一个新的空白文档 + +现在我们实际 **create Word document using Aspose**。该对象将作为我们形状的画布。 + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` 类是其他所有内容的入口——段落、节,当然还有绘图对象。 + +--- + +## 第三步 – 插入矩形形状 + +文档准备好后,我们可以添加形状。这里我们选择一个简单的矩形,但相同的逻辑也适用于圆形、直线或自定义多边形。 + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **为什么使用形状?** 在 Aspose.Words 中,`Shape` 对象可以容纳文本、图像,或仅作为装饰元素。为形状添加阴影比尝试操作图片框要容易得多。 + +--- + +## 第四步 – 配置阴影(Add Shadow to Shape) + +这是本教程的核心——**how to add shape shadow** 并微调其外观。`ShadowFormat` 属性让您拥有完整的控制权。 + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### 各属性功能说明 + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | 打开或关闭阴影。 | `true` / `false` | +| **Blur** | 软化阴影边缘。 | `0` (hard) to `10` (very soft) | +| **Distance** | 将阴影从形状移开。 | `1`–`5` points is common | +| **Angle** | 控制偏移方向。 | `0`–`360` degrees | +| **Transparency** | 使阴影部分透明。 | `0` (opaque) to `1` (invisible) | + +> **边缘情况:** 如果将 `Transparency` 设置为 `1`,阴影会完全消失——这在程序化切换时很有用。 + +--- + +## 第五步 – 将形状添加到文档 + +我们现在将形状附加到文档正文的第一个段落。若不存在段落,Aspose 会自动创建。 + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +如果文档已经包含内容,您可以使用 `InsertAfter` 或 `InsertBefore` 在任意节点插入形状。 + +--- + +## 第六步 – 保存文档 + +最后,将文件写入磁盘。您可以选择任何受支持的格式(`.docx`、`.pdf`、`.odt` 等),但在本教程中我们将使用原生 Word 格式。 + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +在 Microsoft Word 中打开生成的 `ShadowedShape.docx`,您会看到一个带有柔和 45 度阴影且透明度为 30% 的矩形——正是我们配置的效果。 + +--- + +## 完整工作示例 + +下面是 **完整、可直接复制粘贴** 的程序,包含上述所有步骤。将其保存为 `Program.cs` 并使用 `dotnet run` 运行。 + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**预期输出:** 一个名为 `ShadowedShape.docx` 的文件,包含一个带有细微半透明、45° 角投影的单个矩形。 + +--- + +## 变体与高级技巧 + +### 更改阴影颜色 + +默认情况下,阴影继承形状的填充颜色,但您可以设置自定义颜色: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 多个形状及不同阴影 + +如果需要多个形状,只需重复创建和配置步骤。如果计划稍后引用,请记得为每个形状分配唯一名称。 + +### 导出为 PDF 并保留阴影 + +Aspose.Words 在保存为 PDF 时会保留阴影效果: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### 常见陷阱 + +| 症状 | 可能原因 | 解决方案 | +|------|----------|----------| +| 阴影未显示 | `ShadowFormat.Visible` 保持为 `false` | 设置为 `true`。 | +| 阴影看起来太硬 | `Blur` 设置为 `0` | 将 `Blur` 提高到 3–6。 | +| PDF 中阴影消失 | 使用旧版 Aspose.Words (< 22.9) | 升级到最新库。 | + +--- + +## 结论 + +我们已经介绍了使用 Aspose.Words **how to add shadow to shape** 的完整过程,从初始化文档到微调模糊、距离、角度以及 **apply shadow transparency**。完整示例展示了一种简洁、可投入生产的做法,您可以将其应用于任何形状或文档布局。 + +如果您对更复杂场景下的 **create word document using aspose**(例如带阴影的表格或动态数据驱动的形状)有疑问,请在下方留言或查看 Aspose.Words 图像处理和段落格式化的相关教程。 + +祝编码愉快,尽情为您的 Word 文档增添额外的视觉光彩! + +--- + +![为形状添加阴影示例](shadowed_shape.png "为形状添加阴影示例") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/czech/words/_index.md b/content/czech/words/_index.md new file mode 100644 index 000000000..404ad64ce --- /dev/null +++ b/content/czech/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "czech" +type: "family" +--- + +# Words Tutorials diff --git a/content/czech/words/net/_index.md b/content/czech/words/net/_index.md new file mode 100644 index 000000000..8f5c94660 --- /dev/null +++ b/content/czech/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "czech" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/czech/words/net/getting-started/_index.md b/content/czech/words/net/getting-started/_index.md new file mode 100644 index 000000000..210240a01 --- /dev/null +++ b/content/czech/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "czech" +type: "category" +--- + +# Getting Started diff --git a/content/czech/words/net/getting-started/tutorial/_index.md b/content/czech/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..b2909d644 --- /dev/null +++ b/content/czech/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: cs +url: /czech/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Detekce chybějících fontů v dokumentech Aspose.Words – kompletní průvodce v C# + +Už jste se někdy zamýšleli, jak **detekovat chybějící fonty**, když načítáte soubor Word pomocí Aspose.Words? Ve své každodenní práci jsem narazil na několik PDF, které vypadaly špatně, protože původní dokument používal font, který jsem neměl nainstalovaný. Dobrá zpráva? Aspose.Words vám může přesně říct, kdy nahrazuje font, a tuto informaci můžete zachytit pomocí jednoduchého callbacku pro varování. + +V tomto tutoriálu projdeme **kompletním, spustitelným příkladem**, který vám ukáže, jak zaznamenat každou substituci fontu, proč je callback důležitý, a pár dalších triků pro spolehlivou detekci chybějících fontů. Žádné zbytečnosti, jen kód a úvahy, které potřebujete k okamžitému fungování. + +--- + +## Co se naučíte + +- Jak implementovat **Aspose.Words warning callback** pro zachycení událostí substituce fontu. +- Jak nakonfigurovat **LoadOptions C#**, aby byl callback vyvolán při načítání dokumentu. +- Jak ověřit, že detekce chybějících fontů skutečně funguje, a jak vypadá výstup v konzoli. +- Volitelné úpravy pro velké dávky nebo headless prostředí. + +**Požadavky** – Potřebujete aktuální verzi Aspose.Words pro .NET (kód byl testován s verzí 23.12), .NET 6 nebo novější a základní znalost C#. Pokud to máte, můžete začít. + +--- + +## Detekce chybějících fontů pomocí warning callbacku + +Jádrem řešení je implementace `IWarningCallback`. Aspose.Words vyvolá objekt `WarningInfo` pro mnoho situací, ale nás zajímá pouze `WarningType.FontSubstitution`. Podívejme se, jak se na to napojit. + +### Krok 1: Vytvořte sběrač varování o fontech + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Proč je to důležité*: Filtrováním na `WarningType.FontSubstitution` se vyhneme nepořádku od nesouvisejících varování (např. zastaralých funkcí). `info.Description` již obsahuje původní název fontu a použité náhradní písmo, což vám poskytuje jasný auditní záznam. + +--- + +## Nastavení LoadOptions pro použití callbacku + +Nyní řekneme Aspose.Words, aby při načítání souboru použil náš sběrač. + +### Krok 2: Nastavte LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Proč je to důležité*: `LoadOptions` je jediné místo, kde můžete připojit callback, šifrovací hesla a další chování při načítání. Udržení odděleného od konstruktoru `Document` činí kód znovupoužitelným pro mnoho souborů. + +--- + +## Načtení dokumentu a zachycení chybějících fontů + +S nastaveným callbackem je dalším krokem jednoduše načíst dokument. + +### Krok 3: Načtěte svůj DOCX (nebo jakýkoli podporovaný formát) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Když konstruktor `Document` parsuje soubor, jakýkoli chybějící font spustí náš `FontWarningCollector`. Konzole zobrazí řádky jako: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Tento řádek je konkrétním důkazem, že **detekce chybějících fontů** fungovala. + +--- + +## Ověření výstupu – co očekávat + +Spusťte program z terminálu nebo Visual Studio. Pokud zdrojový dokument obsahuje font, který nemáte nainstalovaný, uvidíte alespoň jeden řádek „Font substituted“. Pokud dokument používá pouze nainstalované fonty, callback zůstane tichý a zobrazí se pouze zpráva „Document loaded successfully.“ + +**Tip**: Pro dvojitou kontrolu otevřete soubor Word v Microsoft Word a podívejte se na seznam fontů. Jakýkoli font, který se objeví v *Replace Fonts* pod skupinou *Home → Font*, je kandidátem na substituci. + +--- + +## Pokročilé: Detekce chybějících fontů ve velkém měřítku + +Často potřebujete prohledat desítky souborů. Stejný vzor se dobře škáluje: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Protože `FontWarningCollector` zapisuje do konzole při každém vyvolání, získáte zprávu pro každý soubor bez dalšího kódu. Pro produkční scénáře můžete chtít logovat do souboru nebo databáze – stačí nahradit `Console.WriteLine` vaším preferovaným loggerem. + +--- + +## Časté úskalí a profesionální tipy + +| Problém | Proč se to stane | Řešení | +|-------|----------------|-----| +| **Neobjeví se žádná varování** | Dokument ve skutečnosti obsahuje pouze nainstalované fonty. | Ověřte otevřením souboru ve Wordu nebo úmyslným odebráním fontu ze systému. | +| **Callback není volán** | `LoadOptions.WarningCallback` nebyl nikdy přiřazen nebo byla později použita nová instance `LoadOptions`. | Udržujte jediný objekt `LoadOptions` a znovu jej používejte pro každé načtení. | +| **Příliš mnoho nesouvisejících varování** | Nefiltrovali jste podle `WarningType.FontSubstitution`. | Přidejte podmínku `if (info.Type == WarningType.FontSubstitution)`, jak je ukázáno. | +| **Zpomalení výkonu u velkých souborů** | Callback se spouští u každého varování, což může být u velkých dokumentů mnoho. | Zakázat jiné typy varování pomocí `LoadOptions.WarningCallback` nebo nastavit `LoadOptions.LoadFormat` na konkrétní typ, pokud jej znáte. | + +--- + +## Plně funkční příklad (připravený ke kopírování) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Očekávaný výstup v konzoli** (když je detekován chybějící font): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Pokud nedojde k žádné substituci, uvidíte pouze řádek s úspěchem. + +--- + +## Závěr + +Nyní máte **kompletní, připravený pro produkci způsob, jak detekovat chybějící fonty** v jakémkoli dokumentu zpracovávaném pomocí Aspose.Words. Využitím **Aspose.Words warning callback** a konfigurací **LoadOptions C#** můžete zaznamenat každou substituci fontu, řešit problémy s rozvržením a zajistit, aby vaše PDF zachovávaly zamýšlený vzhled. + +Od jednoho souboru po obrovskou dávku zůstává vzor stejný — implementujte `IWarningCallback`, připojte jej k `LoadOptions` a nechte Aspose.Words udělat těžkou práci. + +Jste připraveni na další krok? Zkuste kombinovat toto s **font embedding** nebo **fallback font families**, abyste problém automaticky opravili, nebo prozkoumejte API **DocumentVisitor** pro hlubší analýzu obsahu. Šťastné programování a ať všechny vaše fonty zůstávají tam, kde je očekáváte! + +--- + +![Detekce chybějících fontů v Aspose.Words – snímek výstupu v konzoli](https://example.com/images/detect-missing-fonts.png "detekce chybějících fontů výstup v konzoli") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/czech/words/net/images-and-shapes/_index.md b/content/czech/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..d8928a298 --- /dev/null +++ b/content/czech/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "czech" +type: "category" +--- + +# Images And Shapes diff --git a/content/czech/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/czech/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..a5b461481 --- /dev/null +++ b/content/czech/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,249 @@ +--- +category: general +date: 2025-12-08 +description: Rychle přidejte stín k tvaru pomocí Aspose.Words. Naučte se, jak vytvořit + dokument Word pomocí Aspose, jak přidat stín k tvaru a jak nastavit průhlednost + stínu v C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: cs +og_description: Přidejte stín k tvaru v souboru Word pomocí Aspose.Words. Tento krok‑za‑krokem + průvodce ukazuje, jak vytvořit dokument, přidat tvar a nastavit průhlednost stínu. +og_title: Přidat stín k tvaru – Aspose.Words C# tutoriál +tags: +- Aspose.Words +- C# +- Word Automation +title: Přidat stín k tvaru v dokumentu Word – Kompletní průvodce Aspose.Words +url: /czech/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Přidání stínu k tvaru – Kompletní průvodce Aspose.Words + +Už jste někdy potřebovali **přidat stín k tvaru** v souboru Word, ale nebyli jste si jisti, které volání API použít? Nejste v tom sami. Mnoho vývojářů narazí na problém, když poprvé zkusí dát obdélníku nebo jakémukoli kreslenému prvku správný vržený stín, zejména při práci s Aspose.Words pro .NET. + +V tomto tutoriálu projdeme vše, co potřebujete vědět: od **vytvoření Word dokumentu pomocí Aspose** po nastavení stínu, úpravu jeho rozostření, vzdálenosti, úhlu a dokonce **aplikaci průhlednosti stínu**. Na konci budete mít připravený spustitelný C# program, který vytvoří soubor `.docx` s pěkně stínovaným obdélníkem – bez ručního ladění ve Wordu. + +--- + +## Co se naučíte + +- Jak nastavit projekt Aspose.Words ve Visual Studio. +- Přesné kroky k **vytvoření Word dokumentu pomocí Aspose** a vložení tvaru. +- **Jak přidat stín k tvaru** s úplnou kontrolou nad rozostřením, vzdáleností, úhlem a průhledností. +- Tipy pro řešení běžných problémů (např. chybějící licence, nesprávné jednotky). +- Kompletní ukázkový kód ke zkopírování a vložení, který můžete spustit ještě dnes. + +> **Předpoklady:** .NET 6+ (nebo .NET Framework 4.7.2+), platná licence Aspose.Words (nebo bezplatná zkušební verze) a základní znalost C#. + +## Krok 1 – Nastavte svůj projekt a přidejte Aspose.Words + +Nejprve. Otevřete Visual Studio, vytvořte novou **Console App (.NET Core)** a přidejte NuGet balíček Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Tip:** Pokud máte soubor licence (`Aspose.Words.lic`), zkopírujte jej do kořenového adresáře projektu a načtěte jej při spuštění. Tím se vyhnete vodoznaku, který se objevuje v režimu bezplatného hodnocení. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## Krok 2 – Vytvořte nový prázdný dokument + +Nyní skutečně **vytvoříme Word dokument pomocí Aspose**. Tento objekt bude sloužit jako plátno pro náš tvar. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` třída je vstupním bodem pro vše ostatní – odstavce, sekce a samozřejmě kreslené objekty. + +## Krok 3 – Vložte obdélníkový tvar + +Když je dokument připraven, můžeme přidat tvar. Zde volíme jednoduchý obdélník, ale stejná logika funguje i pro kruhy, čáry nebo vlastní mnohoúhelníky. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Proč tvar?** V Aspose.Words objekt `Shape` může obsahovat text, obrázky nebo sloužit jen jako dekorativní prvek. Přidání stínu k tvaru je mnohem jednodušší než pokus o manipulaci s rámečkem obrázku. + +## Krok 4 – Nastavte stín (Přidání stínu k tvaru) + +Toto je jádro tutoriálu – **jak přidat stín k tvaru** a jemně doladit jeho vzhled. Vlastnost `ShadowFormat` vám dává plnou kontrolu. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Co dělá každá vlastnost + +| Vlastnost | Efekt | Typické hodnoty | +|----------|--------|----------------| +| **Visible** | Zapíná nebo vypíná stín. | `true` / `false` | +| **Blur** | Změkčuje hrany stínu. | `0` (hard) to `10` (very soft) | +| **Distance** | Posouvá stín od tvaru. | `1`–`5` points is common | +| **Angle** | Řídí směr posunu. | `0`–`360` degrees | +| **Transparency** | Způsobí, že stín je částečně průhledný. | `0` (opaque) to `1` (invisible) | + +> **Hraniční případ:** Pokud nastavíte `Transparency` na `1`, stín zmizí úplně – užitečné pro programové přepínání. + +## Krok 5 – Přidejte tvar do dokumentu + +Nyní připojíme tvar k prvnímu odstavci těla dokumentu. Aspose automaticky vytvoří odstavec, pokud neexistuje. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Pokud váš dokument již obsahuje obsah, můžete tvar vložit na libovolný uzel pomocí `InsertAfter` nebo `InsertBefore`. + +## Krok 6 – Uložte dokument + +Nakonec zapíšete soubor na disk. Můžete zvolit libovolný podporovaný formát (`.docx`, `.pdf`, `.odt` atd.), ale pro tento tutoriál zůstaneme u nativního formátu Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Otevřete výsledný `ShadowedShape.docx` v Microsoft Word a uvidíte obdélník s měkkým, 45‑stupňovým stínem, který je 30 % průhledný – přesně tak, jak jsme nakonfigurovali. + +## Kompletní funkční příklad + +Níže je **kompletní, připravený ke zkopírování a vložení** program, který zahrnuje všechny výše uvedené kroky. Uložte jej jako `Program.cs` a spusťte pomocí `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Očekávaný výstup:** Soubor pojmenovaný `ShadowedShape.docx` obsahující jeden obdélník s jemným, poloprůhledným vrženým stínem natočeným pod úhlem 45°. + +## Variace a pokročilé tipy + +### Změna barvy stínu + +Ve výchozím nastavení stín dědí barvu výplně tvaru, ale můžete nastavit vlastní barvu: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Více tvarů s různými stíny + +Pokud potřebujete několik tvarů, stačí opakovat kroky vytvoření a konfigurace. Nezapomeňte každému tvaru přiřadit jedinečný název, pokud je budete později odkazovat. + +### Export do PDF se zachovanými stíny + +Aspose.Words zachovává efekty stínů při ukládání do PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Běžné úskalí + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Stín není viditelný | `ShadowFormat.Visible` ponechán jako `false` | Nastavte na `true`. | +| Stín vypadá příliš tvrdě | `Blur` nastaven na `0` | Zvyšte `Blur` na 3–6. | +| Stín zmizí v PDF | Použití staré verze Aspose.Words (< 22.9) | Aktualizujte na nejnovější knihovnu. | + +## Závěr + +Probrali jsme **jak přidat stín k tvaru** pomocí Aspose.Words, od inicializace dokumentu po jemné doladění rozostření, vzdálenosti, úhlu a **aplikaci průhlednosti stínu**. Kompletní příklad ukazuje čistý, připravený na produkci přístup, který můžete přizpůsobit libovolnému tvaru nebo rozložení dokumentu. + +Máte otázky ohledně **create word document using aspose** pro složitější scénáře – například tabulky se stíny nebo dynamicky generované tvary? Zanechte komentář níže nebo se podívejte na související tutoriály o zpracování obrázků a formátování odstavců v Aspose.Words. + +Šťastné programování a užijte si, že vašim Word dokumentům přidáte ten extra vizuální lesk! + +--- + +![příklad přidání stínu k tvaru](shadowed_shape.png "příklad přidání stínu k tvaru") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/dutch/words/_index.md b/content/dutch/words/_index.md new file mode 100644 index 000000000..c192757f0 --- /dev/null +++ b/content/dutch/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "dutch" +type: "family" +--- + +# Words Tutorials diff --git a/content/dutch/words/net/_index.md b/content/dutch/words/net/_index.md new file mode 100644 index 000000000..be597a1c4 --- /dev/null +++ b/content/dutch/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "dutch" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/dutch/words/net/getting-started/_index.md b/content/dutch/words/net/getting-started/_index.md new file mode 100644 index 000000000..40ea882ee --- /dev/null +++ b/content/dutch/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "dutch" +type: "category" +--- + +# Getting Started diff --git a/content/dutch/words/net/getting-started/tutorial/_index.md b/content/dutch/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..cfd3b9148 --- /dev/null +++ b/content/dutch/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: nl +url: /dutch/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Ontdek Ontbrekende Lettertypen in Aspose.Words Documenten – Complete C# Gids + +Heb je je ooit afgevraagd hoe je **ontbrekende lettertypen** kunt **detecteren** wanneer je een Word‑bestand laadt met Aspose.Words? In mijn dagelijkse werk ben ik een paar PDF's tegengekomen die er niet goed uitzagen omdat het oorspronkelijke document een lettertype gebruikte dat ik niet geïnstalleerd had. Het goede nieuws? Aspose.Words kan je precies vertellen wanneer het een lettertype vervangt, en je kunt die informatie vastleggen met een eenvoudige warning‑callback. + +In deze tutorial lopen we een **volledig, uitvoerbaar voorbeeld** door dat laat zien hoe je elke lettertype‑vervanging logt, waarom de callback belangrijk is, en een paar extra trucjes voor robuuste detectie van ontbrekende lettertypen. Geen poespas, alleen de code en de redenering die je nodig hebt om het vandaag werkend te krijgen. + +--- + +## Wat je zult leren + +- Hoe je een **Aspose.Words warning callback** implementeert om font‑substitutie‑gebeurtenissen op te vangen. +- Hoe je **LoadOptions C#** configureert zodat de callback wordt aangeroepen tijdens het laden van een document. +- Hoe je verifieert dat de detectie van ontbrekende lettertypen echt werkt, en hoe de console‑output eruitziet. +- Optionele aanpassingen voor grote batches of headless omgevingen. + +**Prerequisites** – Je hebt een recente versie van Aspose.Words voor .NET nodig (de code is getest met 23.12), .NET 6 of later, en een basisbegrip van C#. Als je die hebt, kun je van start. + +--- + +## Detecteer Ontbrekende Lettertypen met een Warning Callback + +Het hart van de oplossing is een implementatie van `IWarningCallback`. Aspose.Words genereert een `WarningInfo`‑object voor veel situaties, maar we zijn alleen geïnteresseerd in `WarningType.FontSubstitution`. Laten we zien hoe we hierop kunnen inhaken. + +### Stap 1: Maak een Font‑Warning Collector + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Waarom dit belangrijk is*: Door te filteren op `WarningType.FontSubstitution` vermijden we rommel van niet‑gerelateerde waarschuwingen (zoals verouderde functies). De `info.Description` bevat al de oorspronkelijke lettertype‑naam en de gebruikte fallback, waardoor je een duidelijk audit‑pad hebt. + +--- + +## Configureer LoadOptions om de Callback te Gebruiken + +Nu vertellen we Aspose.Words om onze collector te gebruiken wanneer het een bestand laadt. + +### Stap 2: Stel LoadOptions In + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Waarom dit belangrijk is*: `LoadOptions` is de enige plek waar je de callback, encryptiewachtwoorden en andere laad‑gedragingen kunt aansluiten. Het gescheiden houden van de `Document`‑constructor maakt de code herbruikbaar voor vele bestanden. + +--- + +## Laad het Document en Leg Ontbrekende Lettertypen Vast + +Met de callback aangesloten is de volgende stap simpelweg het document laden. + +### Stap 3: Laad je DOCX (of elk ondersteund formaat) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Wanneer de `Document`‑constructor het bestand parseert, triggert elk ontbrekend lettertype onze `FontWarningCollector`. De console toont regels zoals: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Die regel is het concrete bewijs dat **ontbrekende lettertypen detecteren** heeft gewerkt. + +--- + +## Verifieer de Output – Wat te Verwachten + +Voer het programma uit vanuit een terminal of Visual Studio. Als het bron‑document een lettertype bevat dat je niet geïnstalleerd hebt, zie je minstens één regel “Font substituted”. Als het document alleen geïnstalleerde lettertypen gebruikt, blijft de callback stil en krijg je alleen het bericht “Document loaded successfully.”. + +**Tip**: Om dubbel te controleren, open het Word‑bestand in Microsoft Word en bekijk de lettertype‑lijst. Elk lettertype dat verschijnt in *Replace Fonts* onder de *Home → Font*‑groep is een kandidaat voor substitutie. + +--- + +## Geavanceerd: Detecteer Ontbrekende Lettertypen in Bulk + +Vaak moet je tientallen bestanden scannen. Hetzelfde patroon schaalt mooi: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Omdat de `FontWarningCollector` elke keer dat hij wordt aangeroepen naar de console schrijft, krijg je een per‑bestand rapport zonder extra infrastructuur. Voor productiescenario's wil je misschien naar een bestand of een database loggen – vervang simpelweg `Console.WriteLine` door je voorkeurslogger. + +--- + +## Veelvoorkomende Valkuilen & Pro‑Tips + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Geen waarschuwingen verschijnen** | Het document bevat in feite alleen geïnstalleerde lettertypen. | Controleer door het bestand in Word te openen of door opzettelijk een lettertype van je systeem te verwijderen. | +| **Callback niet aangeroepen** | `LoadOptions.WarningCallback` was nooit toegewezen of er later een nieuw `LoadOptions`‑object werd gebruikt. | Bewaar één `LoadOptions`‑object en hergebruik het voor elke load. | +| **Te veel niet‑gerelateerde waarschuwingen** | Je filterde niet op `WarningType.FontSubstitution`. | Voeg de `if (info.Type == WarningType.FontSubstitution)`‑guard toe zoals getoond. | +| **Prestatie‑vertraging bij enorme bestanden** | De callback wordt uitgevoerd bij elke waarschuwing, wat er veel kan zijn voor grote documenten. | Schakel andere waarschuwingstypen uit via `LoadOptions.WarningCallback` of stel `LoadOptions.LoadFormat` in op een specifiek type als je dat weet. | + +--- + +## Volledig Werkend Voorbeeld (Klaar om te Kopiëren‑Plakken) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Verwachte console‑output** (wanneer een ontbrekend lettertype wordt aangetroffen): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Als er geen substitutie plaatsvindt, zie je alleen de succesregel. + +--- + +## Conclusie + +Je hebt nu een **volledige, productie‑klare manier om ontbrekende lettertypen te detecteren** in elk document dat door Aspose.Words wordt verwerkt. Door gebruik te maken van de **Aspose.Words warning callback** en het configureren van **LoadOptions C#**, kun je elke lettertype‑substitutie loggen, lay‑outproblemen oplossen en ervoor zorgen dat je PDF's de beoogde uitstraling behouden. + +Van één enkel bestand tot een enorme batch, het patroon blijft hetzelfde—implementeer `IWarningCallback`, sluit het aan op `LoadOptions`, en laat Aspose.Words het zware werk doen. + +Klaar voor de volgende stap? Probeer dit te combineren met **font embedding** of **fallback font families** om het probleem automatisch op te lossen, of verken de **DocumentVisitor**‑API voor diepere inhoudsanalyse. Veel plezier met coderen, en moge al je lettertypen blijven waar je ze verwacht! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/dutch/words/net/images-and-shapes/_index.md b/content/dutch/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..31dbb48d3 --- /dev/null +++ b/content/dutch/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "dutch" +type: "category" +--- + +# Images And Shapes diff --git a/content/dutch/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/dutch/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..15e57a500 --- /dev/null +++ b/content/dutch/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Voeg snel schaduw toe aan een vorm met Aspose.Words. Leer hoe je een + Word‑document maakt met Aspose, hoe je vormschaduw toevoegt en schaduwtransparantie + toepast in C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: nl +og_description: Schaduw toevoegen aan vorm in een Word‑bestand met Aspose.Words. Deze + stapsgewijze handleiding laat zien hoe je een document maakt, een vorm toevoegt + en schaduwtransparantie toepast. +og_title: Schaduw toevoegen aan vorm – Aspose.Words C#-handleiding +tags: +- Aspose.Words +- C# +- Word Automation +title: Schaduw toevoegen aan vorm in een Word‑document – Complete Aspose.Words‑gids +url: /dutch/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Schaduw toevoegen aan vorm – Complete Aspose.Words-gids + +Heb je ooit **schaduw aan een vorm** moeten toevoegen in een Word‑bestand, maar wist je niet welke API‑aanroepen je moest gebruiken? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur wanneer ze voor het eerst een rechthoek of een ander tekenobject een echte slagschaduw willen geven, vooral wanneer ze werken met Aspose.Words voor .NET. + +In deze tutorial lopen we alles door wat je moet weten: van **een Word‑document maken met Aspose** tot het configureren van de schaduw, het aanpassen van de vervaging, afstand, hoek en zelfs **schaduwtransparantie toepassen**. Aan het einde heb je een kant‑klaar C#‑programma dat een `.docx`‑bestand produceert met een mooi gearceerde rechthoek—geen handmatig geknoei in Word nodig. + +--- + +## Wat je zult leren + +- Hoe je een Aspose.Words‑project opzet in Visual Studio. +- De exacte stappen om **een Word‑document te maken met Aspose** en een vorm in te voegen. +- **Hoe je vormschaduw toevoegt** met volledige controle over vervaging, afstand, hoek en transparantie. +- Tips voor het oplossen van veelvoorkomende valkuilen (bijv. ontbrekende licentie, onjuiste eenheden). +- Een complete, copy‑and‑paste code‑voorbeeld dat je vandaag nog kunt uitvoeren. + +> **Voorwaarden:** .NET 6+ (of .NET Framework 4.7.2+), een geldige Aspose.Words‑licentie (of de gratis proefversie), en een basiskennis van C#. + +--- + +## Stap 1 – Stel je project in en voeg Aspose.Words toe + +Allereerst. Open Visual Studio, maak een nieuwe **Console App (.NET Core)** aan en voeg het Aspose.Words‑NuGet‑pakket toe: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro‑tip:** Als je een licentiebestand (`Aspose.Words.lic`) hebt, kopieer dit dan naar de project‑root en laad het bij het opstarten. Dit voorkomt het watermerk dat verschijnt in de gratis evaluatiemodus. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Stap 2 – Maak een nieuw leeg document + +Nu **maken we een Word‑document met Aspose**. Dit object dient als het canvas voor onze vorm. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +De `Document`‑klasse is het toegangspunt voor alles wat volgt—alinea’s, secties en uiteraard tekenobjecten. + +--- + +## Stap 3 – Voeg een rechthoekige vorm toe + +Met het document klaar, kunnen we een vorm toevoegen. Hier kiezen we een eenvoudige rechthoek, maar dezelfde logica werkt voor cirkels, lijnen of aangepaste polygonen. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Waarom een vorm?** In Aspose.Words kan een `Shape`‑object tekst, afbeeldingen of gewoon een decoratief element bevatten. Het toevoegen van een schaduw aan een vorm is veel eenvoudiger dan het manipuleren van een afbeeldingskader. + +--- + +## Stap 4 – Configureer de schaduw (Schaduw toevoegen aan vorm) + +Dit is het hart van de tutorial—**hoe je vormschaduw toevoegt** en het uiterlijk fijn afstemt. De eigenschap `ShadowFormat` geeft je volledige controle. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Wat elke eigenschap doet + +| Eigenschap | Effect | Typische waarden | +|------------|--------|------------------| +| **Visible** | Schakelt de schaduw in/uit. | `true` / `false` | +| **Blur** | Verzacht de randen van de schaduw. | `0` (hard) tot `10` (zeer zacht) | +| **Distance** | Verplaatst de schaduw van de vorm af. | `1`–`5` punten is gebruikelijk | +| **Angle** | Bepaalt de richting van de offset. | `0`–`360` graden | +| **Transparency** | Maakt de schaduw gedeeltelijk doorschijnend. | `0` (ondoorzichtig) tot `1` (onzichtbaar) | + +> **Randgeval:** Als je `Transparency` op `1` zet, verdwijnt de schaduw volledig—handig om deze programmatisch te toggelen. + +--- + +## Stap 5 – Voeg de vorm toe aan het document + +We koppelen de vorm nu aan de eerste alinea van de body van het document. Aspose maakt automatisch een alinea aan als er nog geen bestaat. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Als je document al inhoud bevat, kun je de vorm op elk knooppunt invoegen met `InsertAfter` of `InsertBefore`. + +--- + +## Stap 6 – Sla het document op + +Tot slot schrijven we het bestand naar schijf. Je kunt elk ondersteund formaat kiezen (`.docx`, `.pdf`, `.odt`, enz.), maar voor deze tutorial blijven we bij het native Word‑formaat. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Open het resulterende `ShadowedShape.docx` in Microsoft Word, en je ziet een rechthoek met een zachte, 45‑graden schaduw die 30 % transparant is—precies zoals we hebben geconfigureerd. + +--- + +## Volledig werkend voorbeeld + +Hieronder staat het **complete, copy‑and‑paste‑klare** programma dat alle bovenstaande stappen bevat. Sla het op als `Program.cs` en voer het uit met `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Verwachte output:** Een bestand genaamd `ShadowedShape.docx` met één rechthoek en een subtiele, half‑transparante slagschaduw onder een hoek van 45°. + +--- + +## Variaties & Geavanceerde tips + +### Schaduwkleur wijzigen + +Standaard erft de schaduw de vulkleur van de vorm, maar je kunt een aangepaste kleur instellen: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Meerdere vormen met verschillende schaduwen + +Als je meerdere vormen nodig hebt, herhaal dan simpelweg de creatie‑ en configuratiestappen. Vergeet niet elke vorm een unieke naam te geven als je later naar ze wilt verwijzen. + +### Exporteren naar PDF met behouden schaduwen + +Aspose.Words behoudt schaduweffecten bij het opslaan naar PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Veelvoorkomende valkuilen + +| Symptoom | Waarschijnlijke oorzaak | Oplossing | +|----------|--------------------------|-----------| +| Schaduw niet zichtbaar | `ShadowFormat.Visible` staat op `false` | Zet op `true`. | +| Schaduw ziet er te hard uit | `Blur` staat op `0` | Verhoog `Blur` naar 3–6. | +| Schaduw verdwijnt in PDF | Een oude Aspose.Words‑versie (< 22.9) wordt gebruikt | Upgrade naar de nieuwste bibliotheek. | + +--- + +## Conclusie + +We hebben behandeld **hoe je schaduw aan een vorm toevoegt** met Aspose.Words, van het initialiseren van een document tot het fijn afstemmen van vervaging, afstand, hoek en **schaduwtransparantie toepassen**. Het volledige voorbeeld toont een nette, productie‑klare aanpak die je kunt aanpassen aan elke vorm of documentlay-out. + +Heb je vragen over **een Word‑document maken met Aspose** voor complexere scenario’s—zoals tabellen met schaduwen of dynamisch gegenereerde vormen? Laat een reactie achter of bekijk de gerelateerde tutorials over Aspose.Words‑afbeeldingsverwerking en alinea‑opmaak. + +Veel programmeerplezier, en geniet van die extra visuele polish in je Word‑documenten! + +--- + +![schaduw aan vorm voorbeeld](shadowed_shape.png "schaduw aan vorm voorbeeld") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/english/words/_index.md b/content/english/words/_index.md new file mode 100644 index 000000000..71a27424c --- /dev/null +++ b/content/english/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "english" +type: "family" +--- + +# Words Tutorials diff --git a/content/english/words/net/_index.md b/content/english/words/net/_index.md new file mode 100644 index 000000000..58ce702fc --- /dev/null +++ b/content/english/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "english" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/english/words/net/getting-started/_index.md b/content/english/words/net/getting-started/_index.md new file mode 100644 index 000000000..4ac49d782 --- /dev/null +++ b/content/english/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "english" +type: "category" +--- + +# Getting Started diff --git a/content/english/words/net/getting-started/tutorial/_index.md b/content/english/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..8f23cf747 --- /dev/null +++ b/content/english/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,242 @@ +--- +url: /net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide + +Ever wondered how to **detect missing fonts** when you load a Word file with Aspose.Words? In my day‑to‑day work, I’ve run into a few PDFs that looked off because the original document used a font I didn’t have installed. The good news? Aspose.Words can tell you exactly when it substitutes a font, and you can capture that information with a simple warning callback. + +In this tutorial we’ll walk through a **complete, runnable example** that shows you how to log every font substitution, why the callback matters, and a couple of extra tricks for robust missing‑font detection. No fluff, just the code and the reasoning you need to get it working today. + +--- + +## What You’ll Learn + +- How to implement **Aspose.Words warning callback** to catch font substitution events. +- How to configure **LoadOptions C#** so the callback is invoked while loading a document. +- How to verify that the missing‑font detection really worked, and what the console output looks like. +- Optional tweaks for large batches or headless environments. + +**Prerequisites** – You need a recent version of Aspose.Words for .NET (the code was tested with 23.12), .NET 6 or later, and a basic grasp of C#. If you’ve got those, you’re good to go. + +--- + +## Detect Missing Fonts with a Warning Callback + +The heart of the solution is an implementation of `IWarningCallback`. Aspose.Words fires a `WarningInfo` object for many situations, but we only care about `WarningType.FontSubstitution`. Let’s see how to hook into that. + +### Step 1: Create a Font‑Warning Collector + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Why this matters*: By filtering on `WarningType.FontSubstitution` we avoid clutter from unrelated warnings (like deprecated features). The `info.Description` already contains the original font name and the fallback used, giving you a clear audit trail. + +--- + +## Configure LoadOptions to Use the Callback + +Now we tell Aspose.Words to use our collector when it loads a file. + +### Step 2: Set Up LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Why this matters*: `LoadOptions` is the single place where you can plug in the callback, encryption passwords, and other loading behaviours. Keeping it separate from the `Document` constructor makes the code reusable across many files. + +--- + +## Load the Document and Capture Missing Fonts + +With the callback wired up, the next step is simply loading the document. + +### Step 3: Load Your DOCX (or any supported format) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +When the `Document` constructor parses the file, any missing font triggers our `FontWarningCollector`. The console will show lines such as: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +That line is the concrete evidence that **detect missing fonts** worked. + +--- + +## Verify the Output – What to Expect + +Run the program from a terminal or Visual Studio. If the source document contains a font you don’t have installed, you’ll see at least one “Font substituted” line. If the document uses only installed fonts, the callback stays silent and you’ll just get the “Document loaded successfully.” message. + +**Tip**: To double‑check, open the Word file in Microsoft Word and look at the font list. Any font that appears in *Replace Fonts* under the *Home → Font* group is a candidate for substitution. + +--- + +## Advanced: Detect Missing Fonts in Bulk + +Often you need to scan dozens of files. The same pattern scales nicely: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Because the `FontWarningCollector` writes to the console each time it’s invoked, you’ll get a per‑file report without extra plumbing. For production scenarios you might want to log to a file or a database – simply replace `Console.WriteLine` with your preferred logger. + +--- + +## Common Pitfalls & Pro Tips + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **No warnings appear** | The document actually contains only installed fonts. | Verify by opening the file in Word or by deliberately removing a font from your system. | +| **Callback not called** | `LoadOptions.WarningCallback` was never assigned or a new `LoadOptions` instance was used later. | Keep a single `LoadOptions` object and reuse it for every load. | +| **Too many unrelated warnings** | You didn’t filter by `WarningType.FontSubstitution`. | Add the `if (info.Type == WarningType.FontSubstitution)` guard as shown. | +| **Performance slowdown on huge files** | The callback runs on every warning, which can be many for large docs. | Disable other warning types via `LoadOptions.WarningCallback` or set `LoadOptions.LoadFormat` to a specific type if you know it. | + +--- + +## Full Working Example (Copy‑Paste Ready) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Expected console output** (when a missing font is encountered): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +If no substitution occurs, you’ll only see the success line. + +--- + +## Conclusion + +You now have a **complete, production‑ready way to detect missing fonts** in any document processed by Aspose.Words. By leveraging the **Aspose.Words warning callback** and configuring **LoadOptions C#**, you can log every font substitution, troubleshoot layout issues, and ensure your PDFs retain the intended look‑and‑feel. + +From a single file to a massive batch, the pattern stays the same—implement `IWarningCallback`, plug it into `LoadOptions`, and let Aspose.Words do the heavy lifting. + +Ready for the next step? Try combining this with **font embedding** or **fallback font families** to automatically fix the problem, or explore the **DocumentVisitor** API for deeper content analysis. Happy coding, and may all your fonts stay where you expect them! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} \ No newline at end of file diff --git a/content/english/words/net/images-and-shapes/_index.md b/content/english/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..b6a0df798 --- /dev/null +++ b/content/english/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "english" +type: "category" +--- + +# Images And Shapes diff --git a/content/english/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/english/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..82b25425b --- /dev/null +++ b/content/english/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2025-12-08 +description: Add shadow to shape quickly with Aspose.Words. Learn how to create Word + document using Aspose, how to add shape shadow, and apply shadow transparency in + C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: en +og_description: Add shadow to shape in a Word file using Aspose.Words. This step‑by‑step + guide shows how to create a document, add a shape, and apply shadow transparency. +og_title: Add Shadow to Shape – Aspose.Words C# Tutorial +tags: +- Aspose.Words +- C# +- Word Automation +title: Add Shadow to Shape in a Word Document – Complete Aspose.Words Guide +url: /net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +# Add Shadow to Shape – Complete Aspose.Words Guide + +Ever needed to **add shadow to shape** in a Word file but weren’t sure which API calls to use? You’re not alone. Many developers hit a wall when they first try to give a rectangle or any drawing element a proper drop‑shadow, especially when they’re working with Aspose.Words for .NET. + +In this tutorial we’ll walk through everything you need to know: from **creating a Word document using Aspose** to configuring the shadow, tweaking its blur, distance, angle, and even **applying shadow transparency**. By the end you’ll have a ready‑to‑run C# program that produces a `.docx` file with a nicely shaded rectangle—no manual fiddling in Word required. + +--- + +## What You’ll Learn + +- How to set up an Aspose.Words project in Visual Studio. +- The exact steps to **create Word document using Aspose** and insert a shape. +- **How to add shape shadow** with full control over blur, distance, angle, and transparency. +- Tips for troubleshooting common pitfalls (e.g., missing license, incorrect units). +- A complete, copy‑and‑paste code sample you can run today. + +> **Prerequisites:** .NET 6+ (or .NET Framework 4.7.2+), a valid Aspose.Words license (or the free trial), and a basic familiarity with C#. + +--- + +## Step 1 – Set Up Your Project and Add Aspose.Words + +First things first. Open Visual Studio, create a new **Console App (.NET Core)**, and add the Aspose.Words NuGet package: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** If you have a license file (`Aspose.Words.lic`), copy it into the project root and load it at startup. This avoids the watermark that appears in the free evaluation mode. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Step 2 – Create a New Blank Document + +Now we actually **create Word document using Aspose**. This object will serve as the canvas for our shape. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +The `Document` class is the entry point for everything else—paragraphs, sections, and of course, drawing objects. + +--- + +## Step 3 – Insert a Rectangle Shape + +With the document ready, we can add a shape. Here we choose a simple rectangle, but the same logic works for circles, lines, or custom polygons. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Why a shape?** In Aspose.Words a `Shape` object can hold text, images, or just act as a decorative element. Adding a shadow to a shape is far easier than trying to manipulate a picture frame. + +--- + +## Step 4 – Configure the Shadow (Add Shadow to Shape) + +This is the heart of the tutorial—**how to add shape shadow** and fine‑tune its appearance. The `ShadowFormat` property gives you full control. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### What Each Property Does + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | Turns the shadow on/off. | `true` / `false` | +| **Blur** | Softens the shadow edges. | `0` (hard) to `10` (very soft) | +| **Distance** | Moves the shadow away from the shape. | `1`–`5` points is common | +| **Angle** | Controls the direction of the offset. | `0`–`360` degrees | +| **Transparency** | Makes the shadow partially see‑through. | `0` (opaque) to `1` (invisible) | + +> **Edge case:** If you set `Transparency` to `1`, the shadow disappears entirely—useful for toggling it programmatically. + +--- + +## Step 5 – Add the Shape to the Document + +We now attach the shape to the first paragraph of the document’s body. Aspose automatically creates a paragraph if none exists. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +If your document already contains content, you can insert the shape at any node using `InsertAfter` or `InsertBefore`. + +--- + +## Step 6 – Save the Document + +Finally, write the file to disk. You can choose any supported format (`.docx`, `.pdf`, `.odt`, etc.), but for this tutorial we’ll stick with the native Word format. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Open the resulting `ShadowedShape.docx` in Microsoft Word, and you’ll see a rectangle with a soft, 45‑degree shadow that’s 30 % transparent—exactly what we configured. + +--- + +## Full Working Example + +Below is the **complete, copy‑and‑paste ready** program that incorporates all the steps above. Save it as `Program.cs` and run it with `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Expected output:** A file named `ShadowedShape.docx` containing a single rectangle with a subtle, semi‑transparent drop shadow angled at 45°. + +--- + +## Variations & Advanced Tips + +### Changing Shadow Color + +By default the shadow inherits the shape’s fill color, but you can set a custom color: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Multiple Shapes with Different Shadows + +If you need several shapes, just repeat the creation and configuration steps. Remember to give each shape a unique name if you plan to reference them later. + +### Exporting to PDF with Preserved Shadows + +Aspose.Words preserves shadow effects when saving to PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Common Pitfalls + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Shadow not visible | `ShadowFormat.Visible` left as `false` | Set to `true`. | +| Shadow looks too hard | `Blur` set to `0` | Increase `Blur` to 3–6. | +| Shadow disappears in PDF | Using an old Aspose.Words version (< 22.9) | Upgrade to the latest library. | + +--- + +## Conclusion + +We’ve covered **how to add shadow to shape** using Aspose.Words, from initializing a document to fine‑tuning blur, distance, angle, and **applying shadow transparency**. The full example demonstrates a clean, production‑ready approach that you can adapt to any shape or document layout. + +Got questions about **create word document using aspose** for more complex scenarios—like tables with shadows or dynamic data‑driven shapes? Drop a comment below or check out the related tutorials on Aspose.Words image handling and paragraph formatting. + +Happy coding, and enjoy giving your Word documents that extra visual polish! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} \ No newline at end of file diff --git a/content/french/words/_index.md b/content/french/words/_index.md new file mode 100644 index 000000000..0168063f6 --- /dev/null +++ b/content/french/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "french" +type: "family" +--- + +# Words Tutorials diff --git a/content/french/words/net/_index.md b/content/french/words/net/_index.md new file mode 100644 index 000000000..abf011043 --- /dev/null +++ b/content/french/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "french" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/french/words/net/getting-started/_index.md b/content/french/words/net/getting-started/_index.md new file mode 100644 index 000000000..6901e34ef --- /dev/null +++ b/content/french/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "french" +type: "category" +--- + +# Getting Started diff --git a/content/french/words/net/getting-started/tutorial/_index.md b/content/french/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..a8fc471b5 --- /dev/null +++ b/content/french/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: fr +url: /french/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Détecter les polices manquantes dans les documents Aspose.Words – Guide complet C# + +Vous êtes-vous déjà demandé comment **détecter les polices manquantes** lorsque vous chargez un fichier Word avec Aspose.Words ? Dans mon travail quotidien, je suis tombé sur quelques PDF qui semblaient incorrects parce que le document original utilisait une police que je n’avais pas installée. Bonne nouvelle : Aspose.Words peut vous indiquer exactement quand il substitue une police, et vous pouvez capturer cette information avec un simple rappel d’avertissement. + +Dans ce tutoriel, nous allons parcourir un **exemple complet et exécutable** qui montre comment consigner chaque substitution de police, pourquoi le rappel est important, et quelques astuces supplémentaires pour une détection robuste des polices manquantes. Pas de fioritures, juste le code et le raisonnement dont vous avez besoin pour le faire fonctionner dès aujourd’hui. + +--- + +## Ce que vous allez apprendre + +- Comment implémenter le **rappel d’avertissement Aspose.Words** pour intercepter les événements de substitution de police. +- Comment configurer **LoadOptions C#** afin que le rappel soit invoqué lors du chargement d’un document. +- Comment vérifier que la détection des polices manquantes a réellement fonctionné, et à quoi ressemble la sortie console. +- Ajustements optionnels pour les gros lots ou les environnements sans interface graphique. + +**Prérequis** – Vous avez besoin d’une version récente d’Aspose.Words pour .NET (le code a été testé avec la version 23.12), .NET 6 ou ultérieur, et une compréhension de base du C#. Si vous avez tout cela, vous êtes prêt à commencer. + +--- + +## Détecter les polices manquantes avec un rappel d’avertissement + +Le cœur de la solution est une implémentation de `IWarningCallback`. Aspose.Words déclenche un objet `WarningInfo` pour de nombreuses situations, mais nous ne nous intéressons qu’à `WarningType.FontSubstitution`. Voyons comment s’y brancher. + +### Étape 1 : Créer un collecteur d’avertissements de police + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Pourquoi c’est important* : En filtrant sur `WarningType.FontSubstitution`, nous évitons le bruit des avertissements non pertinents (comme les fonctionnalités obsolètes). `info.Description` contient déjà le nom de la police d’origine et la police de secours utilisée, vous offrant ainsi une traçabilité claire. + +--- + +## Configurer LoadOptions pour utiliser le rappel + +Nous indiquons maintenant à Aspose.Words d’utiliser notre collecteur lors du chargement d’un fichier. + +### Étape 2 : Configurer LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Pourquoi c’est important* : `LoadOptions` est le seul endroit où vous pouvez brancher le rappel, les mots de passe de chiffrement et d’autres comportements de chargement. Le garder séparé du constructeur `Document` rend le code réutilisable pour de nombreux fichiers. + +--- + +## Charger le document et capturer les polices manquantes + +Avec le rappel en place, l’étape suivante consiste simplement à charger le document. + +### Étape 3 : Charger votre DOCX (ou tout autre format supporté) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Lorsque le constructeur `Document` analyse le fichier, toute police manquante déclenche notre `FontWarningCollector`. La console affichera des lignes telles que : + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Cette ligne constitue la preuve concrète que la **détection des polices manquantes** a fonctionné. + +--- + +## Vérifier la sortie – À quoi s’attendre + +Exécutez le programme depuis un terminal ou Visual Studio. Si le document source contient une police que vous n’avez pas installée, vous verrez au moins une ligne « Font substituted ». Si le document n’utilise que des polices installées, le rappel reste silencieux et vous n’obtiendrez que le message « Document loaded successfully. ». + +**Astuce** : Pour vérifier, ouvrez le fichier Word dans Microsoft Word et consultez la liste des polices. Toute police apparaissant dans *Remplacer les polices* sous le groupe *Accueil → Police* est susceptible d’être substituée. + +--- + +## Avancé : Détecter les polices manquantes en masse + +Souvent, vous devez analyser des dizaines de fichiers. Le même schéma s’adapte facilement : + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Comme le `FontWarningCollector` écrit dans la console à chaque invocation, vous obtenez un rapport par fichier sans logique supplémentaire. Pour les scénarios de production, vous pourriez vouloir consigner dans un fichier ou une base de données — remplacez simplement `Console.WriteLine` par votre logger préféré. + +--- + +## Pièges courants & astuces professionnelles + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| **Aucun avertissement n’apparaît** | Le document ne contient en fait que des polices installées. | Vérifiez en ouvrant le fichier dans Word ou en supprimant délibérément une police de votre système. | +| **Le rappel n’est pas appelé** | `LoadOptions.WarningCallback` n’a jamais été assigné ou une nouvelle instance de `LoadOptions` a été utilisée plus tard. | Conservez un seul objet `LoadOptions` et réutilisez‑le pour chaque chargement. | +| **Trop d’avertissements non pertinents** | Vous n’avez pas filtré par `WarningType.FontSubstitution`. | Ajoutez la condition `if (info.Type == WarningType.FontSubstitution)` comme indiqué. | +| **Ralentissement sur de très gros fichiers** | Le rappel s’exécute pour chaque avertissement, ce qui peut être nombreux pour de gros documents. | Désactivez les autres types d’avertissements via `LoadOptions.WarningCallback` ou définissez `LoadOptions.LoadFormat` sur un type spécifique si vous le connaissez. | + +--- + +## Exemple complet fonctionnel (prêt à copier‑coller) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Sortie console attendue** (lorsqu’une police manquante est rencontrée) : + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Si aucune substitution ne se produit, vous ne verrez que la ligne de succès. + +--- + +## Conclusion + +Vous disposez maintenant d’une **méthode complète et prête pour la production** afin de détecter les polices manquantes dans tout document traité par Aspose.Words. En tirant parti du **rappel d’avertissement Aspose.Words** et en configurant **LoadOptions C#**, vous pouvez consigner chaque substitution de police, dépanner les problèmes de mise en page et garantir que vos PDF conservent l’apparence prévue. + +Qu’il s’agisse d’un seul fichier ou d’un lot massif, le schéma reste le même — implémentez `IWarningCallback`, branchez‑le à `LoadOptions`, et laissez Aspose.Words faire le travail lourd. + +Prêt pour l’étape suivante ? Essayez de combiner cela avec **l’incorporation de polices** ou **les familles de polices de secours** pour corriger automatiquement le problème, ou explorez l’API **DocumentVisitor** pour une analyse de contenu plus approfondie. Bon codage, et que toutes vos polices restent là où vous les attendez ! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/french/words/net/images-and-shapes/_index.md b/content/french/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..b007435c0 --- /dev/null +++ b/content/french/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "french" +type: "category" +--- + +# Images And Shapes diff --git a/content/french/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/french/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..a112f42e6 --- /dev/null +++ b/content/french/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Ajoutez rapidement une ombre à une forme avec Aspose.Words. Apprenez + comment créer un document Word avec Aspose, comment ajouter une ombre à une forme + et appliquer la transparence de l’ombre en C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: fr +og_description: Ajouter une ombre à une forme dans un fichier Word à l'aide d'Aspose.Words. + Ce guide étape par étape montre comment créer un document, ajouter une forme et + appliquer la transparence de l'ombre. +og_title: Ajouter une ombre à la forme – Tutoriel Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Ajouter une ombre à une forme dans un document Word – Guide complet d’Aspose.Words +url: /french/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Ajouter une ombre à une forme – Guide complet Aspose.Words + +Vous avez déjà eu besoin d'**ajouter une ombre à une forme** dans un fichier Word mais vous ne saviez pas quelles appels d'API utiliser ? Vous n'êtes pas seul. De nombreux développeurs se heurtent à un mur lorsqu'ils essaient pour la première fois d'ajouter une ombre portée à un rectangle ou à tout autre élément de dessin, surtout lorsqu'ils travaillent avec Aspose.Words pour .NET. + +Dans ce tutoriel, nous passerons en revue tout ce que vous devez savoir : de la **création d'un document Word en utilisant Aspose** à la configuration de l'ombre, en ajustant son flou, sa distance, son angle et même **l'application de la transparence de l'ombre**. À la fin, vous disposerez d'un programme C# prêt à l'emploi qui produit un fichier `.docx` avec un rectangle joliment ombré — aucune manipulation manuelle dans Word requise. + +--- + +## Ce que vous apprendrez + +- Comment configurer un projet Aspose.Words dans Visual Studio. +- Les étapes exactes pour **créer un document Word en utilisant Aspose** et insérer une forme. +- **Comment ajouter une ombre à une forme** avec un contrôle complet sur le flou, la distance, l'angle et la transparence. +- Conseils pour dépanner les problèmes courants (par ex., licence manquante, unités incorrectes). +- Un exemple complet, copiable, que vous pouvez exécuter dès aujourd'hui. + +> **Prérequis :** .NET 6+ (ou .NET Framework 4.7.2+), une licence valide Aspose.Words (ou l'essai gratuit), et une connaissance de base du C#. + +--- + +## Étape 1 – Configurez votre projet et ajoutez Aspose.Words + +Tout d'abord, ouvrez Visual Studio, créez une nouvelle **Application console (.NET Core)**, puis ajoutez le package NuGet Aspose.Words : + +```bash +dotnet add package Aspose.Words +``` + +> **Astuce :** Si vous avez un fichier de licence (`Aspose.Words.lic`), copiez‑le à la racine du projet et chargez‑le au démarrage. Cela évite le filigrane qui apparaît en mode d'évaluation gratuit. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Étape 2 – Créez un nouveau document vierge + +Nous allons maintenant **créer un document Word en utilisant Aspose**. Cet objet servira de toile pour notre forme. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +La classe `Document` est le point d'entrée pour tout le reste — paragraphes, sections, et bien sûr, objets de dessin. + +--- + +## Étape 3 – Insérez une forme rectangulaire + +Avec le document prêt, nous pouvons ajouter une forme. Ici nous choisissons un simple rectangle, mais la même logique fonctionne pour des cercles, des lignes ou des polygones personnalisés. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Pourquoi une forme ?** Dans Aspose.Words, un objet `Shape` peut contenir du texte, des images, ou simplement servir d'élément décoratif. Ajouter une ombre à une forme est bien plus simple que de manipuler un cadre d'image. + +--- + +## Étape 4 – Configurez l'ombre (Ajouter une ombre à une forme) + +C’est le cœur du tutoriel — **comment ajouter une ombre à une forme** et affiner son apparence. La propriété `ShadowFormat` vous donne un contrôle total. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Ce que chaque propriété fait + +| Propriété | Effet | Valeurs typiques | +|-----------|-------|-------------------| +| **Visible** | Active ou désactive l'ombre. | `true` / `false` | +| **Blur** | Adoucit les bords de l'ombre. | `0` (dur) à `10` (très doux) | +| **Distance** | Déplace l'ombre loin de la forme. | `1`–`5` points est courant | +| **Angle** | Contrôle la direction du décalage. | `0`–`360` degrés | +| **Transparency** | Rend l'ombre partiellement transparente. | `0` (opaque) à `1` (invisible) | + +> **Cas limite :** Si vous définissez `Transparency` à `1`, l'ombre disparaît complètement — utile pour la désactiver programmatique. + +--- + +## Étape 5 – Ajoutez la forme au document + +Nous attachons maintenant la forme au premier paragraphe du corps du document. Aspose crée automatiquement un paragraphe s'il n'en existe pas. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Si votre document contient déjà du contenu, vous pouvez insérer la forme à n'importe quel nœud en utilisant `InsertAfter` ou `InsertBefore`. + +--- + +## Étape 6 – Enregistrez le document + +Enfin, écrivez le fichier sur le disque. Vous pouvez choisir n'importe quel format supporté (`.docx`, `.pdf`, `.odt`, etc.), mais pour ce tutoriel nous resterons sur le format natif Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Ouvrez le `ShadowedShape.docx` résultant dans Microsoft Word, et vous verrez un rectangle avec une ombre douce à 45 degrés, 30 % transparente — exactement ce que nous avons configuré. + +--- + +## Exemple complet fonctionnel + +Voici le programme **complet, prêt à copier‑coller** qui intègre toutes les étapes ci‑dessus. Enregistrez‑le sous `Program.cs` et exécutez‑le avec `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Sortie attendue :** Un fichier nommé `ShadowedShape.docx` contenant un seul rectangle avec une ombre subtile, semi‑transparente, inclinée à 45°. + +--- + +## Variantes & astuces avancées + +### Changer la couleur de l'ombre + +Par défaut, l'ombre hérite de la couleur de remplissage de la forme, mais vous pouvez définir une couleur personnalisée : + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Plusieurs formes avec des ombres différentes + +Si vous avez besoin de plusieurs formes, répétez simplement les étapes de création et de configuration. Pensez à donner à chaque forme un nom unique si vous prévoyez de les référencer plus tard. + +### Exportation en PDF avec les ombres conservées + +Aspose.Words conserve les effets d'ombre lors de l'enregistrement en PDF : + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Pièges courants + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Ombre non visible | `ShadowFormat.Visible` left as `false` | Définir sur `true`. | +| L'ombre semble trop dure | `Blur` set to `0` | Augmenter `Blur` à 3–6. | +| L'ombre disparaît dans le PDF | Using an old Aspose.Words version (< 22.9) | Mettre à jour vers la dernière bibliothèque. | + +--- + +## Conclusion + +Nous avons couvert **comment ajouter une ombre à une forme** avec Aspose.Words, depuis l'initialisation d'un document jusqu'à l'ajustement du flou, de la distance, de l'angle et **l'application de la transparence de l'ombre**. L'exemple complet montre une approche propre, prête pour la production, que vous pouvez adapter à n'importe quelle forme ou mise en page de document. + +Vous avez des questions sur **créer un document Word en utilisant Aspose** pour des scénarios plus complexes — comme des tableaux avec des ombres ou des formes dynamiques alimentées par des données ? Laissez un commentaire ci‑dessous ou consultez les tutoriels associés sur la gestion des images et le formatage des paragraphes avec Aspose.Words. + +Bon codage, et profitez de donner à vos documents Word ce petit plus visuel ! + +--- + +![exemple d'ajout d'ombre à une forme](shadowed_shape.png "exemple d'ajout d'ombre à une forme") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/german/words/_index.md b/content/german/words/_index.md new file mode 100644 index 000000000..385f96477 --- /dev/null +++ b/content/german/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "german" +type: "family" +--- + +# Words Tutorials diff --git a/content/german/words/net/_index.md b/content/german/words/net/_index.md new file mode 100644 index 000000000..e0fe0b24b --- /dev/null +++ b/content/german/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "german" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/german/words/net/getting-started/_index.md b/content/german/words/net/getting-started/_index.md new file mode 100644 index 000000000..d20396ba3 --- /dev/null +++ b/content/german/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "german" +type: "category" +--- + +# Getting Started diff --git a/content/german/words/net/getting-started/tutorial/_index.md b/content/german/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..3b540d426 --- /dev/null +++ b/content/german/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,231 @@ +--- +language: de +url: /german/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Fehlende Schriftarten in Aspose.Words-Dokumenten erkennen – Vollständige C#‑Anleitung + +Haben Sie sich jemals gefragt, wie Sie **fehlende Schriftarten** erkennen können, wenn Sie eine Word‑Datei mit Aspose.Words laden? In meiner täglichen Arbeit bin ich auf ein paar PDFs gestoßen, die nicht richtig aussahen, weil das Originaldokument eine Schriftart verwendete, die ich nicht installiert hatte. Die gute Nachricht? Aspose.Words kann Ihnen genau mitteilen, wann es eine Schriftart ersetzt, und Sie können diese Information mit einem einfachen Warning‑Callback erfassen. + +In diesem Tutorial führen wir Sie durch ein **vollständiges, ausführbares Beispiel**, das zeigt, wie Sie jede Schriftart‑Ersetzung protokollieren, warum der Callback wichtig ist und ein paar zusätzliche Tricks für eine robuste Erkennung fehlender Schriftarten. Kein Schnickschnack, nur der Code und die Überlegungen, die Sie benötigen, um es noch heute zum Laufen zu bringen. + +--- + +## Was Sie lernen werden + +- Wie man **Aspose.Words warning callback** implementiert, um Schriftart‑Ersetzungs‑Ereignisse abzufangen. +- Wie man **LoadOptions C#** konfiguriert, damit der Callback beim Laden eines Dokuments aufgerufen wird. +- Wie man überprüft, dass die Erkennung fehlender Schriftarten wirklich funktioniert hat, und wie die Konsolenausgabe aussieht. +- Optionale Anpassungen für große Stapelverarbeitungen oder headless Umgebungen. + +**Voraussetzungen** – Sie benötigen eine aktuelle Version von Aspose.Words für .NET (der Code wurde mit 23.12 getestet), .NET 6 oder höher und ein grundlegendes Verständnis von C#. Wenn Sie das haben, können Sie loslegen. + +## Fehlende Schriftarten mit einem Warning‑Callback erkennen + +Das Herzstück der Lösung ist eine Implementierung von `IWarningCallback`. Aspose.Words löst ein `WarningInfo`‑Objekt für viele Situationen aus, aber wir interessieren uns nur für `WarningType.FontSubstitution`. Sehen wir uns an, wie man sich daran anhängt. + +### Schritt 1: Einen Font‑Warning‑Collector erstellen + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Warum das wichtig ist*: Durch das Filtern nach `WarningType.FontSubstitution` vermeiden wir Unordnung durch nicht verwandte Warnungen (wie veraltete Features). `info.Description` enthält bereits den ursprünglichen Schriftartnamen und die verwendete Ersatzschrift, was Ihnen eine klare Prüfspur liefert. + +## LoadOptions konfigurieren, um den Callback zu verwenden + +Jetzt teilen wir Aspose.Words mit, dass es unseren Collector beim Laden einer Datei verwenden soll. + +### Schritt 2: LoadOptions einrichten + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Warum das wichtig ist*: `LoadOptions` ist der einzige Ort, an dem Sie den Callback, Verschlüsselungspasswörter und andere Ladeverhalten einbinden können. Wenn Sie es vom `Document`‑Konstruktor getrennt halten, wird der Code für viele Dateien wiederverwendbar. + +## Das Dokument laden und fehlende Schriftarten erfassen + +Mit dem angeschlossenen Callback besteht der nächste Schritt einfach darin, das Dokument zu laden. + +### Schritt 3: Laden Sie Ihr DOCX (oder ein beliebiges unterstütztes Format) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Wenn der `Document`‑Konstruktor die Datei analysiert, löst jede fehlende Schriftart unseren `FontWarningCollector` aus. Die Konsole zeigt Zeilen wie: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Diese Zeile ist der konkrete Beweis, dass **fehlende Schriftarten erkennen** funktioniert hat. + +## Die Ausgabe überprüfen – Was zu erwarten ist + +Führen Sie das Programm in einem Terminal oder Visual Studio aus. Wenn das Quell‑Dokument eine Schriftart enthält, die Sie nicht installiert haben, sehen Sie mindestens eine Zeile „Font substituted“. Wenn das Dokument nur installierte Schriftarten verwendet, bleibt der Callback still und Sie erhalten nur die Meldung „Document loaded successfully.“. + +**Tipp**: Öffnen Sie die Word‑Datei in Microsoft Word und schauen Sie sich die Schriftartenliste an. Jede Schriftart, die unter *Replace Fonts* in der Gruppe *Home → Font* erscheint, ist ein Kandidat für eine Ersetzung. + +## Fortgeschritten: Fehlende Schriftarten in großen Mengen erkennen + +Oft müssen Sie Dutzende von Dateien scannen. Das gleiche Muster skaliert gut: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Da der `FontWarningCollector` jedes Mal, wenn er aufgerufen wird, in die Konsole schreibt, erhalten Sie einen Bericht pro Datei ohne zusätzlichen Aufwand. Für Produktionsszenarien möchten Sie vielleicht in eine Datei oder Datenbank protokollieren – ersetzen Sie einfach `Console.WriteLine` durch Ihren bevorzugten Logger. + +## Häufige Fallstricke & Profi‑Tipps + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Keine Warnungen erscheinen** | Das Dokument enthält tatsächlich nur installierte Schriftarten. | Überprüfen Sie dies, indem Sie die Datei in Word öffnen oder bewusst eine Schriftart von Ihrem System entfernen. | +| **Callback wird nicht aufgerufen** | `LoadOptions.WarningCallback` wurde nie zugewiesen oder später wurde eine neue `LoadOptions`‑Instanz verwendet. | Behalten Sie ein einzelnes `LoadOptions`‑Objekt und verwenden Sie es für jedes Laden wieder. | +| **Zu viele nicht verwandte Warnungen** | Sie haben nicht nach `WarningType.FontSubstitution` gefiltert. | Fügen Sie die `if (info.Type == WarningType.FontSubstitution)`‑Abfrage wie gezeigt hinzu. | +| **Leistungsabfall bei riesigen Dateien** | Der Callback wird bei jeder Warnung ausgeführt, was bei großen Dokumenten sehr häufig sein kann. | Deaktivieren Sie andere Warnungstypen über `LoadOptions.WarningCallback` oder setzen Sie `LoadOptions.LoadFormat` auf einen bestimmten Typ, wenn Sie diesen kennen. | + +## Voll funktionsfähiges Beispiel (Copy‑Paste‑bereit) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Erwartete Konsolenausgabe** (wenn eine fehlende Schriftart gefunden wird): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Wenn keine Ersetzung erfolgt, sehen Sie nur die Erfolgszeile. + +## Fazit + +Sie haben jetzt eine **vollständige, produktionsreife Methode, um fehlende Schriftarten** in jedem von Aspose.Words verarbeiteten Dokument zu erkennen. Durch die Nutzung des **Aspose.Words warning callback** und die Konfiguration von **LoadOptions C#** können Sie jede Schriftart‑Ersetzung protokollieren, Layout‑Probleme beheben und sicherstellen, dass Ihre PDFs das beabsichtigte Aussehen behalten. + +Ob einzelne Datei oder riesiger Stapel, das Muster bleibt gleich – implementieren Sie `IWarningCallback`, binden Sie ihn in `LoadOptions` ein und lassen Sie Aspose.Words die schwere Arbeit erledigen. + +Bereit für den nächsten Schritt? Versuchen Sie, dies mit **font embedding** oder **fallback font families** zu kombinieren, um das Problem automatisch zu beheben, oder erkunden Sie die **DocumentVisitor**‑API für eine tiefere Inhaltsanalyse. Viel Spaß beim Coden, und möge jede Ihrer Schriftarten dort bleiben, wo Sie sie erwarten! + +--- + +![Fehlende Schriftarten in Aspose.Words – Konsolenausgabe Screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/german/words/net/images-and-shapes/_index.md b/content/german/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..78996bda1 --- /dev/null +++ b/content/german/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "german" +type: "category" +--- + +# Images And Shapes diff --git a/content/german/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/german/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..4c8017a06 --- /dev/null +++ b/content/german/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Fügen Sie einer Form schnell einen Schatten mit Aspose.Words hinzu. Erfahren + Sie, wie Sie ein Word‑Dokument mit Aspose erstellen, wie Sie einer Form einen Schatten + hinzufügen und die Schatten‑Transparenz in C# anwenden. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: de +og_description: Schatten zu einer Form in einer Word‑Datei mit Aspose.Words hinzufügen. + Diese Schritt‑für‑Schritt‑Anleitung zeigt, wie man ein Dokument erstellt, eine Form + hinzufügt und die Schatten‑Transparenz anwendet. +og_title: Schatten zur Form hinzufügen – Aspose.Words C#‑Tutorial +tags: +- Aspose.Words +- C# +- Word Automation +title: Schatten zu einer Form in einem Word‑Dokument hinzufügen – Vollständiger Aspose.Words‑Leitfaden +url: /german/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Schatten zu Form hinzufügen – Vollständiger Aspose.Words Leitfaden + +Haben Sie jemals **Schatten zu Form hinzufügen** in einer Word‑Datei benötigt, waren sich aber nicht sicher, welche API‑Aufrufe Sie verwenden müssen? Sie sind nicht allein. Viele Entwickler stoßen an ihre Grenzen, wenn sie zum ersten Mal einem Rechteck oder einem anderen Zeichenobjekt einen richtigen Drop‑Shadow geben wollen, besonders wenn sie mit Aspose.Words für .NET arbeiten. + +In diesem Tutorial führen wir Sie durch alles, was Sie wissen müssen: vom **Erstellen eines Word‑Dokuments mit Aspose** über die Konfiguration des Schattens, das Anpassen von Weichzeichnung, Abstand, Winkel und sogar das **Anwenden von Schatten‑Transparenz**. Am Ende haben Sie ein sofort ausführbares C#‑Programm, das eine `.docx`‑Datei mit einem schön schattierten Rechteck erzeugt – ganz ohne manuelles Nachhaken in Word. + +--- + +## Was Sie lernen werden + +- Wie Sie ein Aspose.Words‑Projekt in Visual Studio einrichten. +- Die genauen Schritte, um **ein Word‑Dokument mit Aspose zu erstellen** und eine Form einzufügen. +- **Wie man Schatten zu einer Form hinzufügt** mit voller Kontrolle über Weichzeichnung, Abstand, Winkel und Transparenz. +- Tipps zur Fehlersuche bei häufigen Stolperfallen (z. B. fehlende Lizenz, falsche Einheiten). +- Ein komplettes Copy‑and‑Paste‑Code‑Beispiel, das Sie noch heute ausführen können. + +> **Voraussetzungen:** .NET 6+ (oder .NET Framework 4.7.2+), eine gültige Aspose.Words‑Lizenz (oder die kostenlose Testversion) und Grundkenntnisse in C#. + +--- + +## Schritt 1 – Projekt einrichten und Aspose.Words hinzufügen + +Zuerst das Wichtigste. Öffnen Sie Visual Studio, erstellen Sie eine neue **Console App (.NET Core)** und fügen Sie das Aspose.Words‑NuGet‑Paket hinzu: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro‑Tipp:** Wenn Sie eine Lizenzdatei (`Aspose.Words.lic`) besitzen, kopieren Sie sie in das Projekt‑Root‑Verzeichnis und laden Sie sie beim Start. Das verhindert das Wasserzeichen, das im kostenlosen Evaluierungsmodus erscheint. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Schritt 2 – Neues leeres Dokument erstellen + +Jetzt **ein Word‑Dokument mit Aspose erstellen**. Dieses Objekt dient als Zeichenfläche für unsere Form. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Die `Document`‑Klasse ist der Einstiegspunkt für alles andere – Absätze, Abschnitte und natürlich Zeichenobjekte. + +--- + +## Schritt 3 – Ein Rechteck einfügen + +Nachdem das Dokument bereit ist, können wir eine Form hinzufügen. Hier wählen wir ein einfaches Rechteck, aber dieselbe Logik funktioniert für Kreise, Linien oder benutzerdefinierte Polygone. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Warum eine Form?** In Aspose.Words kann ein `Shape`‑Objekt Text, Bilder oder einfach nur ein dekoratives Element enthalten. Einen Schatten zu einer Form hinzuzufügen ist weitaus einfacher, als ein Bildrahmen‑Element zu manipulieren. + +--- + +## Schritt 4 – Schatten konfigurieren (Schatten zu Form hinzufügen) + +Dies ist das Herzstück des Tutorials – **wie man Schatten zu einer Form hinzufügt** und das Aussehen feinjustiert. Die Eigenschaft `ShadowFormat` gibt Ihnen volle Kontrolle. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Was jede Eigenschaft bewirkt + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | Schaltet den Schatten ein/aus. | `true` / `false` | +| **Blur** | Weichzeichnet die Schattenkanten. | `0` (hart) bis `10` (sehr weich) | +| **Distance** | Verschiebt den Schatten vom Objekt weg. | `1`–`5` Punkte sind üblich | +| **Angle** | Steuert die Richtung des Versatzes. | `0`–`360` Grad | +| **Transparency** | Macht den Schatten teilweise durchsichtig. | `0` (undurchsichtig) bis `1` (unsichtbar) | + +> **Randfall:** Wenn Sie `Transparency` auf `1` setzen, verschwindet der Schatten vollständig – praktisch, um ihn programmgesteuert ein- bzw. auszuschalten. + +--- + +## Schritt 5 – Form dem Dokument hinzufügen + +Wir hängen die Form jetzt an den ersten Absatz des Dokumentenkörpers an. Aspose erzeugt automatisch einen Absatz, falls keiner vorhanden ist. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Enthält Ihr Dokument bereits Inhalte, können Sie die Form an jeder beliebigen Stelle mit `InsertAfter` oder `InsertBefore` einfügen. + +--- + +## Schritt 6 – Dokument speichern + +Zum Schluss schreiben wir die Datei auf die Festplatte. Sie können jedes unterstützte Format wählen (`.docx`, `.pdf`, `.odt` usw.), aber für dieses Tutorial bleiben wir beim nativen Word‑Format. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Öffnen Sie die resultierende `ShadowedShape.docx` in Microsoft Word, und Sie sehen ein Rechteck mit einem weichen, 45‑Grad‑Schatten, der zu 30 % transparent ist – genau so, wie wir ihn konfiguriert haben. + +--- + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das **komplette, copy‑and‑paste‑fertige** Programm, das alle oben genannten Schritte enthält. Speichern Sie es als `Program.cs` und führen Sie es mit `dotnet run` aus. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Erwartete Ausgabe:** Eine Datei namens `ShadowedShape.docx`, die ein einzelnes Rechteck mit einem dezenten, halbtransparenten Drop‑Shadow im 45‑Grad‑Winkel enthält. + +--- + +## Varianten & fortgeschrittene Tipps + +### Schattenfarbe ändern + +Standardmäßig übernimmt der Schatten die Füllfarbe der Form, aber Sie können eine eigene Farbe festlegen: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Mehrere Formen mit unterschiedlichen Schatten + +Falls Sie mehrere Formen benötigen, wiederholen Sie einfach die Erstellungs‑ und Konfigurationsschritte. Denken Sie daran, jeder Form einen eindeutigen Namen zu geben, wenn Sie später darauf verweisen wollen. + +### Export nach PDF mit erhaltenen Schatten + +Aspose.Words bewahrt Schatteneffekte beim Speichern als PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Häufige Stolperfallen + +| Symptom | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| Schatten nicht sichtbar | `ShadowFormat.Visible` bleibt `false` | Auf `true` setzen. | +| Schatten wirkt zu hart | `Blur` ist `0` | `Blur` auf 3–6 erhöhen. | +| Schatten verschwindet im PDF | Verwendung einer alten Aspose.Words‑Version (< 22.9) | Auf die neueste Bibliothek aktualisieren. | + +--- + +## Fazit + +Wir haben gezeigt, **wie man Schatten zu einer Form hinzufügt** mit Aspose.Words – von der Initialisierung eines Dokuments bis zur Feinabstimmung von Weichzeichnung, Abstand, Winkel und **Anwenden von Schatten‑Transparenz**. Das vollständige Beispiel demonstriert einen sauberen, produktionsreifen Ansatz, den Sie auf jede Form oder Dokumenten‑Layout anpassen können. + +Haben Sie Fragen zu **create word document using aspose** für komplexere Szenarien – etwa Tabellen mit Schatten oder dynamisch datenbasierte Formen? Hinterlassen Sie einen Kommentar unten oder schauen Sie sich die verwandten Tutorials zu Aspose.Words Bildverarbeitung und Absatzformatierung an. + +Viel Spaß beim Coden und genießen Sie den zusätzlichen visuellen Feinschliff Ihrer Word‑Dokumente! + +--- + +![Schatten zu Form Beispiel](shadowed_shape.png "Schatten zu Form Beispiel") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/greek/words/_index.md b/content/greek/words/_index.md new file mode 100644 index 000000000..93a8ce96c --- /dev/null +++ b/content/greek/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "greek" +type: "family" +--- + +# Words Tutorials diff --git a/content/greek/words/net/_index.md b/content/greek/words/net/_index.md new file mode 100644 index 000000000..bfe5571db --- /dev/null +++ b/content/greek/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "greek" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/greek/words/net/getting-started/_index.md b/content/greek/words/net/getting-started/_index.md new file mode 100644 index 000000000..9eab2f55e --- /dev/null +++ b/content/greek/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "greek" +type: "category" +--- + +# Getting Started diff --git a/content/greek/words/net/getting-started/tutorial/_index.md b/content/greek/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..355cf3a51 --- /dev/null +++ b/content/greek/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,230 @@ +--- +language: el +url: /greek/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Ανίχνευση Ελλειπουσών Γραμματοσειρών σε Έγγραφα Aspose.Words – Πλήρης Οδηγός C# + +Έχετε αναρωτηθεί ποτέ πώς να **ανιχνεύσετε ελλειπούσες γραμματοσειρές** όταν φορτώνετε ένα αρχείο Word με το Aspose.Words; Στην καθημερινή μου εργασία, αντιμετώπισα μερικά PDF που έδειχναν παράξενες εμφανίσεις επειδή το αρχικό έγγραφο χρησιμοποιούσε μια γραμματοσειρά που δεν είχα εγκατεστημένη. Τα καλά νέα; Το Aspose.Words μπορεί να σας πει ακριβώς πότε αντικαθιστά μια γραμματοσειρά, και μπορείτε να καταγράψετε αυτή την πληροφορία με ένα απλό callback προειδοποίησης. + +Σε αυτό το σεμινάριο θα περάσουμε βήμα‑βήμα από ένα **πλήρες, εκτελέσιμο παράδειγμα** που σας δείχνει πώς να καταγράψετε κάθε αντικατάσταση γραμματοσειράς, γιατί το callback είναι σημαντικό, και μερικά επιπλέον κόλπα για αξιόπιστη ανίχνευση ελλειπουσών γραμματοσειρών. Χωρίς περιττές πληροφορίες, μόνο ο κώδικας και η λογική που χρειάζεστε για να το κάνετε λειτουργικό σήμερα. + +--- + +## Τι Θα Μάθετε + +- Πώς να υλοποιήσετε **Aspose.Words warning callback** για να εντοπίζετε συμβάντα αντικατάστασης γραμματοσειράς. +- Πώς να διαμορφώσετε **LoadOptions C#** ώστε το callback να κληθεί κατά τη φόρτωση ενός εγγράφου. +- Πώς να επαληθεύσετε ότι η ανίχνευση ελλειπούσας γραμματοσειράς λειτούργησε πραγματικά και πώς φαίνεται η έξοδος της κονσόλας. + +**Prerequisites** – Χρειάζεστε μια πρόσφατη έκδοση του Aspose.Words για .NET (ο κώδικας δοκιμάστηκε με την 23.12), .NET 6 ή νεότερη, και βασική γνώση της C#. Αν τα έχετε, είστε έτοιμοι να ξεκινήσετε. + +## Ανίχνευση Ελλειπουσών Γραμματοσειρών με ένα Warning Callback + +Η καρδιά της λύσης είναι μια υλοποίηση του `IWarningCallback`. Το Aspose.Words δημιουργεί ένα αντικείμενο `WarningInfo` για πολλές καταστάσεις, αλλά μας ενδιαφέρει μόνο το `WarningType.FontSubstitution`. Ας δούμε πώς να το συνδέσουμε. + +### Βήμα 1: Δημιουργία Συλλέκτη Προειδοποιήσεων Γραμματοσειράς + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Γιατί είναι σημαντικό*: Φιλτράροντας με βάση το `WarningType.FontSubstitution` αποφεύγουμε την ακαταστασία από άσχετες προειδοποιήσεις (όπως παρωχημένες λειτουργίες). Το `info.Description` περιέχει ήδη το αρχικό όνομα της γραμματοσειράς και την εναλλακτική που χρησιμοποιήθηκε, παρέχοντάς σας ένα σαφές ίχνος ελέγχου. + +## Διαμόρφωση LoadOptions για Χρήση του Callback + +Τώρα λέμε στο Aspose.Words να χρησιμοποιεί τον συλλέκτη μας όταν φορτώνει ένα αρχείο. + +### Βήμα 2: Ρύθμιση LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Γιατί είναι σημαντικό*: Το `LoadOptions` είναι το μοναδικό σημείο όπου μπορείτε να ενσωματώσετε το callback, κωδικούς κρυπτογράφησης και άλλες συμπεριφορές φόρτωσης. Κρατώντας το ξεχωριστά από τον κατασκευαστή `Document` κάνει τον κώδικα επαναχρησιμοποιήσιμο για πολλά αρχεία. + +## Φόρτωση του Εγγράφου και Καταγραφή Ελλειπουσών Γραμματοσειρών + +Με το callback συνδεδεμένο, το επόμενο βήμα είναι απλώς η φόρτωση του εγγράφου. + +### Βήμα 3: Φορτώστε το DOCX σας (ή οποιαδήποτε υποστηριζόμενη μορφή) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Όταν ο κατασκευαστής `Document` αναλύει το αρχείο, οποιαδήποτε ελλειπούσα γραμματοσειρά ενεργοποιεί τον `FontWarningCollector`. Η κονσόλα θα εμφανίσει γραμμές όπως: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Αυτή η γραμμή είναι η σαφής απόδειξη ότι η **ανίχνευση ελλειπουσών γραμματοσειρών** λειτούργησε. + +## Επαλήθευση της Εξόδου – Τι να Περιμένετε + +Εκτελέστε το πρόγραμμα από ένα τερματικό ή το Visual Studio. Εάν το πηγαίο έγγραφο περιέχει μια γραμματοσειρά που δεν έχετε εγκατεστημένη, θα δείτε τουλάχιστον μία γραμμή «Font substituted». Εάν το έγγραφο χρησιμοποιεί μόνο εγκατεστημένες γραμματοσειρές, το callback παραμένει σιωπηλό και θα λάβετε μόνο το μήνυμα «Document loaded successfully.». + +**Tip**: Για διπλό έλεγχο, ανοίξτε το αρχείο Word στο Microsoft Word και κοιτάξτε τη λίστα γραμματοσειρών. Οποιαδήποτε γραμματοσειρά εμφανίζεται στο *Replace Fonts* κάτω από την ομάδα *Home → Font* είναι υποψήφια για αντικατάσταση. + +## Προχωρημένο: Ανίχνευση Ελλειπουσών Γραμματοσειρών σε Μαζική Επεξεργασία + +Συχνά χρειάζεται να σαρώσετε δεκάδες αρχεία. Το ίδιο μοτίβο κλιμακώνεται άψογα: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Επειδή ο `FontWarningCollector` γράφει στην κονσόλα κάθε φορά που καλείται, θα λάβετε μια αναφορά ανά αρχείο χωρίς πρόσθετο κώδικα. Για παραγωγικά σενάρια ίσως θέλετε να καταγράφετε σε αρχείο ή βάση δεδομένων – απλώς αντικαταστήστε το `Console.WriteLine` με τον προτιμώμενο logger σας. + +## Συνηθισμένα Προβλήματα & Επαγγελματικές Συμβουλές + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|----------|------------------|----------| +| **Δεν εμφανίζονται προειδοποιήσεις** | Το έγγραφο περιέχει μόνο εγκατεστημένες γραμματοσειρές. | Επαληθεύστε ανοίγοντας το αρχείο στο Word ή αφαιρώντας σκόπιμα μια γραμματοσειρά από το σύστημα. | +| **Το callback δεν κλήθηκε** | `LoadOptions.WarningCallback` δεν είχε ποτέ ανατεθεί ή χρησιμοποιήθηκε νέα παρουσία `LoadOptions` αργότερα. | Διατηρήστε ένα μόνο αντικείμενο `LoadOptions` και επαναχρησιμοποιήστε το για κάθε φόρτωση. | +| **Πάρα πολλές άσχετες προειδοποιήσεις** | Δεν φιλτράρατε με βάση το `WarningType.FontSubstitution`. | Προσθέστε την προστασία `if (info.Type == WarningType.FontSubstitution)` όπως φαίνεται. | +| **Μείωση απόδοσης σε τεράστια αρχεία** | Το callback εκτελείται για κάθε προειδοποίηση, που μπορεί να είναι πολλές σε μεγάλα έγγραφα. | Απενεργοποιήστε άλλους τύπους προειδοποιήσεων μέσω `LoadOptions.WarningCallback` ή ορίστε το `LoadOptions.LoadFormat` σε συγκεκριμένο τύπο αν το γνωρίζετε. | + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Αναμενόμενη έξοδος κονσόλας** (όταν εντοπιστεί ελλειπούσα γραμματοσειρά): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Εάν δεν γίνει αντικατάσταση, θα δείτε μόνο τη γραμμή επιτυχίας. + +## Συμπέρασμα + +Τώρα έχετε έναν **πλήρη, έτοιμο για παραγωγή τρόπο ανίχνευσης ελλειπουσών γραμματοσειρών** σε οποιοδήποτε έγγραφο επεξεργάζεται το Aspose.Words. Εκμεταλλευόμενοι το **Aspose.Words warning callback** και διαμορφώνοντας το **LoadOptions C#**, μπορείτε να καταγράψετε κάθε αντικατάσταση γραμματοσειράς, να εντοπίσετε προβλήματα διάταξης και να διασφαλίσετε ότι τα PDF σας διατηρούν την προοριζόμενη εμφάνιση. + +Από ένα μόνο αρχείο έως μια τεράστια δέσμη, το μοτίβο παραμένει το ίδιο — υλοποιήστε το `IWarningCallback`, ενσωματώστε το στο `LoadOptions`, και αφήστε το Aspose.Words να κάνει το δύσκολο έργο. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να συνδυάσετε αυτό με **font embedding** ή **fallback font families** για να διορθώσετε αυτόματα το πρόβλημα, ή εξερευνήστε το API **DocumentVisitor** για πιο βαθιά ανάλυση του περιεχομένου. Καλό προγραμματισμό, και εύχομαι όλες οι γραμματοσειρές σας να παραμένουν εκεί που τις περιμένετε! + +--- + +![Ανίχνευση ελλειπουσών γραμματοσειρών σε Aspose.Words – στιγμιότυπο εξόδου κονσόλας](https://example.com/images/detect-missing-fonts.png "εξαγωγή κονσόλας ανίχνευσης ελλειπουσών γραμματοσειρών") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/greek/words/net/images-and-shapes/_index.md b/content/greek/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..ddcf8f47e --- /dev/null +++ b/content/greek/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "greek" +type: "category" +--- + +# Images And Shapes diff --git a/content/greek/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/greek/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..902d25661 --- /dev/null +++ b/content/greek/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Προσθέστε γρήγορα σκιά σε σχήμα με το Aspose.Words. Μάθετε πώς να δημιουργήσετε + έγγραφο Word χρησιμοποιώντας το Aspose, πώς να προσθέσετε σκιά σε σχήμα και πώς + να εφαρμόσετε διαφάνεια σκιάς σε C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: el +og_description: Προσθέστε σκιά σε σχήμα σε αρχείο Word χρησιμοποιώντας το Aspose.Words. + Αυτός ο οδηγός βήμα‑προς‑βήμα δείχνει πώς να δημιουργήσετε ένα έγγραφο, να προσθέσετε + ένα σχήμα και να εφαρμόσετε διαφάνεια στη σκιά. +og_title: Προσθήκη Σκιάς στο Σχήμα – Εκπαιδευτικό Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Προσθήκη Σκιάς σε Σχήμα σε Έγγραφο Word – Πλήρης Οδηγός Aspose.Words +url: /greek/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Προσθήκη Σκιάς σε Σχήμα – Πλήρης Οδηγός Aspose.Words + +Έχετε χρειαστεί ποτέ να **προσθέσετε σκιά σε σχήμα** σε ένα αρχείο Word αλλά δεν ήξερες ποιες κλήσεις API να χρησιμοποιήσεις; Δεν είστε μόνοι. Πολλοί προγραμματιστές συναντούν δυσκολίες όταν προσπαθούν για πρώτη φορά να δώσουν σε ένα ορθογώνιο ή οποιοδήποτε στοιχείο σχεδίασης μια σωστή σκιά, ειδικά όταν εργάζονται με το Aspose.Words for .NET. + +Σε αυτό το tutorial θα περάσουμε από όλα όσα χρειάζεστε: από τη **δημιουργία εγγράφου Word χρησιμοποιώντας Aspose** μέχρι τη διαμόρφωση της σκιάς, την προσαρμογή της θολώσεως, της απόστασης, της γωνίας και ακόμη και την **εφαρμογή διαφάνειας στη σκιά**. Στο τέλος θα έχετε ένα έτοιμο πρόγραμμα C# που παράγει ένα αρχείο `.docx` με ένα όμορφα σκιασμένο ορθογώνιο—χωρίς χειροκίνητη παρέμβαση στο Word. + +--- + +## Τι Θα Μάθετε + +- Πώς να ρυθμίσετε ένα έργο Aspose.Words στο Visual Studio. +- Τα ακριβή βήματα για **δημιουργία εγγράφου Word χρησιμοποιώντας Aspose** και εισαγωγή σχήματος. +- **Πώς να προσθέσετε σκιά σε σχήμα** με πλήρη έλεγχο της θολώσεως, της απόστασης, της γωνίας και της διαφάνειας. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων (π.χ. έλλειψη άδειας, λανθασμένες μονάδες). +- Ένα πλήρες, αντιγραφή‑και‑επικόλληση δείγμα κώδικα που μπορείτε να τρέξετε σήμερα. + +> **Προαπαιτούμενα:** .NET 6+ (ή .NET Framework 4.7.2+), έγκυρη άδεια Aspose.Words (ή η δωρεάν δοκιμή), και βασική εξοικείωση με C#. + +--- + +## Βήμα 1 – Ρύθμιση του Έργου και Προσθήκη Aspose.Words + +Πρώτα απ' όλα. Ανοίξτε το Visual Studio, δημιουργήστε μια νέα **Console App (.NET Core)**, και προσθέστε το πακέτο NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** Αν έχετε αρχείο άδειας (`Aspose.Words.lic`), αντιγράψτε το στη ρίζα του έργου και φορτώστε το κατά την εκκίνηση. Αυτό αποφεύγει το υδατογράφημα που εμφανίζεται στη δωρεάν λειτουργία αξιολόγησης. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Βήμα 2 – Δημιουργία Νέου Κενού Εγγράφου + +Τώρα δημιουργούμε πραγματικά **το έγγραφο Word χρησιμοποιώντας Aspose**. Αυτό το αντικείμενο θα λειτουργήσει ως καμβάς για το σχήμα μας. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Η κλάση `Document` είναι το σημείο εισόδου για όλα τα υπόλοιπα—παραγράφους, ενότητες και, φυσικά, αντικείμενα σχεδίασης. + +--- + +## Βήμα 3 – Εισαγωγή Σχήματος Ορθογωνίου + +Με το έγγραφο έτοιμο, μπορούμε να προσθέσουμε ένα σχήμα. Εδώ επιλέγουμε ένα απλό ορθογώνιο, αλλά η ίδια λογική λειτουργεί για κύκλους, γραμμές ή προσαρμοσμένα πολύγωνα. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Γιατί σχήμα;** Στο Aspose.Words ένα αντικείμενο `Shape` μπορεί να περιέχει κείμενο, εικόνες ή απλώς να λειτουργεί ως διακοσμητικό στοιχείο. Η προσθήκη σκιάς σε σχήμα είναι πολύ πιο εύκολη από το να προσπαθήσετε να χειριστείτε ένα πλαίσιο εικόνας. + +--- + +## Βήμα 4 – Διαμόρφωση της Σκιάς (Add Shadow to Shape) + +Αυτό είναι το κεντρικό μέρος του tutorial—**πώς να προσθέσετε σκιά σε σχήμα** και να ρυθμίσετε την εμφάνισή της. Η ιδιότητα `ShadowFormat` σας δίνει πλήρη έλεγχο. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Τι Κάνει Κάθε Ιδιότητα + +| Ιδιότητα | Επίδραση | Τυπικές Τιμές | +|----------|----------|----------------| +| **Visible** | Ενεργοποιεί/απενεργοποιεί τη σκιά. | `true` / `false` | +| **Blur** | Μαλακώνει τις άκρες της σκιάς. | `0` (σκληρή) έως `10` (πολύ μαλακή) | +| **Distance** | Μετακινεί τη σκιά μακριά από το σχήμα. | `1`–`5` points είναι κοινό | +| **Angle** | Ελέγχει την κατεύθυνση της μετατόπισης. | `0`–`360` μοίρες | +| **Transparency** | Κάνει τη σκιά μερικώς διαφανή. | `0` (αδιαφανής) έως `1` (αόρατη) | + +> **Edge case:** Αν ορίσετε `Transparency` σε `1`, η σκιά εξαφανίζεται εντελώς—χρήσιμο για προγραμματιστική εναλλαγή. + +--- + +## Βήμα 5 – Προσθήκη του Σχήματος στο Έγγραφο + +Τώρα συνδέουμε το σχήμα στην πρώτη παράγραφο του σώματος του εγγράφου. Το Aspose δημιουργεί αυτόματα μια παράγραφο αν δεν υπάρχει. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Αν το έγγραφό σας περιέχει ήδη περιεχόμενο, μπορείτε να εισάγετε το σχήμα σε οποιονδήποτε κόμβο χρησιμοποιώντας `InsertAfter` ή `InsertBefore`. + +--- + +## Βήμα 6 – Αποθήκευση του Εγγράφου + +Τέλος, γράψτε το αρχείο στο δίσκο. Μπορείτε να επιλέξετε οποιαδήποτε υποστηριζόμενη μορφή (`.docx`, `.pdf`, `.odt`, κλπ.), αλλά για αυτό το tutorial θα μείνουμε στη γονική μορφή Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Ανοίξτε το παραγόμενο `ShadowedShape.docx` στο Microsoft Word και θα δείτε ένα ορθογώνιο με μια ήπια σκιά 45 μοιρών που είναι 30 % διαφανής—ακριβώς όπως το ρυθμίσαμε. + +--- + +## Πλήρες Παράδειγμα Εργασίας + +Παρακάτω είναι το **πλήρες, έτοιμο για αντιγραφή‑και‑επικόλληση** πρόγραμμα που ενσωματώνει όλα τα παραπάνω βήματα. Αποθηκεύστε το ως `Program.cs` και τρέξτε το με `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Αναμενόμενο αποτέλεσμα:** Ένα αρχείο με όνομα `ShadowedShape.docx` που περιέχει ένα μόνο ορθογώνιο με μια διακριτική, ημιδιαφανή σκιά που κατευθύνεται στις 45°. + +--- + +## Παραλλαγές & Προχωρημένες Συμβουλές + +### Αλλαγή Χρώματος Σκιάς + +Από προεπιλογή η σκιά κληρονομεί το χρώμα γεμίσματος του σχήματος, αλλά μπορείτε να ορίσετε προσαρμοσμένο χρώμα: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Πολλά Σχήματα με Διαφορετικές Σκιές + +Αν χρειάζεστε πολλά σχήματα, απλώς επαναλάβετε τα βήματα δημιουργίας και διαμόρφωσης. Θυμηθείτε να δώσετε σε κάθε σχήμα μοναδικό όνομα αν σκοπεύετε να το αναφέρετε αργότερα. + +### Εξαγωγή σε PDF με Διατηρημένες Σκιές + +Το Aspose.Words διατηρεί τα εφέ σκιάς κατά την αποθήκευση σε PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Συνηθισμένα Προβλήματα + +| Συμπτωμα | Πιθανή Αιτία | Διόρθωση | +|----------|--------------|----------| +| Η σκιά δεν εμφανίζεται | `ShadowFormat.Visible` παραμένει `false` | Ορίστε σε `true`. | +| Η σκιά φαίνεται πολύ σκληρή | `Blur` ορίστηκε σε `0` | Αυξήστε το `Blur` σε 3–6. | +| Η σκιά εξαφανίζεται σε PDF | Χρήση παλιάς έκδοσης Aspose.Words (< 22.9) | Αναβαθμίστε στην πιο πρόσφατη βιβλιοθήκη. | + +--- + +## Συμπέρασμα + +Καλύψαμε **πώς να προσθέσετε σκιά σε σχήμα** χρησιμοποιώντας Aspose.Words, από την αρχικοποίηση ενός εγγράφου μέχρι τη λεπτομερή ρύθμιση της θολώσεως, της απόστασης, της γωνίας και της **εφαρμογής διαφάνειας στη σκιά**. Το πλήρες παράδειγμα δείχνει μια καθαρή, έτοιμη για παραγωγή προσέγγιση που μπορείτε να προσαρμόσετε σε οποιοδήποτε σχήμα ή διάταξη εγγράφου. + +Έχετε ερωτήσεις σχετικά με **δημιουργία εγγράφου Word χρησιμοποιώντας Aspose** για πιο σύνθετα σενάρια—όπως πίνακες με σκιές ή σχήματα που δημιουργούνται δυναμικά από δεδομένα; Αφήστε ένα σχόλιο παρακάτω ή ρίξτε μια ματιά στα συναφή tutorials για διαχείριση εικόνων και μορφοποίηση παραγράφων στο Aspose.Words. + +Καλή προγραμματιστική δουλειά, και απολαύστε το επιπλέον οπτικό polish στα έγγραφα Word σας! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hindi/words/_index.md b/content/hindi/words/_index.md new file mode 100644 index 000000000..8eb61d100 --- /dev/null +++ b/content/hindi/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "hindi" +type: "family" +--- + +# Words Tutorials diff --git a/content/hindi/words/net/_index.md b/content/hindi/words/net/_index.md new file mode 100644 index 000000000..bd5e848ea --- /dev/null +++ b/content/hindi/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "hindi" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/hindi/words/net/getting-started/_index.md b/content/hindi/words/net/getting-started/_index.md new file mode 100644 index 000000000..02e031052 --- /dev/null +++ b/content/hindi/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "hindi" +type: "category" +--- + +# Getting Started diff --git a/content/hindi/words/net/getting-started/tutorial/_index.md b/content/hindi/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..e2db31d39 --- /dev/null +++ b/content/hindi/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,246 @@ +--- +language: hi +url: /hindi/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Aspose.Words दस्तावेज़ों में लापता फ़ॉन्ट्स का पता लगाएँ – पूर्ण C# गाइड + +क्या आपने कभी सोचा है कि Aspose.Words के साथ Word फ़ाइल लोड करते समय **लापता फ़ॉन्ट्स** का पता कैसे लगाया जाए? मेरे दैनिक काम में, मैंने कुछ PDF देखे हैं जो ठीक नहीं लग रहे थे क्योंकि मूल दस्तावेज़ में ऐसा फ़ॉन्ट इस्तेमाल हुआ था जो मेरे सिस्टम में स्थापित नहीं था। अच्छी खबर? Aspose.Words आपको बिल्कुल बता सकता है जब वह फ़ॉन्ट को बदलता है, और आप इस जानकारी को एक साधारण warning callback के साथ कैप्चर कर सकते हैं। + +इस ट्यूटोरियल में हम एक **पूर्ण, चलाने योग्य उदाहरण** के माध्यम से चलेंगे जो दिखाता है कि हर फ़ॉन्ट प्रतिस्थापन को कैसे लॉग किया जाए, callback क्यों महत्वपूर्ण है, और मजबूत लापता‑फ़ॉन्ट पहचान के लिए कुछ अतिरिक्त ट्रिक्स। कोई फालतू बात नहीं, सिर्फ कोड और वह तर्क जो आपको इसे आज ही काम करने में मदद करेगा। + +--- + +## आप क्या सीखेंगे + +- **Aspose.Words warning callback** को लागू करके फ़ॉन्ट प्रतिस्थापन इवेंट्स को कैसे पकड़ें। +- **LoadOptions C#** को इस प्रकार कॉन्फ़िगर करें कि दस्तावेज़ लोड करते समय callback कॉल हो। +- यह सत्यापित करें कि लापता‑फ़ॉन्ट पहचान वास्तव में काम कर रही है, और कंसोल आउटपुट कैसा दिखता है। + +**Prerequisites** – आपको Aspose.Words for .NET का नवीनतम संस्करण चाहिए (कोड 23.12 के साथ परीक्षण किया गया था), .NET 6 या बाद का, और C# की बुनियादी समझ। यदि आपके पास ये हैं, तो आप शुरू करने के लिए तैयार हैं। + +--- + +## Warning Callback के साथ लापता फ़ॉन्ट्स का पता लगाएँ + +समाधान का मुख्य भाग `IWarningCallback` का कार्यान्वयन है। Aspose.Words कई स्थितियों में `WarningInfo` ऑब्जेक्ट फायर करता है, लेकिन हमें केवल `WarningType.FontSubstitution` की परवाह है। चलिए देखते हैं कि इसे कैसे हुक किया जाए। + +### चरण 1: फ़ॉन्ट‑वॉर्निंग कलेक्टर बनाएं + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Why this matters*: `WarningType.FontSubstitution` पर फ़िल्टर करके हम असंबंधित चेतावनियों (जैसे deprecated features) से बचते हैं। `info.Description` में पहले से ही मूल फ़ॉन्ट नाम और उपयोग किया गया fallback शामिल होता है, जो आपको एक स्पष्ट ऑडिट ट्रेल देता है। + +--- + +## Callback उपयोग करने के लिए LoadOptions कॉन्फ़िगर करें + +अब हम Aspose.Words को बताते हैं कि फ़ाइल लोड करते समय हमारा कलेक्टर उपयोग करे। + +### चरण 2: LoadOptions सेट अप करें + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Why this matters*: `LoadOptions` वह एकमात्र जगह है जहाँ आप callback, एन्क्रिप्शन पासवर्ड और अन्य लोडिंग व्यवहार जोड़ सकते हैं। इसे `Document` कंस्ट्रक्टर से अलग रखने से कोड कई फ़ाइलों में पुन: उपयोग योग्य बनता है। + +--- + +## दस्तावेज़ लोड करें और लापता फ़ॉन्ट्स को कैप्चर करें + +callback को जोड़ने के बाद, अगला कदम बस दस्तावेज़ को लोड करना है। + +### चरण 3: अपना DOCX (या कोई भी समर्थित फ़ॉर्मेट) लोड करें + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +जब `Document` कंस्ट्रक्टर फ़ाइल को पार्स करता है, तो कोई भी लापता फ़ॉन्ट हमारे `FontWarningCollector` को ट्रिगर करता है। कंसोल में इस तरह की पंक्तियाँ दिखेंगी: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +वह पंक्ति यह ठोस प्रमाण है कि **लापता फ़ॉन्ट्स का पता लगाना** काम किया। + +--- + +## आउटपुट सत्यापित करें – क्या अपेक्षित है + +प्रोग्राम को टर्मिनल या Visual Studio से चलाएँ। यदि स्रोत दस्तावेज़ में ऐसा फ़ॉन्ट है जो आपके सिस्टम में स्थापित नहीं है, तो आपको कम से कम एक “Font substituted” पंक्ति दिखेगी। यदि दस्तावेज़ केवल स्थापित फ़ॉन्ट्स का उपयोग करता है, तो callback चुप रहेगा और आपको केवल “Document loaded successfully.” संदेश मिलेगा। + +**Tip**: दोबारा जांचने के लिए, Word फ़ाइल को Microsoft Word में खोलें और फ़ॉन्ट सूची देखें। कोई भी फ़ॉन्ट जो *Home → Font* समूह के तहत *Replace Fonts* में दिखाई देता है, वह प्रतिस्थापन का उम्मीदवार है। + +--- + +## उन्नत: बैच में लापता फ़ॉन्ट्स का पता लगाएँ + +अक्सर आपको दर्जनों फ़ाइलों को स्कैन करना पड़ता है। वही पैटर्न आसानी से स्केल करता है: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +क्योंकि `FontWarningCollector` हर बार कॉल होने पर कंसोल में लिखता है, आपको अतिरिक्त सेटअप के बिना प्रति‑फ़ाइल रिपोर्ट मिल जाएगी। प्रोडक्शन परिदृश्यों में आप इसे फ़ाइल या डेटाबेस में लॉग करना चाह सकते हैं – बस `Console.WriteLine` को अपने पसंदीदा logger से बदल दें। + +--- + +## सामान्य समस्याएँ और प्रो टिप्स + +| समस्या | क्यों होता है | समाधान | +|-------|----------------|-----| +| **कोई चेतावनी नहीं दिखती** | दस्तावेज़ वास्तव में केवल स्थापित फ़ॉन्ट्स ही रखता है। | फ़ाइल को Word में खोलकर या जानबूझकर अपने सिस्टम से एक फ़ॉन्ट हटाकर सत्यापित करें। | +| **Callback नहीं बुलाया गया** | `LoadOptions.WarningCallback` कभी असाइन नहीं किया गया या बाद में नया `LoadOptions` इंस्टेंस उपयोग किया गया। | एक ही `LoadOptions` ऑब्जेक्ट रखें और हर लोड के लिए पुन: उपयोग करें। | +| **बहुत सारी असंबंधित चेतावनियां** | आपने `WarningType.FontSubstitution` द्वारा फ़िल्टर नहीं किया। | जैसा दिखाया गया है, `if (info.Type == WarningType.FontSubstitution)` गार्ड जोड़ें। | +| **बड़ी फ़ाइलों पर प्रदर्शन धीमा** | Callback हर चेतावनी पर चलता है, जो बड़े दस्तावेज़ों में बहुत हो सकता है। | `LoadOptions.WarningCallback` के माध्यम से अन्य चेतावनी प्रकारों को अक्षम करें या यदि आप जानते हैं तो `LoadOptions.LoadFormat` को विशिष्ट प्रकार पर सेट करें। | + +--- + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**अपेक्षित कंसोल आउटपुट** (जब लापता फ़ॉन्ट मिलता है): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +यदि कोई प्रतिस्थापन नहीं होता, तो आप केवल सफलता पंक्ति देखेंगे। + +--- + +## निष्कर्ष + +अब आपके पास Aspose.Words द्वारा प्रोसेस किए गए किसी भी दस्तावेज़ में लापता फ़ॉन्ट्स का पता लगाने का **पूर्ण, प्रोडक्शन‑रेडी तरीका** है। **Aspose.Words warning callback** का उपयोग करके और **LoadOptions C#** को कॉन्फ़िगर करके, आप हर फ़ॉन्ट प्रतिस्थापन को लॉग कर सकते हैं, लेआउट समस्याओं का समाधान कर सकते हैं, और सुनिश्चित कर सकते हैं कि आपके PDF इच्छित लुक‑एंड‑फ़ील को बनाए रखें। + +एक फ़ाइल से लेकर बड़े बैच तक, पैटर्न वही रहता है—`IWarningCallback` को लागू करें, इसे `LoadOptions` में प्लग करें, और Aspose.Words को भारी काम करने दें। + +अगले कदम के लिए तैयार हैं? इसको **फ़ॉन्ट एम्बेडिंग** या **फ़ॉलबैक फ़ॉन्ट फ़ैमिली** के साथ मिलाकर समस्या को स्वचालित रूप से ठीक करने का प्रयास करें, या गहरी सामग्री विश्लेषण के लिए **DocumentVisitor** API देखें। कोडिंग का आनंद लें, और आपके सभी फ़ॉन्ट्स जहाँ आप उम्मीद करते हैं, वहीं रहें! + +--- + +![Aspose.Words में लापता फ़ॉन्ट्स का पता – कंसोल आउटपुट स्क्रीनशॉट](https://example.com/images/detect-missing-fonts.png "लापता फ़ॉन्ट्स कंसोल आउटपुट") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hindi/words/net/images-and-shapes/_index.md b/content/hindi/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..6f5da9a9a --- /dev/null +++ b/content/hindi/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "hindi" +type: "category" +--- + +# Images And Shapes diff --git a/content/hindi/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/hindi/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..d57d31a58 --- /dev/null +++ b/content/hindi/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2025-12-08 +description: Aspose.Words के साथ शीघ्रता से आकार में छाया जोड़ें। Aspose का उपयोग + करके Word दस्तावेज़ बनाना, आकार में छाया जोड़ना, और C# में छाया की पारदर्शिता लागू + करना सीखें। +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: hi +og_description: Aspose.Words का उपयोग करके Word फ़ाइल में आकार पर छाया जोड़ें। यह + चरण‑दर‑चरण गाइड दिखाता है कि दस्तावेज़ कैसे बनाएं, आकार जोड़ें, और छाया की पारदर्शिता + कैसे लागू करें। +og_title: आकार में छाया जोड़ें – Aspose.Words C# ट्यूटोरियल +tags: +- Aspose.Words +- C# +- Word Automation +title: Word दस्तावेज़ में आकृति पर छाया जोड़ें – पूर्ण Aspose.Words गाइड +url: /hindi/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# आकार में छाया जोड़ें – पूर्ण Aspose.Words गाइड + +क्या आपको कभी Word फ़ाइल में **add shadow to shape** जोड़ने की ज़रूरत पड़ी है लेकिन कौन से API कॉल्स उपयोग करने हैं, इस बात को लेकर अनिश्चित रहे हैं? आप अकेले नहीं हैं। कई डेवलपर्स पहली बार जब एक आयत या किसी भी ड्राइंग एलिमेंट को उचित ड्रॉप‑शैडो देने की कोशिश करते हैं, तो वे अटक जाते हैं, विशेषकर जब वे Aspose.Words for .NET के साथ काम कर रहे होते हैं। + +इस ट्यूटोरियल में हम आपको वह सब कुछ बताएँगे जो आपको जानना आवश्यक है: **creating a Word document using Aspose** से लेकर शैडो को कॉन्फ़िगर करने, उसके ब्लर, दूरी, कोण, और यहाँ तक कि **applying shadow transparency** तक। अंत तक आपके पास एक तैयार‑चलाने योग्य C# प्रोग्राम होगा जो एक `.docx` फ़ाइल बनाता है जिसमें एक सुंदर शेडेड आयत होती है—Word में मैन्युअल हस्तक्षेप की आवश्यकता नहीं। + +--- + +## आप क्या सीखेंगे + +- Visual Studio में Aspose.Words प्रोजेक्ट सेट अप करने का तरीका। +- **create Word document using Aspose** और एक shape डालने के सटीक कदम। +- **How to add shape shadow** ब्लर, दूरी, कोण, और ट्रांसपेरेंसी पर पूर्ण नियंत्रण के साथ। +- सामान्य समस्याओं (जैसे, लाइसेंस गायब होना, गलत यूनिट) को हल करने के टिप्स। +- एक पूर्ण, कॉपी‑एंड‑पेस्ट कोड सैंपल जिसे आप आज ही चला सकते हैं। + +> **Prerequisites:** .NET 6+ (या .NET Framework 4.7.2+), एक वैध Aspose.Words लाइसेंस (या फ्री ट्रायल), और C# की बुनियादी परिचितता। + +## चरण 1 – अपना प्रोजेक्ट सेट अप करें और Aspose.Words जोड़ें + +सबसे पहले, Visual Studio खोलें, एक नया **Console App (.NET Core)** बनाएं, और Aspose.Words NuGet पैकेज जोड़ें: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** यदि आपके पास लाइसेंस फ़ाइल (`Aspose.Words.lic`) है, तो उसे प्रोजेक्ट रूट में कॉपी करें और स्टार्टअप पर लोड करें। इससे फ्री इवैल्यूएशन मोड में दिखाई देने वाला वाटरमार्क हट जाता है। + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## चरण 2 – एक नया खाली दस्तावेज़ बनाएं + +अब हम वास्तव में **create Word document using Aspose** करेंगे। यह ऑब्जेक्ट हमारे shape के लिए कैनवास के रूप में काम करेगा। + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` क्लास बाकी सब चीज़ों—पैराग्राफ, सेक्शन, और बेशक, ड्राइंग ऑब्जेक्ट्स—के लिए एंट्री पॉइंट है। + +## चरण 3 – एक आयताकार Shape डालें + +डॉक्यूमेंट तैयार होने पर, हम एक shape जोड़ सकते हैं। यहाँ हम एक साधारण आयत चुनते हैं, लेकिन वही लॉजिक सर्कल, लाइन, या कस्टम पॉलीगॉन के लिए भी काम करता है। + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Why a shape?** Aspose.Words में एक `Shape` ऑब्जेक्ट टेक्स्ट, इमेजेज़ रख सकता है, या सिर्फ एक सजावटी तत्व के रूप में कार्य कर सकता है। एक shape में शैडो जोड़ना picture frame को मैनिपुलेट करने से बहुत आसान है। + +## चरण 4 – शैडो कॉन्फ़िगर करें (Add Shadow to Shape) + +यह ट्यूटोरियल का मुख्य भाग है—**how to add shape shadow** और उसकी उपस्थिति को बारीकी से ट्यून करना। `ShadowFormat` प्रॉपर्टी आपको पूर्ण नियंत्रण देती है। + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### प्रत्येक प्रॉपर्टी क्या करती है + +| प्रॉपर्टी | प्रभाव | सामान्य मान | +|----------|--------|----------------| +| **Visible** | शैडो को ऑन/ऑफ़ करता है। | `true` / `false` | +| **Blur** | शैडो के किनारों को नरम करता है। | `0` (hard) to `10` (very soft) | +| **Distance** | शैडो को shape से दूर ले जाता है। | `1`–`5` points is common | +| **Angle** | ऑफ़सेट की दिशा को नियंत्रित करता है। | `0`–`360` degrees | +| **Transparency** | शैडो को आंशिक रूप से पारदर्शी बनाता है। | `0` (opaque) to `1` (invisible) | + +> **Edge case:** यदि आप `Transparency` को `1` सेट करते हैं, तो शैडो पूरी तरह गायब हो जाता है—प्रोग्रामेटिक रूप से इसे टॉगल करने के लिए उपयोगी। + +## चरण 5 – Shape को दस्तावेज़ में जोड़ें + +अब हम shape को दस्तावेज़ के बॉडी के पहले पैराग्राफ से जोड़ते हैं। यदि कोई पैराग्राफ नहीं है तो Aspose स्वचालित रूप से एक पैराग्राफ बना देता है। + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +यदि आपके दस्तावेज़ में पहले से सामग्री है, तो आप `InsertAfter` या `InsertBefore` का उपयोग करके shape को किसी भी नोड पर डाल सकते हैं। + +## चरण 6 – दस्तावेज़ को सेव करें + +अंत में, फ़ाइल को डिस्क पर लिखें। आप कोई भी समर्थित फ़ॉर्मेट (`.docx`, `.pdf`, `.odt`, आदि) चुन सकते हैं, लेकिन इस ट्यूटोरियल के लिए हम मूल Word फ़ॉर्मेट ही उपयोग करेंगे। + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +परिणामी `ShadowedShape.docx` को Microsoft Word में खोलें, और आपको एक आयत दिखेगी जिसमें एक नरम, 45‑डिग्री शैडो है जो 30 % पारदर्शी है—बिल्कुल वही जो हमने कॉन्फ़िगर किया था। + +## पूर्ण कार्यशील उदाहरण + +नीचे **complete, copy‑and‑paste ready** प्रोग्राम है जो ऊपर बताए सभी चरणों को सम्मिलित करता है। इसे `Program.cs` के रूप में सेव करें और `dotnet run` से चलाएँ। + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Expected output:** `ShadowedShape.docx` नाम की फ़ाइल जिसमें एक ही आयत है जिसमें 45° के कोण पर एक सूक्ष्म, अर्ध‑पारदर्शी ड्रॉप शैडो है। + +## विविधताएँ और उन्नत टिप्स + +### शैडो रंग बदलना + +डिफ़ॉल्ट रूप से शैडो shape के फ़िल रंग को विरासत में लेता है, लेकिन आप एक कस्टम रंग सेट कर सकते हैं: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### विभिन्न शैडो वाले कई Shapes + +यदि आपको कई shapes चाहिए, तो बस निर्माण और कॉन्फ़िगरेशन चरणों को दोहराएँ। यदि आप बाद में उन्हें रेफ़र करने की योजना बनाते हैं तो प्रत्येक shape को एक अनूठा नाम देना याद रखें। + +### शैडो संरक्षित रखते हुए PDF में एक्सपोर्ट करना + +PDF में सेव करते समय Aspose.Words शैडो इफ़ेक्ट्स को संरक्षित रखता है: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### सामान्य समस्याएँ + +| लक्षण | संभावित कारण | समाधान | +|---------|--------------|-----| +| शैडो दिखाई नहीं दे रहा | `ShadowFormat.Visible` left as `false` | Set to `true`. | +| शैडो बहुत कठोर दिख रहा है | `Blur` set to `0` | Increase `Blur` to 3–6. | +| PDF में शैडो गायब हो जाता है | पुराना Aspose.Words संस्करण (< 22.9) उपयोग करना | Upgrade to the latest library. | + +## निष्कर्ष + +हमने Aspose.Words का उपयोग करके **how to add shadow to shape** को कवर किया है, दस्तावेज़ को इनिशियलाइज़ करने से लेकर ब्लर, दूरी, कोण, और **applying shadow transparency** को बारीकी से ट्यून करने तक। पूर्ण उदाहरण एक साफ़, प्रोडक्शन‑रेडी अप्रोच दिखाता है जिसे आप किसी भी shape या दस्तावेज़ लेआउट में अनुकूलित कर सकते हैं। + +यदि आपके पास **create word document using aspose** के बारे में अधिक जटिल परिदृश्यों—जैसे शैडो वाले टेबल या डायनामिक डेटा‑ड्रिवेन shapes—के बारे में प्रश्न हैं, तो नीचे टिप्पणी छोड़ें या Aspose.Words इमेज हैंडलिंग और पैराग्राफ फ़ॉर्मेटिंग पर संबंधित ट्यूटोरियल देखें। + +कोडिंग का आनंद लें, और अपने Word दस्तावेज़ों को वह अतिरिक्त विज़ुअल पॉलिश देने का मज़ा उठाएँ! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hongkong/words/_index.md b/content/hongkong/words/_index.md new file mode 100644 index 000000000..8c1ae0c3d --- /dev/null +++ b/content/hongkong/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "hongkong" +type: "family" +--- + +# Words Tutorials diff --git a/content/hongkong/words/net/_index.md b/content/hongkong/words/net/_index.md new file mode 100644 index 000000000..068372d8d --- /dev/null +++ b/content/hongkong/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "hongkong" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/hongkong/words/net/getting-started/_index.md b/content/hongkong/words/net/getting-started/_index.md new file mode 100644 index 000000000..016d3c867 --- /dev/null +++ b/content/hongkong/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "hongkong" +type: "category" +--- + +# Getting Started diff --git a/content/hongkong/words/net/getting-started/tutorial/_index.md b/content/hongkong/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..506dd26df --- /dev/null +++ b/content/hongkong/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: zh-hant +url: /hongkong/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# 偵測 Aspose.Words 文件中缺失字型 – 完整 C# 指南 + +有沒有想過在使用 Aspose.Words 載入 Word 檔案時,如何 **偵測缺失的字型**?在我的日常工作中,我曾遇到過幾個 PDF 看起來怪怪的,因為原始文件使用了我電腦上未安裝的字型。好消息是?Aspose.Words 能夠精確告訴你何時替換了字型,且你可以透過簡單的 warning callback 取得這些資訊。 + +在本教學中,我們將逐步說明一個 **完整、可執行的範例**,展示如何記錄每一次字型替換、為何需要此 callback,以及幾個額外技巧,以實現穩健的缺失字型偵測。沒有多餘的說明,只有你今天就能運作的程式碼與原理。 + +--- + +## 你將學到 + +- 如何實作 **Aspose.Words warning callback** 以捕捉字型替換事件。 +- 如何設定 **LoadOptions C#**,使在載入文件時觸發 callback。 +- 如何驗證缺失字型偵測確實生效,以及 console 輸出長什麼樣子。 +- 可選的調整方式,適用於大量批次或無頭環境。 + +**先決條件** – 你需要最新版的 Aspose.Words for .NET(程式碼已在 23.12 版本測試),.NET 6 或更新版本,以及基本的 C# 知識。只要具備這些,就可以開始了。 + +--- + +## 使用 Warning Callback 偵測缺失字型 + +此解決方案的核心是實作 `IWarningCallback`。Aspose.Words 會在多種情況下拋出 `WarningInfo` 物件,但我們只關注 `WarningType.FontSubstitution`。讓我們看看如何掛接它。 + +### 步驟 1:建立字型警告收集器 + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*為何重要*:透過篩選 `WarningType.FontSubstitution`,我們可以避免與字型無關的警告(例如已棄用的功能)造成雜訊。`info.Description` 已包含原始字型名稱與使用的備援字型,讓你得到清晰的稽核紀錄。 + +--- + +## 設定 LoadOptions 以使用 Callback + +現在我們告訴 Aspose.Words 在載入檔案時使用我們的收集器。 + +### 步驟 2:設定 LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*為何重要*:`LoadOptions` 是唯一可以插入 callback、加密密碼以及其他載入行為的地方。將它與 `Document` 建構子分離,使程式碼能在多個檔案間重複使用。 + +--- + +## 載入文件並捕捉缺失字型 + +在掛接好 callback 後,接下來只需要載入文件即可。 + +### 步驟 3:載入你的 DOCX(或任何支援的格式) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +當 `Document` 建構子解析檔案時,任何缺失的字型都會觸發我們的 `FontWarningCollector`。Console 會顯示類似以下的行: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +那一行即是 **偵測缺失字型** 成功的具體證據。 + +--- + +## 驗證輸出 – 期待的結果 + +在終端機或 Visual Studio 中執行程式。若來源文件使用了你未安裝的字型,將會看到至少一行 “Font substituted” 訊息。若文件僅使用已安裝的字型,callback 不會有任何輸出,僅會顯示 “Document loaded successfully.” 訊息。 + +**小技巧**:若要再次確認,可在 Microsoft Word 中開啟該檔案並檢視字型清單。任何出現在 *Home → Font* 群組下的 *Replace Fonts* 中的字型,都可能被替換。 + +--- + +## 進階:批次偵測缺失字型 + +通常你需要掃描數十個檔案。相同的模式可以輕鬆擴展: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +由於 `FontWarningCollector` 每次被呼叫時都會寫入 console,你會得到每個檔案的報告,且不需額外的程式碼。於正式環境中,你可能想將日誌寫入檔案或資料庫,只要將 `Console.WriteLine` 換成你偏好的 logger 即可。 + +--- + +## 常見陷阱與專業提示 + +| 問題 | 為何會發生 | 解決方式 | +|------|------------|----------| +| **沒有警告出現** | 文件實際上只包含已安裝的字型。 | 可透過在 Word 中開啟檔案或刻意從系統中移除字型來驗證。 | +| **Callback 未被呼叫** | `LoadOptions.WarningCallback` 從未被指派,或之後使用了新的 `LoadOptions` 實例。 | 保留單一 `LoadOptions` 物件,並在每次載入時重複使用。 | +| **過多不相關的警告** | 你未依 `WarningType.FontSubstitution` 進行過濾。 | 如範例所示,加入 `if (info.Type == WarningType.FontSubstitution)` 的判斷。 | +| **大型檔案的效能下降** | callback 會在每個警告時執行,對於大型文件可能會產生大量警告。 | 透過 `LoadOptions.WarningCallback` 停用其他警告類型,或在已知格式時設定 `LoadOptions.LoadFormat` 為特定類型。 | + +--- + +## 完整可執行範例(直接複製貼上) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**預期的 console 輸出**(當遇到缺失字型時): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +若未發生替換,則只會看到成功訊息。 + +--- + +## 結論 + +現在你已擁有一個 **完整、可投入生產的缺失字型偵測方式**,適用於任何由 Aspose.Words 處理的文件。透過利用 **Aspose.Words warning callback** 並設定 **LoadOptions C#**,你可以記錄每一次字型替換、排除版面問題,並確保 PDF 保持預期的外觀與感受。 + +無論是單一檔案還是大量批次,模式皆相同——實作 `IWarningCallback`、將其插入 `LoadOptions`,讓 Aspose.Words 完成繁重的工作。 + +準備好下一步了嗎?試著結合 **font embedding** 或 **fallback font families** 來自動解決問題,或探索 **DocumentVisitor** API 以進行更深入的內容分析。祝開發愉快,願所有字型都如你所預期般存在! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hongkong/words/net/images-and-shapes/_index.md b/content/hongkong/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..9e6446a5e --- /dev/null +++ b/content/hongkong/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "hongkong" +type: "category" +--- + +# Images And Shapes diff --git a/content/hongkong/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/hongkong/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..e9be0dc69 --- /dev/null +++ b/content/hongkong/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2025-12-08 +description: 使用 Aspose.Words 快速為圖形添加陰影。了解如何使用 Aspose 建立 Word 文件、如何為圖形添加陰影,以及如何在 C# + 中套用陰影透明度。 +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: zh-hant +og_description: 使用 Aspose.Words 為 Word 檔案中的形狀添加陰影。本分步指南展示如何建立文件、加入形狀以及套用陰影透明度。 +og_title: 為形狀添加陰影 – Aspose.Words C# 教程 +tags: +- Aspose.Words +- C# +- Word Automation +title: 在 Word 文件中為圖形添加陰影 – 完整 Aspose.Words 指南 +url: /hongkong/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# 為圖形新增陰影 – 完整 Aspose.Words 教學 + +是否曾想在 Word 檔案中 **為圖形新增陰影**,卻不確定要使用哪個 API 呼叫?你並不孤單。許多開發者在第一次嘗試為矩形或任何繪圖元素加上適當的投影時,常會卡關,尤其是使用 Aspose.Words for .NET 時。 + +在本教學中,我們將一步步說明你需要的全部知識:從 **使用 Aspose 建立 Word 文件** 到設定陰影、調整模糊度、距離、角度,甚至 **套用陰影透明度**。完成後,你將擁有一個可直接執行的 C# 程式,產生帶有柔和陰影矩形的 `.docx` 檔案——不需要在 Word 中手動調整。 + +--- + +## 你將學到什麼 + +- 如何在 Visual Studio 中建立 Aspose.Words 專案。 +- **使用 Aspose 建立 Word 文件** 並插入圖形的完整步驟。 +- **如何為圖形新增陰影**,並完整控制模糊度、距離、角度與透明度。 +- 常見問題的排除技巧(例如授權遺失、單位錯誤)。 +- 一段完整、可直接複製貼上的程式碼範例,讓你今天就能執行。 + +> **先備條件:** .NET 6+(或 .NET Framework 4.7.2+)、有效的 Aspose.Words 授權(或免費試用版),以及對 C# 的基本認識。 + +--- + +## 第一步 – 設定專案並加入 Aspose.Words + +首先,開啟 Visual Studio,建立一個新的 **Console App (.NET Core)**,然後加入 Aspose.Words NuGet 套件: + +```bash +dotnet add package Aspose.Words +``` + +> **小技巧:** 若你有授權檔 (`Aspose.Words.lic`),請將它複製到專案根目錄,並在程式啟動時載入。這樣可避免在免費評估模式下出現浮水印。 + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## 第二步 – 建立新的空白文件 + +現在我們實際 **使用 Aspose 建立 Word 文件**。此物件將作為圖形的畫布。 + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` 類別是所有其他功能的入口點——段落、節,當然還有繪圖物件。 + +--- + +## 第三步 – 插入矩形圖形 + +文件準備好後,我們即可加入圖形。這裡選擇一個簡單的矩形,其他形狀(圓形、線條或自訂多邊形)同樣適用相同的邏輯。 + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **為什麼要使用圖形?** 在 Aspose.Words 中,`Shape` 物件可以容納文字、圖片,或僅作為裝飾元素。為圖形加入陰影遠比操作圖片框來得簡單。 + +--- + +## 第四步 – 設定陰影(Add Shadow to Shape) + +這是本教學的核心——**如何為圖形新增陰影** 並微調外觀。`ShadowFormat` 屬性讓你完全掌控。 + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### 各屬性說明 + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | 開啟或關閉陰影。 | `true` / `false` | +| **Blur** | 使陰影邊緣變得柔和。 | `0`(硬)到 `10`(非常柔) | +| **Distance** | 將陰影從圖形向外移動的距離。 | 常見為 `1`–`5` 點 | +| **Angle** | 控制偏移的方向。 | `0`–`360` 度 | +| **Transparency** | 讓陰影呈現半透明。 | `0`(不透明)到 `1`(完全透明) | + +> **邊緣情況:** 若將 `Transparency` 設為 `1`,陰影會完全消失——可用於程式中動態切換。 + +--- + +## 第五步 – 將圖形加入文件 + +現在把圖形附加到文件正文的第一個段落。若文件中尚未有段落,Aspose 會自動建立。 + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +如果你的文件已經有內容,也可以使用 `InsertAfter` 或 `InsertBefore` 在任意節點插入圖形。 + +--- + +## 第六步 – 儲存文件 + +最後,將檔案寫入磁碟。你可以選擇任何支援的格式(`.docx`、`.pdf`、`.odt` 等),但本教學仍以原生 Word 格式為例。 + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +開啟產生的 `ShadowedShape.docx`,你會看到一個帶有柔和、45 度、透明度 30 % 的矩形——正是我們剛剛設定的效果。 + +--- + +## 完整可執行範例 + +以下是 **完整、可直接複製貼上** 的程式碼,已整合上述所有步驟。將它存為 `Program.cs`,然後以 `dotnet run` 執行。 + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**預期結果:** 產生名為 `ShadowedShape.docx` 的檔案,內含一個帶有細緻、半透明、45° 角度投影的矩形。 + +--- + +## 變化與進階技巧 + +### 更改陰影顏色 + +預設情況下,陰影會繼承圖形的填色,但你也可以自行指定顏色: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 多個圖形搭配不同陰影 + +若需要多個圖形,只要重複建立與設定的步驟即可。若日後要引用,記得為每個圖形設定唯一名稱。 + +### 匯出為 PDF 並保留陰影 + +Aspose.Words 在儲存為 PDF 時會保留陰影效果: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### 常見問題 + +| 症狀 | 可能原因 | 解決方式 | +|------|----------|----------| +| 陰影不顯示 | `ShadowFormat.Visible` 為 `false` | 設為 `true`。 | +| 陰影太硬 | `Blur` 設為 `0` | 將 `Blur` 提升至 3–6。 | +| PDF 中陰影消失 | 使用舊版 Aspose.Words (< 22.9) | 升級至最新版本。 | + +--- + +## 結論 + +我們已完整說明 **如何使用 Aspose.Words 為圖形新增陰影**,從文件初始化到微調模糊度、距離、角度,以及 **套用陰影透明度**。完整範例展示了乾淨、可投入生產環境的作法,且可依需求套用於任何圖形或文件版面。 + +對於更複雜的情境(例如帶陰影的表格或動態資料驅動的圖形)有任何疑問,歡迎在下方留言,或參考 Aspose.Words 圖片處理與段落格式化的相關教學。 + +祝開發順利,讓你的 Word 文件更添視覺魅力! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hungarian/words/_index.md b/content/hungarian/words/_index.md new file mode 100644 index 000000000..a89762123 --- /dev/null +++ b/content/hungarian/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "hungarian" +type: "family" +--- + +# Words Tutorials diff --git a/content/hungarian/words/net/_index.md b/content/hungarian/words/net/_index.md new file mode 100644 index 000000000..cfadc2160 --- /dev/null +++ b/content/hungarian/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "hungarian" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/hungarian/words/net/getting-started/_index.md b/content/hungarian/words/net/getting-started/_index.md new file mode 100644 index 000000000..e5f2fa9d0 --- /dev/null +++ b/content/hungarian/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "hungarian" +type: "category" +--- + +# Getting Started diff --git a/content/hungarian/words/net/getting-started/tutorial/_index.md b/content/hungarian/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..12295f196 --- /dev/null +++ b/content/hungarian/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: hu +url: /hungarian/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Hiányzó betűtípusok észlelése Aspose.Words dokumentumokban – Teljes C# útmutató + +Gondolkodtál már azon, hogyan **észlelheted a hiányzó betűtípusokat**, amikor egy Word fájlt töltesz be az Aspose.Words segítségével? A mindennapi munkám során néhány PDF-et találtam, amelyek rosszul néztek ki, mert az eredeti dokumentum egy olyan betűtípust használt, amely nincs telepítve a gépemen. A jó hír? Az Aspose.Words pontosan megmondja, mikor helyettesít egy betűtípust, és ezt az információt egy egyszerű figyelmeztető visszahívással (warning callback) el lehet kapni. + +Ebben az útmutatóban egy **teljes, futtatható példán** keresztül vezetünk, amely megmutatja, hogyan naplózhatsz minden betűtípus helyettesítést, miért fontos a visszahívás, és néhány extra trükköt a robusztus hiányzó betűtípusok észleléséhez. Felesleges részletek nélkül, csak a kód és a gondolatmenet, amire ma működésre van szükséged. + +--- + +## Mit fogsz megtanulni + +- Hogyan valósítsd meg az **Aspose.Words warning callback**-et a betűtípus helyettesítési események elkapásához. +- Hogyan konfiguráld a **LoadOptions C#**-t, hogy a visszahívás a dokumentum betöltésekor meghívódjon. +- Hogyan ellenőrizd, hogy a hiányzó betűtípusok észlelése valóban működött-e, és hogy néz ki a konzol kimenete. +- Opcionális finomhangolások nagy kötegelt feldolgozáshoz vagy fej nélküli környezetekhez. + +**Előfeltételek** – Szükséged van egy naprakész Aspose.Words for .NET verzióra (a kód 23.12-vel lett tesztelve), .NET 6 vagy újabb verzióra, valamint az C# alapjaira. Ha ezek megvannak, már indulhatsz. + +--- + +## Hiányzó betűtípusok észlelése figyelmeztető visszahívással + +A megoldás lényege a `IWarningCallback` megvalósítása. Az Aspose.Words számos helyzetben kibocsát egy `WarningInfo` objektumot, de csak a `WarningType.FontSubstitution` érdekel minket. Nézzük meg, hogyan kapcsolódhatunk ehhez. + +### 1. lépés: Hozz létre egy betűtípus‑figyelmeztető gyűjtőt + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Miért fontos*: A `WarningType.FontSubstitution` szűrésével elkerüljük a nem releváns figyelmeztetések (például elavult funkciók) által okozott zajt. Az `info.Description` már tartalmazza az eredeti betűtípus nevét és a használt helyettesítőt, így egyértelmű nyomkövetést biztosít. + +--- + +## LoadOptions konfigurálása a visszahívás használatához + +Most azt mondjuk az Aspose.Words-nak, hogy a fájl betöltésekor használja a gyűjtőnket. + +### 2. lépés: LoadOptions beállítása + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Miért fontos*: A `LoadOptions` az egyetlen hely, ahol a visszahívást, titkosítási jelszavakat és egyéb betöltési viselkedéseket csatlakoztathatod. A `Document` konstruktorától elkülönítve a kód újrahasználható több fájl esetén is. + +--- + +## Dokumentum betöltése és a hiányzó betűtípusok rögzítése + +Miután a visszahívás be lett kötve, a következő lépés egyszerűen a dokumentum betöltése. + +### 3. lépés: Töltsd be a DOCX-et (vagy bármely támogatott formátumot) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Amikor a `Document` konstruktor feldolgozza a fájlt, minden hiányzó betűtípus aktiválja a `FontWarningCollector`-t. A konzol ilyen sorokat fog megjeleníteni: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Ez a sor a konkrét bizonyíték arra, hogy a **hiányzó betűtípusok észlelése** működött. + +--- + +## A kimenet ellenőrzése – Mit várhatsz + +Futtasd a programot egy terminálból vagy a Visual Studio-ból. Ha a forrásdokumentum olyan betűtípust tartalmaz, amely nincs telepítve, legalább egy „Font substituted” sort fogsz látni. Ha a dokumentum csak telepített betűtípusokat használ, a visszahívás csendes marad, és csak a „Document loaded successfully.” üzenetet kapod. + +**Tipp**: A dupla ellenőrzéshez nyisd meg a Word fájlt a Microsoft Wordben, és nézd meg a betűtípuslistát. Bármely betűtípus, amely a *Home → Font* csoport *Replace Fonts* részében megjelenik, helyettesítésre kerülhet. + +--- + +## Haladó: Hiányzó betűtípusok észlelése tömegesen + +Gyakran szükség van tucatnyi fájl átvizsgálására. Ugyanaz a minta szépen skálázható: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Mivel a `FontWarningCollector` minden meghíváskor a konzolra ír, fájlonként kapsz jelentést extra kód nélkül. Gyártási környezetben érdemes lehet fájlba vagy adatbázisba naplózni – egyszerűen cseréld le a `Console.WriteLine`-t a kedvenc naplózó eszközödre. + +--- + +## Gyakori hibák és profi tippek + +| Probléma | Miért fordul elő | Megoldás | +|----------|------------------|----------| +| **Nem jelennek meg figyelmeztetések** | A dokumentum valójában csak telepített betűtípusokat tartalmaz. | Ellenőrizd a fájl Wordben való megnyitásával vagy szándékosan egy betűtípus eltávolításával a rendszeredből. | +| **A visszahívás nem hívódik meg** | A `LoadOptions.WarningCallback` soha nem lett hozzárendelve, vagy később egy új `LoadOptions` példányt használtál. | Tarts egyetlen `LoadOptions` objektumot, és használd újra minden betöltésnél. | +| **Túl sok nem releváns figyelmeztetés** | Nem szűrtél a `WarningType.FontSubstitution` alapján. | Add hozzá a `if (info.Type == WarningType.FontSubstitution)` feltételt, ahogy a példában látható. | +| **Teljesítménycsökkenés nagy fájloknál** | A visszahívás minden figyelmeztetésnél lefut, ami nagy dokumentumoknál sok lehet. | Kapcsold ki a többi figyelmeztetést a `LoadOptions.WarningCallback`-on keresztül, vagy állítsd be a `LoadOptions.LoadFormat`-ot egy konkrét típusra, ha tudod. | + +--- + +## Teljes működő példa (másolás‑beillesztés kész) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Várható konzol kimenet** (ha hiányzó betűtípusra bukkansz): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Ha nincs helyettesítés, csak a sikeres sor jelenik meg. + +--- + +## Összegzés + +Most már van egy **teljes, termelés‑kész módszered a hiányzó betűtípusok észlelésére** bármely, az Aspose.Words által feldolgozott dokumentumban. Az **Aspose.Words warning callback** és a **LoadOptions C#** konfigurálásával naplózhatod minden betűtípus helyettesítést, hibaelháríthatod a megjelenési problémákat, és biztosíthatod, hogy a PDF-ek megőrizzék a kívánt megjelenést. + +Egyetlen fájltól egy hatalmas kötegig a minta ugyanaz marad – valósítsd meg a `IWarningCallback`-et, csatlakoztasd a `LoadOptions`-hoz, és hagyd, hogy az Aspose.Words végezze a nehéz munkát. + +Készen állsz a következő lépésre? Próbáld meg kombinálni ezt **betűtípus beágyazással** vagy **helyettesítő betűtípus családokkal**, hogy automatikusan megoldja a problémát, vagy fedezd fel a **DocumentVisitor** API-t a mélyebb tartalomelemzéshez. Boldog kódolást, és legyenek a betűtípusaid mindig a várt helyen! + +--- + +![Hiányzó betűtípusok észlelése Aspose.Words‑ben – konzol kimenet képernyőkép](https://example.com/images/detect-missing-fonts.png "hiányzó betűtípusok konzol kimenete") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/hungarian/words/net/images-and-shapes/_index.md b/content/hungarian/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..177729946 --- /dev/null +++ b/content/hungarian/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "hungarian" +type: "category" +--- + +# Images And Shapes diff --git a/content/hungarian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/hungarian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..3ae77ddd3 --- /dev/null +++ b/content/hungarian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2025-12-08 +description: Adj gyorsan árnyékot a formához az Aspose.Words segítségével. Tanulja + meg, hogyan hozhat létre Word-dokumentumot az Aspose használatával, hogyan adhat + árnyékot a formához, és hogyan alkalmazhat árnyék átlátszóságot C#‑ban. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: hu +og_description: Árnyék hozzáadása alakzathoz egy Word-fájlban az Aspose.Words használatával. + Ez a lépésről‑lépésre útmutató bemutatja, hogyan hozhatunk létre dokumentumot, adhatunk + hozzá alakzatot, és állíthatjuk be az árnyék átlátszóságát. +og_title: Árnyék hozzáadása alakzathoz – Aspose.Words C# útmutató +tags: +- Aspose.Words +- C# +- Word Automation +title: Árnyék hozzáadása alakzathoz egy Word-dokumentumban – Teljes Aspose.Words útmutató +url: /hungarian/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Árnyék hozzáadása alakzathoz – Teljes Aspose.Words útmutató + +Valaha szükséged volt **árnyék hozzáadására alakzathoz** egy Word fájlban, de nem tudtad, mely API hívásokat kell használni? Nem vagy egyedül. Sok fejlesztő akad el, amikor először próbál meg egy téglalapnak vagy bármely rajz elemnek megfelelő vetett árnyékot adni, különösen, ha az Aspose.Words for .NET-et használja. + +Ebben az útmutatóban mindent végigvázolunk, amit tudnod kell: a **Word dokumentum létrehozását Aspose-szal**ól az árnyék beállításáig, a homály, a távolság, a szög finomhangolásáig, sőt a **árnyék átlátszóságának alkalmazásáig**. A végére egy azonnal futtatható C# programod lesz, amely egy `.docx` fájlt hoz létre egy szép árnyékolt téglalappal – manuális beavatkozás a Wordben nélkül. + +--- + +## Mit fogsz megtanulni + +- Hogyan állíts be egy Aspose.Words projektet a Visual Studio-ban. +- A pontos lépések a **Word dokumentum létrehozásához Aspose-szal** és egy alakzat beszúrásához. +- **Hogyan adj hozzá alakzati árnyékot** teljes irányítással a homály, a távolság, a szög és az átlátszóság felett. +- Tippek a gyakori hibák elhárításához (pl. hiányzó licenc, helytelen egységek). +- Egy teljes, másolás‑beillesztésre kész kódminta, amelyet ma futtathatsz. + +> **Előfeltételek:** .NET 6+ (vagy .NET Framework 4.7.2+), egy érvényes Aspose.Words licenc (vagy a ingyenes próba), valamint az alapvető C# ismeretek. + +## 1. lépés – A projekt beállítása és az Aspose.Words hozzáadása + +Először is. Nyisd meg a Visual Studio-t, hozz létre egy új **Console App (.NET Core)** projektet, és add hozzá az Aspose.Words NuGet csomagot: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tipp:** Ha rendelkezel egy licencfájllal (`Aspose.Words.lic`), másold a projekt gyökerébe, és töltsd be indításkor. Ez elkerüli a vízjelet, amely az ingyenes értékelő módban megjelenik. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## 2. lépés – Új üres dokumentum létrehozása + +Most ténylegesen **Word dokumentumot hozunk létre Aspose-szal**. Ez az objektum szolgál a vászonként az alakzatunk számára. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +A `Document` osztály a kiindulópont minden más számára – bekezdések, szakaszok, és természetesen a rajzobjektusok. + +## 3. lépés – Téglalap alakzat beszúrása + +A dokumentum készen áll, hozzáadhatunk egy alakzatot. Itt egy egyszerű téglalapot választunk, de ugyanaz a logika működik körök, vonalak vagy egyedi sokszögek esetén is. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Miért alakzat?** Az Aspose.Words-ben egy `Shape` objektum tartalmazhat szöveget, képeket, vagy egyszerűen dekoratív elemként működhet. Árnyék hozzáadása egy alakzathoz sokkal egyszerűbb, mint egy képkeret manipulálása. + +## 4. lépés – Árnyék beállítása (Árnyék hozzáadása alakzathoz) + +Ez a tutorial szíve – **hogyan adjunk hozzá alakzati árnyékot** és finomhangoljuk a megjelenését. A `ShadowFormat` tulajdonság teljes irányítást biztosít. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Mit jelent minden tulajdonság + +| Tulajdonság | Hatás | Tipikus értékek | +|-------------|------|-----------------| +| **Visible** | Bekapcsolja vagy kikapcsolja az árnyékot. | `true` / `false` | +| **Blur** | Lágyítja az árnyék szélét. | `0 (hard) to `10` (very soft) | +| **Distance** | Elmozdítja az árnyékot az alakzattól. | `1`–`5` points is common | +| **Angle** | Szabályozza az eltolás irányát. | `0`–`360` degrees | +| **Transparency** | Átlátszóvá teszi az árnyékot részben. | `0` (opaque) to `1` (invisible) | + +> **Szélsőséges eset:** Ha a `Transparency` értékét `1`‑re állítod, az árnyék teljesen eltűnik – hasznos programozott kapcsoláshoz. + +## 5. lépés – Alakzat hozzáadása a dokumentumhoz + +Most a dokumentum törzsének első bekezdéséhez csatoljuk az alakzatot. Az Aspose automatikusan létrehoz egy bekezdést, ha nincs. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Ha a dokumentum már tartalmaz tartalmat, a `InsertAfter` vagy `InsertBefore` metódusokkal bármelyik csomópontba beillesztheted az alakzatot. + +## 6. lépés – Dokumentum mentése + +Végül írd a fájlt a lemezre. Bármely támogatott formátumot választhatod (`.docx`, `.pdf`, `.odt`, stb.), de ebben a tutorialban a natív Word formátumot használjuk. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Nyisd meg a keletkezett `ShadowedShape.docx` fájlt a Microsoft Wordben, és egy téglalapot látsz egy lágy, 45‑ fokos árnyékkal, amely 30 % átlátszó – pontosan úgy, ahogy beállítottuk. + +## Teljes működő példa + +Az alábbi **teljes, másolás‑beillesztésre kész** program tartalmazza a fenti összes lépést. Mentsd el `Program.cs` néven, és futtasd a `dotnet run` paranccsal. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Várható kimenet:** Egy `ShadowedShape.docx` nevű fájl, amely egyetlen téglalapot tartalmaz egy finom, félig átlátszó vetett árnyékkal, 45°-os szöggel. + +## Variációk és haladó tippek + +### Árnyék színének módosítása + +Alapértelmezés szerint az árnyék örökli az alakzat kitöltőszínét, de beállíthatsz egy egyedi színt: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Több alakzat különböző árnyékokkal + +Ha több alakzatra van szükséged, egyszerűen ismételd meg a létrehozási és konfigurációs lépéseket. Ne felejts egyedi nevet adni minden alakzatnak, ha később hivatkozni szeretnél rájuk. + +### Exportálás PDF-be az árnyékok megőrzésével + +Az Aspose.Words megőrzi az árnyékhatásokat PDF-be mentéskor: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Gyakori hibák + +| Tünet | Valószínű ok |oldás | +|-------|---------------|----------| +| Az árnyék nem látható | `ShadowFormat.Visible` értéke `false` maradt | Állítsd `true`‑ra. | +| Az árnyék túl kemény | `Blur` értéke `0` | Növeld a `Blur` értékét 3–6‑ra. | +| Az árnyék eltűnik PDF-ben | Régi Aspose.Words verzió (< 22.9) használata | Frissíts a legújabb könyvtárra. | + +## Következtetés + +Áttekintettük, **hogyan adjunk hozzá árnyékot alakzathoz** az Aspose.Words segítségével, a dokumentum inicializálásától a homály, távolság, szög finomhangolásáig és a **árnyék átlátszóságának alkalmazásáig**. A teljes példa egy tiszta, termelésre kész megközelítést mutat, amelyet bármely alakzatra vagy dokumentum elrendezésre adaptálhatsz. + +Van kérdésed a **Word dokumentum létrehozásával Aspose-szal** összetettebb szcenáriókkal kapcsolatban – például árnyékos táblázatok vagy dinamikus adat‑vezérelt alakzatok? Hagyj megjegyzést alább, vagy nézd meg a kapcsolódó útmutatókat az Aspose.Words képek kezelése és bekezdés formázás témakörében. + +Boldog kódolást, és élvezd, hogy Word dokumentumaidnak extra vizuális csillogást adsz! + +--- + +![árnyék hozzáadása alakzathoz példa](shadowed_shape.png "árnyék hozzáadása alakzathoz példa") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/indonesian/words/_index.md b/content/indonesian/words/_index.md new file mode 100644 index 000000000..299721e01 --- /dev/null +++ b/content/indonesian/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "indonesian" +type: "family" +--- + +# Words Tutorials diff --git a/content/indonesian/words/net/_index.md b/content/indonesian/words/net/_index.md new file mode 100644 index 000000000..76ea63b85 --- /dev/null +++ b/content/indonesian/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "indonesian" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/indonesian/words/net/getting-started/_index.md b/content/indonesian/words/net/getting-started/_index.md new file mode 100644 index 000000000..3779ef4fb --- /dev/null +++ b/content/indonesian/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "indonesian" +type: "category" +--- + +# Getting Started diff --git a/content/indonesian/words/net/getting-started/tutorial/_index.md b/content/indonesian/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..5cbb9913d --- /dev/null +++ b/content/indonesian/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: id +url: /indonesian/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Mendeteksi Font yang Hilang dalam Dokumen Aspose.Words – Panduan Lengkap C# + +Pernah bertanya-tanya bagaimana cara **mendeteksi font yang hilang** saat Anda memuat file Word dengan Aspose.Words? Dalam pekerjaan sehari-hari saya, saya pernah menemukan beberapa PDF yang tampak aneh karena dokumen asli menggunakan font yang tidak terpasang di sistem saya. Kabar baiknya? Aspose.Words dapat memberi tahu Anda secara tepat kapan ia menggantikan sebuah font, dan Anda dapat menangkap informasi tersebut dengan callback peringatan sederhana. + +Dalam tutorial ini kami akan membahas **contoh lengkap yang dapat dijalankan** yang menunjukkan cara mencatat setiap substitusi font, mengapa callback penting, dan beberapa trik tambahan untuk deteksi font yang hilang yang kuat. Tanpa basa-basi, hanya kode dan penjelasan yang Anda perlukan untuk membuatnya berfungsi hari ini. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara mengimplementasikan **Aspose.Words warning callback** untuk menangkap peristiwa substitusi font. +- Cara mengkonfigurasi **LoadOptions C#** sehingga callback dipanggil saat memuat dokumen. +- Cara memverifikasi bahwa deteksi font yang hilang benar‑benar berhasil, dan seperti apa output konsolnya. +- Penyesuaian opsional untuk batch besar atau lingkungan tanpa UI. + +**Prasyarat** – Anda memerlukan versi terbaru Aspose.Words untuk .NET (kode ini diuji dengan 23.12), .NET 6 atau lebih baru, dan pemahaman dasar tentang C#. Jika Anda sudah memiliki itu, Anda siap memulai. + +--- + +## Mendeteksi Font yang Hilang dengan Callback Peringatan + +Inti dari solusi ini adalah implementasi `IWarningCallback`. Aspose.Words memicu objek `WarningInfo` untuk banyak situasi, tetapi kita hanya peduli pada `WarningType.FontSubstitution`. Mari kita lihat cara mengaitkannya. + +### Langkah 1: Buat Font‑Warning Collector + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Mengapa ini penting*: Dengan memfilter pada `WarningType.FontSubstitution` kita menghindari kebisingan dari peringatan yang tidak terkait (seperti fitur yang sudah usang). `info.Description` sudah berisi nama font asli dan fallback yang digunakan, memberikan jejak audit yang jelas. + +--- + +## Konfigurasikan LoadOptions untuk Menggunakan Callback + +Sekarang kita memberi tahu Aspose.Words untuk menggunakan collector kami saat memuat file. + +### Langkah 2: Siapkan LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Mengapa ini penting*: `LoadOptions` adalah satu‑satunya tempat di mana Anda dapat menyambungkan callback, kata sandi en, dan perilaku pemuatan lainnya. Memisahkannya dari konstruktor `Document` membuat kode dapat digunakan kembali pada banyak file. + +--- + +## Muat Dokumen dan Tangkap Font yang Hilang + +Dengan callback terpasang, langkah selanjutnya cukup memuat dokumen. + +### Langkah 3: Muat DOCX Anda (atau format lain yang didukung) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Saat konstruktor `Document` mem-parsing file, setiap font yang hilang memicu `FontWarningCollector` kami. Konsol akan menampilkan baris seperti: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Baris itu adalah bukti konkret bahwa **mendeteksi font yang hilang** berhasil. + +--- + +## Verifikasi Output – Apa yang Diharapkan + +Jalankan program dari terminal atau Visual Studio. Jika dokumen sumber berisi font yang tidak terpasang di sistem Anda, Anda akan melihat setidaknya satu baris “Font substituted”. Jika dokumen hanya menggunakan font yang terpasang, callback tetap diam dan Anda hanya akan melihat pesan “Document loaded successfully.” + +**Tip**: Untuk memeriksa kembali, buka file Word di Microsoft Word dan lihat daftar font. Font apa pun yang muncul di *Replace Fonts* di bawah grup *Home → Font* adalah kandidat untuk substitusi. + +--- + +## Lanjutan: Mendeteksi Font yang Hilang secara Massal + +Seringkali Anda perlu memindai puluhan file. Pola yang sama dapat diskalakan dengan baik: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Karena `FontWarningCollector` menulis ke konsol setiap kali dipanggil, Anda akan mendapatkan laporan per‑file tanpa tambahan kode. Untuk skenario produksi Anda mungkin ingin mencatat ke file atau basis data – cukup ganti `Console.WriteLine` dengan logger pilihan Anda. + +--- + +## Kesalahan Umum & Tips Pro + +| Masalah | Mengapa Terjadi | Solusi | +|-------|----------------|-----| +| **Tidak ada peringatan muncul** | Dokumen sebenarnya hanya berisi font yang terpasang. | Verifikasi dengan membuka file di Word atau dengan sengaja menghapus sebuah font dari sistem Anda. | +| **Callback tidak dipanggil** | `LoadOptions.WarningCallback` tidak pernah ditetapkan atau instance `LoadOptions` baru digunakan kemudian. | Gunakan satu objek `LoadOptions` dan gunakan kembali untuk setiap pemuatan. | +| **Terlalu banyak peringatan yang tidak terkait** | Anda tidak memfilter berdasarkan `WarningType.FontSubstitution`. | Tambahkan guard `if (info.Type == WarningType.FontSubstitution)` seperti yang ditunjukkan. | +| **Penurunan kinerja pada file besar** | Callback dijalankan pada setiap peringatan, yang dapat banyak untuk dokumen besar. | Nonaktifkan tipe peringatan lain melalui `LoadOptions.WarningCallback` atau set `LoadOptions.LoadFormat` ke tipe spesifik jika Anda mengetahuinya. | + +--- + +## Contoh Lengkap yang Berfungsi (Siap Salin‑Tempel) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Output konsol yang diharapkan** (ketika font yang hilang ditemukan): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Jika tidak ada substitusi, Anda hanya akan melihat baris keberhasilan. + +--- + +## Kesimpulan + +Anda kini memiliki **cara lengkap dan siap produksi untuk mendeteksi font yang hilang** dalam dokumen apa pun yang diproses oleh Aspose.Words. Dengan memanfaatkan **Aspose.Words warning callback** dan mengkonfigurasi **LoadOptions C#**, Anda dapat mencatat setiap substitusi font, memecahkan masalah tata letak, dan memastikan PDF Anda mempertahankan tampilan‑dan‑rasa yang dimaksudkan. + +Dari satu file hingga batch besar, pola tetap sama—implementasikan `IWarningCallback`, sambungkan ke `LoadOptions`, dan biarkan Aspose.Words melakukan pekerjaan berat. + +Siap untuk langkah selanjutnya? Cobalah menggabungkan ini dengan **font embedding** atau **fallback font families** untuk secara otomatis memperbaiki masalah, atau jelajahi API **DocumentVisitor** untuk analisis konten yang lebih mendalam. Selamat coding, dan semoga semua font Anda tetap berada di tempat yang Anda harapkan! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/indonesian/words/net/images-and-shapes/_index.md b/content/indonesian/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..4ea389e7a --- /dev/null +++ b/content/indonesian/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "indonesian" +type: "category" +--- + +# Images And Shapes diff --git a/content/indonesian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/indonesian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..d8b80b2b5 --- /dev/null +++ b/content/indonesian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Tambahkan bayangan ke bentuk dengan cepat menggunakan Aspose.Words. Pelajari + cara membuat dokumen Word menggunakan Aspose, cara menambahkan bayangan pada bentuk, + dan menerapkan transparansi bayangan di C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: id +og_description: Tambahkan bayangan pada bentuk dalam file Word menggunakan Aspose.Words. + Panduan langkah demi langkah ini menunjukkan cara membuat dokumen, menambahkan bentuk, + dan menerapkan transparansi bayangan. +og_title: Tambahkan Bayangan ke Bentuk – Tutorial Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Tambahkan Bayangan pada Bentuk di Dokumen Word – Panduan Lengkap Aspose.Words +url: /indonesian/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Tambahkan Bayangan ke Bentuk – Panduan Lengkap Aspose.Words + +Pernah perlu **menambahkan bayangan ke bentuk** dalam file Word tetapi tidak yakin panggilan API mana yang harus digunakan? Anda tidak sendirian. Banyak pengembang menemui kebuntuan saat pertama kali mencoba memberi persegi panjang atau elemen gambar apa pun bayangan jatuh yang tepat, terutama ketika mereka bekerja dengan Aspose.Words untuk .NET. + +Dalam tutorial ini kami akan membahas semua yang perlu Anda ketahui: mulai dari **membuat dokumen Word menggunakan Aspose** hingga mengonfigurasi bayangan, menyesuaikan blur, jarak, sudut, dan bahkan **menerapkan transparansi bayangan**. Pada akhir tutorial Anda akan memiliki program C# siap‑jalankan yang menghasilkan file `.docx` dengan persegi panjang berbayangan indah—tanpa harus mengutak‑atik secara manual di Word. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara menyiapkan proyek Aspose.Words di Visual Studio. +- Langkah‑langkah tepat untuk **membuat dokumen Word menggunakan Aspose** dan menyisipkan sebuah bentuk. +- **Cara menambahkan bayangan pada bentuk** dengan kontrol penuh atas blur, jarak, sudut, dan transparansi. +- Tips untuk memecahkan masalah umum (misalnya, lisensi hilang, satuan tidak tepat). +- Contoh kode lengkap yang dapat Anda salin‑tempel dan jalankan hari ini. + +> **Prasyarat:** .NET 6+ (atau .NET Framework 4.7.2+), lisensi Aspose.Words yang valid (atau trial gratis), dan pemahaman dasar tentang C#. + +--- + +## Langkah 1 – Siapkan Proyek Anda dan Tambahkan Aspose.Words + +Hal pertama yang harus dilakukan. Buka Visual Studio, buat **Console App (.NET Core)** baru, dan tambahkan paket NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** Jika Anda memiliki file lisensi (`Aspose.Words.lic`), salin ke root proyek dan muat saat aplikasi dimulai. Ini menghindari watermark yang muncul pada mode evaluasi gratis. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Langkah 2 – Buat Dokumen Kosong Baru + +Sekarang kita benar‑benar **membuat dokumen Word menggunakan Aspose**. Objek ini akan menjadi kanvas bagi bentuk kita. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Kelas `Document` adalah titik masuk untuk semua hal lainnya—paragraf, seksi, dan tentu saja, objek gambar. + +--- + +## Langkah 3 – Sisipkan Bentuk Persegi Panjang + +Dengan dokumen siap, kita dapat menambahkan sebuah bentuk. Di sini kami memilih persegi panjang sederhana, tetapi logika yang sama berlaku untuk lingkaran, garis, atau poligon khusus. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Mengapa bentuk?** Di Aspose.Words objek `Shape` dapat menampung teks, gambar, atau hanya berfungsi sebagai elemen dekoratif. Menambahkan bayangan ke bentuk jauh lebih mudah daripada mencoba memanipulasi bingkai gambar. + +--- + +## Langkah 4 – Konfigurasikan Bayangan (Tambahkan Bayangan ke Bentuk) + +Inilah inti tutorial—**cara menambahkan bayangan pada bentuk** dan menyesuaikan tampilannya. Properti `ShadowFormat` memberi Anda kontrol penuh. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Apa Fungsi Setiap Properti + +| Properti | Efek | Nilai Umum | +|----------|------|------------| +| **Visible** | Mengaktifkan/mematikan bayangan. | `true` / `false` | +| **Blur** | Melunakkan tepi bayangan. | `0` (keras) hingga `10` (sangat lunak) | +| **Distance** | Memindahkan bayangan menjauh dari bentuk. | `1`–`5` poin biasanya | +| **Angle** | Mengontrol arah offset. | `0`–`360` derajat | +| **Transparency** | Membuat bayangan sebagian tembus. | `0` (opak) hingga `1` (tidak terlihat) | + +> **Kasus khusus:** Jika Anda mengatur `Transparency` ke `1`, bayangan akan menghilang sepenuhnya—berguna untuk menyalakannya secara programatik. + +--- + +## Langkah 5 – Tambahkan Bentuk ke Dokumen + +Sekarang kita lampirkan bentuk ke paragraf pertama dalam tubuh dokumen. Aspose secara otomatis membuat paragraf jika belum ada. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Jika dokumen Anda sudah berisi konten, Anda dapat menyisipkan bentuk di node mana pun menggunakan `InsertAfter` atau `InsertBefore`. + +--- + +## Langkah 6 – Simpan Dokumen + +Akhirnya, tulis file ke disk. Anda dapat memilih format apa pun yang didukung (`.docx`, `.pdf`, `.odt`, dll.), tetapi untuk tutorial ini kami tetap menggunakan format Word asli. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Buka `ShadowedShape.docx` yang dihasilkan di Microsoft Word, dan Anda akan melihat persegi panjang dengan bayangan lembut berarah 45‑derajat yang 30 % transparan—tepat seperti yang kami konfigurasikan. + +--- + +## Contoh Lengkap yang Berfungsi + +Berikut adalah program **lengkap, siap salin‑tempel** yang menggabungkan semua langkah di atas. Simpan sebagai `Program.cs` dan jalankan dengan `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Output yang diharapkan:** Sebuah file bernama `ShadowedShape.docx` yang berisi satu persegi panjang dengan bayangan jatuh halus, semi‑transparan, berarah 45°. + +--- + +## Variasi & Tips Lanjutan + +### Mengubah Warna Bayangan + +Secara default bayangan mewarisi warna isi bentuk, tetapi Anda dapat mengatur warna khusus: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Beberapa Bentuk dengan Bayangan Berbeda + +Jika Anda memerlukan beberapa bentuk, cukup ulangi langkah pembuatan dan konfigurasi. Ingat untuk memberi setiap bentuk nama unik bila Anda berencana merujuknya nanti. + +### Mengekspor ke PDF dengan Bayangan Terjaga + +Aspose.Words mempertahankan efek bayangan saat menyimpan ke PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Kesalahan Umum + +| Gejala | Penyebab Kemungkinan | Solusi | +|--------|----------------------|--------| +| Bayangan tidak terlihat | `ShadowFormat.Visible` tetap `false` | Setel ke `true`. | +| Bayangan terlalu keras | `Blur` diatur ke `0` | Tingkatkan `Blur` menjadi 3–6. | +| Bayangan menghilang di PDF | Menggunakan versi Aspose.Words lama (< 22.9) | Tingkatkan ke pustaka terbaru. | + +--- + +## Kesimpulan + +Kami telah membahas **cara menambahkan bayangan ke bentuk** menggunakan Aspose.Words, mulai dari inisialisasi dokumen hingga menyesuaikan blur, jarak, sudut, dan **menerapkan transparansi bayangan**. Contoh lengkap menunjukkan pendekatan bersih dan siap produksi yang dapat Anda adaptasi untuk bentuk atau tata letak dokumen apa pun. + +Punya pertanyaan tentang **membuat dokumen word menggunakan aspose** untuk skenario yang lebih kompleks—seperti tabel dengan bayangan atau bentuk yang digerakkan secara dinamis? Tinggalkan komentar di bawah atau lihat tutorial terkait tentang penanganan gambar Aspose.Words dan pemformatan paragraf. + +Selamat coding, dan nikmati memberi dokumen Word Anda sentuhan visual ekstra! + +--- + +![contoh menambahkan bayangan ke bentuk](shadowed_shape.png "contoh menambahkan bayangan ke bentuk") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/italian/words/_index.md b/content/italian/words/_index.md new file mode 100644 index 000000000..c05f21ad1 --- /dev/null +++ b/content/italian/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "italian" +type: "family" +--- + +# Words Tutorials diff --git a/content/italian/words/net/_index.md b/content/italian/words/net/_index.md new file mode 100644 index 000000000..ece85e87b --- /dev/null +++ b/content/italian/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "italian" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/italian/words/net/getting-started/_index.md b/content/italian/words/net/getting-started/_index.md new file mode 100644 index 000000000..f17d3eb20 --- /dev/null +++ b/content/italian/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "italian" +type: "category" +--- + +# Getting Started diff --git a/content/italian/words/net/getting-started/tutorial/_index.md b/content/italian/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..b8a5dd987 --- /dev/null +++ b/content/italian/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: it +url: /italian/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Rilevare i Font Mancanti nei Documenti Aspose.Words – Guida Completa C# + +Ti sei mai chiesto come **rilevare i font mancanti** quando carichi un file Word con Aspose.Words? Nel mio lavoro quotidiano, mi sono imbattuto in alcuni PDF che sembravano sbagliati perché il documento originale usava un font che non avevo installato. La buona notizia? Aspose.Words può dirti esattamente quando sostituisce un font, e puoi catturare queste informazioni con un semplice callback di avviso. + +In questo tutorial vedremo un **esempio completo e eseguibile** che mostra come registrare ogni sostituzione di font, perché il callback è importante, e un paio di trucchi extra per una rilevazione robusta dei font mancanti. Niente superfluo, solo il codice e il ragionamento di cui hai bisogno per farlo funzionare subito. + +--- + +## Cosa Imparerai + +- Come implementare **Aspose.Words warning callback** per catturare gli eventi di sostituzione dei font. +- Come configurare **LoadOptions C#** affinché il callback venga invocato durante il caricamento di un documento. +- Come verificare che la rilevazione dei font mancanti abbia effettivamente funzionato e come appare l'output della console. +- Ottimizzazioni opzionali per grandi batch o ambienti headless. + +**Prerequisiti** – Hai bisogno di una versione recente di Aspose.Words per .NET (il codice è stato testato con la 23.12), .NET 6 o successivo, e una conoscenza di base di C#. Se li hai, sei pronto a partire. + +--- + +## Rilevare i Font Mancanti con un Callback di Avviso + +Il cuore della soluzione è un'implementazione di `IWarningCallback`. Aspose.Words genera un oggetto `WarningInfo` per molte situazioni, ma noi ci interessiamo solo a `WarningType.FontSubstitution`. Vediamo come collegarci a questo. + +### Passo 1: Creare un Collettore di Avvisi Font + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Perché è importante*: Filtrando su `WarningType.FontSubstitution` evitiamo il rumore di avvisi non correlati (come le funzionalità deprecate). `info.Description` contiene già il nome del font originale e quello di fallback usato, fornendoti una chiara traccia di audit. + +--- + +## Configurare LoadOptions per Usare il Callback + +Ora diciamo ad Aspose.Words di usare il nostro raccoglitore quando carica un file. + +### Passo 2: Configurare LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Perché è importante*: `LoadOptions` è l'unico punto in cui puoi collegare il callback, le password di crittografia e altri comportamenti di caricamento. Tenerlo separato dal costruttore `Document` rende il codice riutilizzabile per molti file. + +--- + +## Caricare il Documento e Catturare i Font Mancanti + +Con il callback collegato, il passo successivo è semplicemente caricare il documento. + +### Passo 3: Carica il tuo DOCX (o qualsiasi formato supportato) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Quando il costruttore `Document` analizza il file, qualsiasi font mancante attiva il nostro `FontWarningCollector`. La console mostrerà righe come: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Quella riga è la prova concreta che **rilevare i font mancanti** ha funzionato. + +--- + +## Verificare l'Output – Cosa Aspettarsi + +Esegui il programma da un terminale o da Visual Studio. Se il documento di origine contiene un font che non hai installato, vedrai almeno una riga “Font substituted”. Se il documento usa solo font installati, il callback rimane silenzioso e vedrai solo il messaggio “Document loaded successfully.”. + +**Suggerimento**: Per ricontrollare, apri il file Word in Microsoft Word e guarda l'elenco dei font. Qualsiasi font che appare in *Replace Fonts* sotto il gruppo *Home → Font* è un candidato per la sostituzione. + +--- + +## Avanzato: Rilevare i Font Mancanti in Massa + +Spesso è necessario analizzare decine di file. Lo stesso schema scala bene: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Poiché il `FontWarningCollector` scrive sulla console ogni volta che viene invocato, otterrai un report per file senza ulteriori complicazioni. Per scenari di produzione potresti voler registrare su un file o su un database – basta sostituire `Console.WriteLine` con il logger preferito. + +--- + +## Problemi Comuni & Consigli Pro + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| **Nessun avviso appare** | Il documento contiene effettivamente solo font installati. | Verifica aprendo il file in Word o rimuovendo deliberatamente un font dal tuo sistema. | +| **Callback non chiamato** | `LoadOptions.WarningCallback` non è mai stato assegnato o è stata usata in seguito una nuova istanza di `LoadOptions`. | Mantieni un unico oggetto `LoadOptions` e riutilizzalo per ogni caricamento. | +| **Troppi avvisi non correlati** | Non hai filtrato per `WarningType.FontSubstitution`. | Aggiungi la guardia `if (info.Type == WarningType.FontSubstitution)` come mostrato. | +| **Rallentamento delle prestazioni su file enormi** | Il callback viene eseguito per ogni avviso, che può essere molti per documenti grandi. | Disabilita altri tipi di avviso tramite `LoadOptions.WarningCallback` o imposta `LoadOptions.LoadFormat` a un tipo specifico se lo conosci. | + +--- + +## Esempio Completo Funzionante (Pronto per Copia‑Incolla) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Output console previsto** (quando si incontra un font mancante): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Se non avviene alcuna sostituzione, vedrai solo la riga di successo. + +--- + +## Conclusione + +Ora hai un **metodo completo e pronto per la produzione per rilevare i font mancanti** in qualsiasi documento elaborato da Aspose.Words. Sfruttando il **callback di avviso Aspose.Words** e configurando **LoadOptions C#**, puoi registrare ogni sostituzione di font, risolvere problemi di layout e assicurarti che i tuoi PDF mantengano l'aspetto previsto. + +Da un singolo file a un batch massivo, lo schema rimane lo stesso—implementa `IWarningCallback`, collegalo a `LoadOptions`, e lascia che Aspose.Words faccia il lavoro pesante. + +Pronto per il passo successivo? Prova a combinare questo con **l'incorporamento dei font** o **famiglie di font di fallback** per correggere automaticamente il problema, o esplora l'API **DocumentVisitor** per un'analisi più profonda del contenuto. Buona programmazione, e che tutti i tuoi font rimangano dove ti aspetti! + +--- + +![Rileva i font mancanti in Aspose.Words – screenshot dell'output della console](https://example.com/images/detect-missing-fonts.png "output consolevamento font mancanti") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/italian/words/net/images-and-shapes/_index.md b/content/italian/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..a6f6816fc --- /dev/null +++ b/content/italian/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "italian" +type: "category" +--- + +# Images And Shapes diff --git a/content/italian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/italian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..351ce5977 --- /dev/null +++ b/content/italian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Aggiungi rapidamente l'ombra a una forma con Aspose.Words. Scopri come + creare un documento Word usando Aspose, come aggiungere l'ombra a una forma e come + applicare la trasparenza dell'ombra in C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: it +og_description: Aggiungi un'ombra alla forma in un file Word usando Aspose.Words. + Questa guida passo‑passo mostra come creare un documento, aggiungere una forma e + applicare la trasparenza dell'ombra. +og_title: Aggiungi ombra alla forma – Tutorial Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Aggiungi ombra alla forma in un documento Word – Guida completa ad Aspose.Words +url: /italian/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Aggiungere Ombra alla Forma – Guida Completa a Aspose.Words + +Hai mai avuto bisogno di **aggiungere ombra alla forma** in un file Word ma non eri sicuro di quali chiamate API utilizzare? Non sei solo. Molti sviluppatori si trovano in difficoltà quando provano per la prima volta a dare a un rettangolo o a qualsiasi elemento di disegno una corretta ombra portata, soprattutto quando lavorano con Aspose.Words per .NET. + +In questo tutorial passeremo in rassegna tutto ciò che devi sapere: dalla **creazione di un documento Word usando Aspose** alla configurazione dell'ombra, alla regolazione del suo blur, distanza, angolo e persino **l'applicazione della trasparenza dell'ombra**. Alla fine avrai un programma C# pronto all'uso che produce un file `.docx` con un rettangolo elegantemente ombreggiato—senza dover intervenire manualmente in Word. + +--- + +## Cosa Imparerai + +- Come configurare un progetto Aspose.Words in Visual Studio. +- I passaggi esatti per **creare un documento Word usando Aspose** e inserire una forma. +- **Come aggiungere l'ombra alla forma** con pieno controllo su blur, distanza, angolo e trasparenza. +- Suggerimenti per risolvere problemi comuni (ad esempio, licenza mancante, unità errate). +- Un esempio di codice completo, pronto per il copia‑incolla, che puoi eseguire subito. + +> **Prerequisiti:** .NET 6+ (o .NET Framework 4.7.2+), una licenza valida di Aspose.Words (o la versione di prova gratuita) e una conoscenza di base di C#. + +--- + +## Passo 1 – Configura il tuo progetto e aggiungi Aspose.Words + +Prima di tutto. Apri Visual Studio, crea una nuova **Console App (.NET Core)** e aggiungi il pacchetto NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Consiglio professionale:** Se hai un file di licenza (`Aspose.Words.lic`), copialo nella radice del progetto e caricalo all'avvio. Questo evita la filigrana che appare nella modalità di valutazione gratuita. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Passo 2 – Crea un nuovo documento vuoto + +Ora creiamo effettivamente **un documento Word usando Aspose**. Questo oggetto servirà da tela per la nostra forma. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +La classe `Document` è il punto di ingresso per tutto il resto—paragrafi, sezioni e, naturalmente, oggetti di disegno. + +--- + +## Passo 3 – Inserisci una forma rettangolare + +Con il documento pronto, possiamo aggiungere una forma. Qui scegliamo un semplice rettangolo, ma la stessa logica funziona per cerchi, linee o poligoni personalizzati. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Perché una forma?** In Aspose.Words un oggetto `Shape` può contenere testo, immagini o fungere semplicemente da elemento decorativo. Aggiungere un'ombra a una forma è molto più semplice che cercare di manipolare una cornice immagine. + +--- + +## Passo 4 – Configura l'ombra (Aggiungere ombra alla forma) + +Questo è il cuore del tutorial—**come aggiungere l'ombra alla forma** e perfezionare il suo aspetto. La proprietà `ShadowFormat` ti offre pieno controllo. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Cosa fa ciascuna proprietà + +| Proprietà | Effetto | Valori tipici | +|-----------|---------|----------------| +| **Visible** | Attiva/disattiva l'ombra. | `true` / `false` | +| **Blur** | Ammorbidisce i bordi dell'ombra. | `0` (duro) a `10` (molto morbido) | +| **Distance** | Sposta l'ombra lontano dalla forma. | `1`–`5` punti è comune | +| **Angle** | Controlla la direzione dello spostamento. | `0`–`360` gradi | +| **Transparency** | Rende l'ombra parzialmente trasparente. | `0` (opaco) a `1` (invisibile) | + +> **Caso limite:** Se imposti `Transparency` a `1`, l'ombra scompare completamente—utile per attivarla/disattivarla programmaticamente. + +--- + +## Passo 5 – Aggiungi la forma al documento + +Ora colleghiamo la forma al primo paragrafo del corpo del documento. Aspose crea automaticamente un paragrafo se non ne esiste. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Se il tuo documento contiene già del contenuto, puoi inserire la forma in qualsiasi nodo usando `InsertAfter` o `InsertBefore`. + +--- + +## Passo 6 – Salva il documento + +Infine, scrivi il file su disco. Puoi scegliere qualsiasi formato supportato (`.docx`, `.pdf`, `.odt`, ecc.), ma per questo tutorial rimarremo al formato Word nativo. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Apri il file risultante `ShadowedShape.docx` in Microsoft Word e vedrai un rettangolo con un'ombra morbida a 45 gradi, trasparente al 30 %—esattamente come abbiamo configurato. + +--- + +## Esempio completo funzionante + +Di seguito trovi il programma **completo, pronto per il copia‑incolla** che incorpora tutti i passaggi sopra. Salvalo come `Program.cs` ed eseguilo con `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Output previsto:** Un file chiamato `ShadowedShape.docx` contenente un singolo rettangolo con una leggera ombra sfumata semi‑trasparente inclinata a 45°. + +--- + +## Varianti e consigli avanzati + +### Cambiare il colore dell'ombra + +Per impostazione predefinita l'ombra eredita il colore di riempimento della forma, ma puoi impostare un colore personalizzato: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Più forme con ombre diverse + +Se ti servono diverse forme, basta ripetere i passaggi di creazione e configurazione. Ricorda di assegnare a ogni forma un nome univoco se prevedi di farvi riferimento in seguito. + +### Esportare in PDF con ombre preservate + +Aspose.Words preserva gli effetti di ombra quando salva in PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Problemi comuni + +| Sintomo | Probabile causa | Soluzione | +|---------|-----------------|-----------| +| Ombra non visibile | `ShadowFormat.Visible` lasciato a `false` | Impostare a `true`. | +| L'ombra appare troppo dura | `Blur` impostato a `0` | Aumentare `Blur` a 3–6. | +| L'ombra scompare in PDF | Uso di una vecchia versione di Aspose.Words (< 22.9) | Aggiornare alla libreria più recente. | + +--- + +## Conclusione + +Abbiamo coperto **come aggiungere l'ombra alla forma** usando Aspose.Words, dall'inizializzazione di un documento alla regolazione fine di blur, distanza, angolo e **l'applicazione della trasparenza dell'ombra**. L'esempio completo dimostra un approccio pulito, pronto per la produzione, che puoi adattare a qualsiasi forma o layout di documento. + +Hai domande su **create word document using aspose** per scenari più complessi—come tabelle con ombre o forme guidate da dati dinamici? Lascia un commento qui sotto o consulta i tutorial correlati su gestione delle immagini e formattazione dei paragrafi in Aspose.Words. + +Buon coding e divertiti a dare ai tuoi documenti Word quel tocco visivo in più! + +--- + +![esempio di aggiunta ombra alla forma](shadowed_shape.png "esempio di aggiunta ombra alla forma") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/japanese/words/_index.md b/content/japanese/words/_index.md new file mode 100644 index 000000000..d2774476e --- /dev/null +++ b/content/japanese/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "japanese" +type: "family" +--- + +# Words Tutorials diff --git a/content/japanese/words/net/_index.md b/content/japanese/words/net/_index.md new file mode 100644 index 000000000..bceaaaccf --- /dev/null +++ b/content/japanese/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "japanese" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/japanese/words/net/getting-started/_index.md b/content/japanese/words/net/getting-started/_index.md new file mode 100644 index 000000000..3754c4087 --- /dev/null +++ b/content/japanese/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "japanese" +type: "category" +--- + +# Getting Started diff --git a/content/japanese/words/net/getting-started/tutorial/_index.md b/content/japanese/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..56a423ffb --- /dev/null +++ b/content/japanese/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: ja +url: /japanese/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Aspose.Words ドキュメントにおける欠損フォントの検出 – 完全 C# ガイド + +Aspose.Words で Word ファイルを読み込むときに **欠損フォントを検出** する方法を考えたことはありますか?日常業務の中で、元のドキュメントがインストールされていないフォントを使用していたために、見た目が崩れた PDF に何度か遭遇しました。良いニュースは、Aspose.Words がフォントを置き換えるタイミングを正確に教えてくれ、シンプルな warning コールバックでその情報を取得できることです。 + +このチュートリアルでは、**完全で実行可能なサンプル**を通して、すべてのフォント置換をログに記録する方法、コールバックが重要な理由、そして堅牢な欠損フォント検出のためのいくつかの追加テクニックを紹介します。余計な説明は省き、今日すぐに動作させるために必要なコードと考え方だけを提供します。 + +--- + +## 学べること + +- **Aspose.Words warning コールバック** を実装してフォント置換イベントを捕捉する方法。 +- **LoadOptions C#** を設定し、ドキュメント読み込み時にコールバックが呼び出されるようにする方法。 +- 欠損フォント検出が実際に機能したかを検証し、コンソール出力がどのようになるかを確認する方法。 +- 大量バッチやヘッドレス環境向けのオプション調整。 + +**Prerequisites** – 最近の Aspose.Words for .NET(コードは 23.12 でテスト)と .NET 6 以降、そして C# の基本的な知識が必要です。これらが揃っていればすぐに始められます。 + +--- + +## Warning コールバックで欠損フォントを検出する + +このソリューションの核心は `IWarningCallback` の実装です。Aspose.Words はさまざまな状況で `WarningInfo` オブジェクトを発行しますが、ここでは `WarningType.FontSubstitution` のみを対象とします。実際にフックする方法を見てみましょう。 + +### Step 1: Font‑Warning コレクタの作成 + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Why this matters*: `WarningType.FontSubstitution` でフィルタリングすることで、無関係な警告(例: 非推奨機能)によるノイズを防げます。`info.Description` には元のフォント名と使用された代替フォントがすでに含まれているため、明確な監査トレイルが得られます。 + +--- + +## コールバックを使用するように LoadOptions を設定する + +ここで、Aspose.Words にファイル読み込み時にコレクタを使用するよう指示します。 + +### Step 2: LoadOptions の設定 + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Why this matters*: `LoadOptions` はコールバックや暗号化パスワード、その他の読み込み動作を設定できる唯一の場所です。`Document` コンストラクタから分離しておくことで、複数のファイルでコードを再利用しやすくなります。 + +--- + +## ドキュメントを読み込み、欠損フォントを取得する + +コールバックが設定されたら、次は単にドキュメントを読み込むだけです。 + +### Step 3: DOCX(またはサポートされている任意の形式)を読み込む + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +`Document` コンストラクタがファイルを解析すると、欠損フォントがある場合に `FontWarningCollector` が呼び出されます。コンソールには次のような行が表示されます。 + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +この行が **欠損フォントの検出** が機能したことを示す具体的な証拠です。 + +--- + +## 出力の確認 – 期待される結果 + +ターミナルまたは Visual Studio からプログラムを実行します。ソースドキュメントにインストールされていないフォントが含まれている場合、少なくとも1行の “Font substituted” が表示されます。ドキュメントがインストール済みフォントのみを使用している場合、コールバックは何も出力せず、 “Document loaded successfully.” メッセージだけが表示されます。 + +**Tip**: 再確認するには、Microsoft で該当の Word ファイルを開き、フォント一覧を確認します。*Home → Font* グループの *Replace Fonts* に表示されるフォントは、置き換えの対象となり得ます。 + +--- + +## 高度な使用法: バルクで欠損フォントを検出する + +多数のファイルをスキャンする必要があることがよくあります。同じパターンはスケーラブルです。 + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +`FontWarningCollector` は呼び出されるたびにコンソールへ書き込むため、追加の仕組みなしでファイルごとのレポートが得られます。実運用ではファイルやデータベースへのログ出力が必要になる場合があります。その際は `Console.WriteLine` を好みのロガーに置き換えるだけです。 + +--- + +## よくある落とし穴とプロのコツ + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **警告が表示されない** | ドキュメントに実際にインストール済みフォントしか含まれていないためです。 | Word でファイルを開くか、システムからフォントを意図的に削除して確認してください。 | +| **コールバックが呼び出されない** | `LoadOptions.WarningCallback` が設定されていない、または後で新しい `LoadOptions` インスタンスが使用されたためです。 | 単一の `LoadOptions` オブジェクトを保持し、すべてのロードで再利用してください。 | +| **無関係な警告が多すぎる** | `WarningType.FontSubstitution` でフィルタリングしていないためです。 | 示したように `if (info.Type == WarningType.FontSubstitution)` ガードを追加してください。 | +| **大容量ファイルでのパフォーマンス低下** | コールバックがすべての警告で実行され、大きなドキュメントでは警告が多数発生するためです。 | `LoadOptions.WarningCallback` で他の警告タイプを無効化するか、既知の場合は `LoadOptions.LoadFormat` を特定の形式に設定してください。 | + +--- + +## 完全動作例(コピー&ペースト可能) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**期待されるコンソール出力**(欠損フォントが検出された場合): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +置き換えが発生しなければ、成功行だけが表示されます。 + +--- + +## 結論 + +これで、Aspose.Words が処理するあらゆるドキュメントに対して **完全な、プロダクション対応の欠損フォント検出方法** を手に入れました。**Aspose.Words warning コールバック** を活用し、**LoadOptions C#** を設定することで、すべてのフォント置換をログに記録し、レイアウト問題をトラブルシュートし、PDF が意図した外観と感触を保つことができます。 + +単一ファイルから大量バッチまで、パターンは同じです。`IWarningCallback` を実装し、`LoadOptions` に組み込み、Aspose.Words に重い処理を任せましょう。 + +次のステップに進む準備はできましたか?この手法を **font embedding** や **fallback font families** と組み合わせて自動的に問題を解決したり、**DocumentVisitor** API を使ってより深いコンテンツ分析に挑戦したりしてみてください。コーディングを楽しみ、すべてのフォントが期待通りの場所にあることを願っています! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/japanese/words/net/images-and-shapes/_index.md b/content/japanese/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..9b72396da --- /dev/null +++ b/content/japanese/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "japanese" +type: "category" +--- + +# Images And Shapes diff --git a/content/japanese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/japanese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..b6fb423c2 --- /dev/null +++ b/content/japanese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,265 @@ +--- +category: general +date: 2025-12-08 +description: Aspose.Words を使用して形状に素早く影を追加します。Aspose を使って Word 文書を作成する方法、形状に影を付ける方法、そして + C# で影の透明度を適用する方法を学びましょう。 +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: ja +og_description: Aspose.Words を使用して Word ファイルの図形に影を追加します。このステップバイステップガイドでは、ドキュメントの作成、図形の追加、影の透明度の適用方法を示します。 +og_title: 図形に影を追加 – Aspose.Words C# チュートリアル +tags: +- Aspose.Words +- C# +- Word Automation +title: Word文書の図形に影を追加する – 完全なAspose.Wordsガイド +url: /japanese/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# 形状に影を追加 – 完全な Aspose.Words ガイド + +Word ファイルで **形状に影を追加** したいと思ったことはありますか、でもどの API 呼び出しを使えばよいか分からなかったことはありませんか? あなたは一人ではありません。多くの開発者は、特に Aspose.Words for .NET を使用しているときに、矩形やその他の描画要素に適切なドロップシャドウを付けようと最初に壁にぶつかります。 + +このチュートリアルでは、**Aspose を使用して Word ドキュメントを作成**することから、影の設定、ぼかし、距離、角度、さらには **影の透明度を適用** する方法まで、必要なすべてを順を追って解説します。最後まで読めば、手動で Word をいじることなく、きれいに陰影が付いた矩形を含む `.docx` ファイルを生成する実行可能な C# プログラムが手に入ります。 + +--- + +## 学べること + +- Visual Studio で Aspose.Words プロジェクトをセットアップする方法。 +- **Aspose を使用して Word ドキュメントを作成**し、シェイプを挿入する正確な手順。 +- **シェイプに影を追加**する方法(ぼかし、距離、角度、透明度をフルコントロール)。 +- 一般的な落とし穴のトラブルシューティングのヒント(例:ライセがない、単位が間違っている)。 +- すぐに実行できる完全なコピー&ペーストコードサンプル。 + +> **前提条件:** .NET 6 以上(または .NET Framework 4.7.2 以上)、有効な Aspose.Words ライセンス(または無料トライアル)、そして C# の基本的な知識。 + +--- + +## Step 1 – プロジェクトをセットアップして Aspose.Words を追加 + +まず最初に、Visual Studio を開き、**Console App (.NET Core)** を新規作成し、Aspose.Words NuGet パッケージを追加します: + +```bash +dotnet add package Aspose.Words +``` + +> **プロのコツ:** ライセンス ファイル (`Aspose.Words.lic`) をプロジェクトのルートにコピーし、起動時にロードしてください。これにより、無料評価モードで表示される透かしを回避できます。 + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Step 2 – 新しい空白ドキュメントを作成 + +ここで実際に **Aspose を使用して Word ドキュメントを作成** します。このオブジェクトがシェイプのキャンバスになります。 + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` クラスは、段落、セクション、そしてもちろん描画オブジェクトすべてのエントリーポイントです。 + +--- + +## Step 3 – 矩形シェイプを挿入 + +ドキュメントの準備ができたらシェイプを追加します。ここではシンプルな矩形を選びますが、同じロジックで円や直線、カスタム多角形にも対応できます。 + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **なぜシェイプか?** Aspose.Words の `Shape` オブジェクトはテキスト、画像、または装飾要素として機能します。シェイプに影を追加する方が、画像フレームを操作するよりはるかに簡単です。 + +--- + +## Step 4 – 影を設定(形状に影を追加) + +本チュートリアルの核心です — **シェイプに影を追加**し、その外観を微調整します。`ShadowFormat` プロパティでフルコントロールが可能です。 + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### 各プロパティの役割 + +| プロパティ | 効果 | 典型的な値 | +|----------|--------|----------------| +| **Visible** | 影のオン/オフを切り替えます。 | `true` / `false` | +| **Blur** | 影のエッジを柔らかくします。 | `0` (ハード) から `10` (非常にソフト) | +| **Distance** | 影をシェイプから離します。 | `1`–`5` ポイントが一般的 | +| **Angle** | オフセットの方向を制御します。 | `0`–`360` 度 | +| **Transparency** | 影を部分的に透過させます。 | `0` (不透明) から `1` (見えない) | + +> **エッジケース:** `Transparency` を `1` に設定すると影が完全に消えます — プログラムでトグルする際に便利です。 + +--- + +## Step 5 – シェイプをドキュメントに追加 + +ここでシェイプをドキュメント本文の最初の段落に添付します。Aspose は段落が存在しない場合自動的に作成します。 + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +既にコンテンツがある場合は、`InsertAfter` や `InsertBefore` を使用して任意のノードにシェイプを挿入できます。 + +--- + +## Step 6 – ドキュメントを保存 + +最後にファイルをディスクに書き出します。サポートされている任意の形式(`.docx`、`.pdf`、`.odt` など)を選べますが、このチュートリアルではネイティブの Word 形式に限定します。 + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +生成された `ShadowedShape.docx` を Microsoft Word で開くと、45 度の方向に 30 % 透明なソフトな影が付いた矩形が表示されます — ちょうど設定した通りです。 + +--- + +## 完全動作サンプル + +以下は **コピー&ペーストでそのまま実行可能** なプログラム全体です。`Program.cs` として保存し、`dotnet run` で実行してください。 + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**期待される出力:** `ShadowedShape.docx` という名前のファイルが作成され、45° の角度で微妙に半透明のドロップシャドウが付いた単一の矩形が含まれます。 + +--- + +## バリエーションと高度なヒント + +### 影の色を変更 + +デフォルトでは影はシェイプの塗りつぶし色を継承しますが、カスタムカラーを設定できます: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 異なる影を持つ複数シェイプ + +複数のシェイプが必要な場合は、作成と設定の手順を繰り返すだけです。後で参照する予定がある場合は、各シェイプに固有の名前を付けることを忘れずに。 + +### 影を保持したまま PDF にエクスポート + +Aspose.Words は PDF 保存時に影効果を保持します: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### よくある落とし穴 + +| 症状 | 考えられる原因 | 対策 | +|---------|--------------|-----| +| 影が表示されない | `ShadowFormat.Visible` が `false` のまま | `true` に設定する。 | +| 影が硬すぎる | `Blur` が `0` に設定されている | `Blur` を 3–6 に上げる。 | +| PDF で影が消える | 古い Aspose.Words バージョン (< 22.9) を使用 | 最新のライブラリにアップグレードする。 | + +--- + +## 結論 + +Aspose.Words を使用して **形状に影を追加**する方法、ドキュメントの初期化からぼかし、距離、角度、そして **影の透明度を適用**するまでを網羅しました。完全なサンプルは、任意のシェイプやドキュメントレイアウトに適用できる、実務レベルのクリーンなアプローチを示しています。 + +**create word document using aspose** に関する、テーブルに影を付ける、動的データ駆動シェイプなど、より複雑なシナリオについて質問がありますか? コメントを残すか、Aspose.Words の画像処理や段落書式設定に関する関連チュートリアルをご覧ください。 + +コーディングを楽しみながら、Word ドキュメントに余分なビジュアル・ポリッシュを加えてください! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/korean/words/_index.md b/content/korean/words/_index.md new file mode 100644 index 000000000..ecb561fe3 --- /dev/null +++ b/content/korean/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "korean" +type: "family" +--- + +# Words Tutorials diff --git a/content/korean/words/net/_index.md b/content/korean/words/net/_index.md new file mode 100644 index 000000000..3301a2f29 --- /dev/null +++ b/content/korean/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "korean" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/korean/words/net/getting-started/_index.md b/content/korean/words/net/getting-started/_index.md new file mode 100644 index 000000000..fee4cc204 --- /dev/null +++ b/content/korean/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "korean" +type: "category" +--- + +# Getting Started diff --git a/content/korean/words/net/getting-started/tutorial/_index.md b/content/korean/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..5188ef3e1 --- /dev/null +++ b/content/korean/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: ko +url: /korean/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Aspose.Words 문서에서 누락된 폰트 감지 – 완전한 C# 가이드 + +Aspose.Words로 Word 파일을 로드할 때 **누락된 폰트를 감지**하는 방법이 궁금하셨나요? 일상 업무에서 원본 문서가 설치되지 않은 폰트를 사용해서 몇몇 PDF가 이상하게 보인 적이 있습니다. 좋은 소식은? Aspose.Words는 폰트를 대체할 때 정확히 알려주며, 간단한 warning callback으로 그 정보를 캡처할 수 있습니다. + +이 튜토리얼에서는 **완전하고 실행 가능한 예제**를 통해 모든 폰트 대체를 로그하는 방법, 콜백이 왜 중요한지, 그리고 견고한 누락 폰트 감지를 위한 몇 가지 추가 팁을 보여드립니다. 불요한 내용은 없으며, 오늘 바로 작동하도록 필요한 코드와 논리만 제공합니다. + +--- + +## 배울 내용 + +- **Aspose.Words warning callback**을 구현하여 폰트 대체 이벤트를 포착하는 방법. +- **LoadOptions C#**을 구성하여 문서를 로드하는 동안 콜백이 호출되도록 하는 방법. +- 누락된 폰트 감지가 실제로 작동했는지 확인하는 방법 및 콘솔 출력 예시. +- 대량 처리나 헤드리스 환경을 위한 선택적 조정 사항. + +**Prerequisites** – 최신 버전의 Aspose.Words for .NET(코드는 23.12 버전에서 테스트됨), .NET 6 이상, 그리고 C#에 대한 기본적인 이해가 필요합니다. 이 조건만 충족한다면 바로 시작할 수 있습니다. + +--- + +## Warning Callback을 사용한 누락된 폰 감지 + +이 솔루션의 핵심은 `IWarningCallback` 구현입니다. Aspose.Words는 다양한 상황에서 `WarningInfo` 객체를 발생시키지만, 여기서는 `WarningType.FontSubstitution`만 신경 씁니다. 어떻게 연결하는지 살펴보겠습니다. + +### Step 1: Font‑Warning Collector 만들기 + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Why this matters*: `WarningType.FontSubstitution`만 필터링하면 관련 없는 경고(예: 사용 중단된 기능)로 인한 잡음을 피할 수 있습니다. `info.Description`에는 원본 폰트 이름과 사용된 대체 폰트가 이미 포함되어 있어 명확한 감사 로그를 제공합니다. + +--- + +## Callback을 사용하도록 LoadOptions 구성 + +이제 Aspose.Words가 파일을 로드할 때 우리 컬렉터를 사용하도록 지시합니다. + +### Step 2: LoadOptions 설정 + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Why this matters*: `LoadOptions`는 콜백, 암호, 기타 로딩 동작을 플러그인할 수 있는 유일한 위치입니다. `Document` 생성자와 분리하면 여러 파일에 대해 코드를 재사용할 수 있습니다. + +--- + +## 문서를 로드하고 누락된 폰트 캡처 + +콜백이 연결되었으니 이제 문서를 로드하기만 하면 됩니다. + +### Step 3: DOCX(또는 지원되는 형식) 로드 + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +`Document` 생성자가 파일을 파싱할 때, 누락된 폰트가 있으면 `FontWarningCollector`가 트리거됩니다. 콘솔에는 다음과 같은 라인이 표시됩니다: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +이 라인은 **누락된 폰트를 감지**했음을 입증하는 구체적인 증거입니다. + +--- + +## 출력 확인 – 기대 결과 + +터미널이나 Visual Studio에서 프로그램을 실행하세요. 원본 문서에 설치되지 않은 폰트가 포함되어 있으면 최소 하나 이상의 “Font substituted” 라인이 표시됩니다. 문서가 설치된 폰트만 사용한다면 콜백은 조용히 동작하고 “Document loaded successfully.” 메시지만 표시됩니다. + +**Tip**: 두 번 확인하려면 Microsoft Word에서 해당 파일을 열고 폰트 목록을 확인하세요. *Home → Font* 그룹 아래 *Replace Fonts*에 나타나는 폰트는 대체 후보가 됩니다. + +--- + +## 고급: 대량 파일에서 누락된 폰트 감지 + +수십 개의 파일을 스캔해야 할 때가 많습니다. 동일한 패턴을 그대로 확장하면 됩니다: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +`FontWarningCollector`가 호출될 때마다 콘솔에 기록하므로 별도의 로직 없이 파일별 보고서를 얻을 수 있습니다. 실제 운영 환경에서는 파일이나 데이터베이스에 로그를 남기고 싶을 수 있는데, `Console.WriteLine`을 원하는 로거로 교체하면 됩니다. + +--- + +## 흔히 발생하는 문제 & 전문가 팁 + +| 문제 | 발생 원인 | 해결 방법 | +|------|-----------|-----------| +| **경고가 전혀 나타나지 않음** | 문서에 실제로 설치된 폰트만 포함되어 있음 | Word에서 파일을 열어 확인하거나 시스템에서 일부 폰트를 의도적으로 제거해 보세요. | +| **Callback이 호출되지 않음** | `LoadOptions.WarningCallback`이 할당되지 않았거나 이후에 새로운 `LoadOptions` 인스턴스를 사용함 | 단일 `LoadOptions` 객체를 유지하고 모든 로드에 재사용하세요. | +| **관련 없는 경고가 너무 많음** | `WarningType.FontSubstitution`으로 필터링하지 않음 | 예시와 같이 `if (info.Type == WarningType.FontSubstitution)` 조건을 추가하세요. | +| **대용량 파일에서 성능 저하** | 콜백이 모든 경고마다 실행돼 대량 문서에서 많음 | `LoadOptions.WarningCallback`을 통해 다른 경고 유형을 비활성화하거나, 파일 형식을 알고 있다면 `LoadOptions.LoadFormat`을 지정하세요. | + +--- + +## 전체 작업 예제 (복사‑붙여넣기 가능) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Expected console output** (when a missing font is encountered): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +대체가 발생하지 않으면 성공 라인만 표시됩니다. + +--- + +## 결론 + +이제 Aspose.Words로 처리하는 모든 문서에서 **완전하고 프로덕션 수준의 누락 폰트 감지** 방법을 갖추었습니다. **Aspose.Words warning callback**과 **LoadOptions C#**을 활용하면 모든 폰트 대체를 로그하고 레이아웃 문제를 진단하며 PDF가 의도한 모양을 유지하도록 할 수 있습니다. + +단일 파일이든 대량 배치이든 패턴은 동일합니다—`IWarningCallback`을 구현하고 `LoadOptions`에 연결하면 Aspose.Words가 무거운 작업을 처리합니다. + +다음 단계가 궁금하신가요? **폰트 임베딩**이나 **fallback font families**와 결합해 문제를 자동으로 해결하거나, **DocumentVisitor** API를 탐색해 더 깊은 콘텐츠 분석을 시도해 보세요. 즐거운 코딩 되시고, 모든 폰트가 기대한 위치에 머물길 바랍니다! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/korean/words/net/images-and-shapes/_index.md b/content/korean/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..407bb5674 --- /dev/null +++ b/content/korean/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "korean" +type: "category" +--- + +# Images And Shapes diff --git a/content/korean/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/korean/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..563830c8a --- /dev/null +++ b/content/korean/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2025-12-08 +description: Aspose.Words를 사용하여 도형에 빠르게 그림자를 추가하세요. Aspose를 이용해 Word 문서를 만드는 방법, 도형에 + 그림자를 추가하는 방법, 그리고 C#에서 그림자 투명도를 적용하는 방법을 배워보세요. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: ko +og_description: Aspose.Words를 사용하여 Word 파일의 도형에 그림자를 추가합니다. 이 단계별 가이드는 문서를 만들고, 도형을 + 추가하고, 그림자 투명도를 적용하는 방법을 보여줍니다. +og_title: 도형에 그림자 추가 – Aspose.Words C# 튜토리얼 +tags: +- Aspose.Words +- C# +- Word Automation +title: Word 문서에서 도형에 그림자 추가 – 완전한 Aspose.Words 가이드 +url: /korean/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# 도형에 그림자 추가 – 완전한 Aspose.Words 가이드 + +Word 파일에 **도형에 그림자 추가**가 필요했지만 어떤 API 호출을 사용해야 할지 몰랐던 적이 있나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 처음으로 사각형이나 기타 그리기 요소에 적절한 드롭‑섀도우를 적용하려 할 때, 특히 Aspose.Words for .NET을 사용할 때 벽에 부딪히곤 합니다. + +이 튜토리얼에서는 **Aspose를 사용한 Word 문서 만들기**부터 그림자 구성, 흐림 정도, 거리, 각도 조정 및 **그림자 투명도 적용**까지 알아야 할 모든 것을 단계별로 안내합니다. 마지막에는 `.docx` 파일에 부드러운 그림자가 적용된 사각형을 생성하는 실행 가능한 C# 프로그램을 얻을 수 있습니다—Word에서 수동으로 조정할 필요가 없습니다. + +--- + +## 배울 내용 + +- Visual Studio에서 Aspose.Words 프로젝트 설정 방법. +- **Aspose를 사용한 Word 문서 만들기** 및 도형 삽입 정확한 단계. +- **도형에 그림자 추가** 방법과 흐림, 거리, 각도, 투명도에 대한 완전한 제어. +- 일반적인 문제점(예: 라이선스 누락, 단위 오류) 해결 팁. +- 오늘 바로 실행할 수 있는 완전한 복사‑붙여넣기 코드 샘플. + +> **전제 조건:** .NET 6+ (또는 .NET Framework 4.7.2+), 유효한 Aspose.Words 라이선스(또는 무료 체험판), 그리고 C#에 대한 기본적인 이해. + +--- + +## Step 1 – 프로젝트 설정 및 Aspose.Words 추가 + +먼저 Visual Studio를 열고 **새 콘솔 앱(.NET Core)**을 만든 뒤 Aspose.Words NuGet 패키지를 추가합니다: + +```bash +dotnet add package Aspose.Words +``` + +> **프로 팁:** 라이선스 파일(`Aspose.Words.lic`)이 있다면 프로젝트 루트에 복사하고 시작 시 로드하세요. 이렇게 하면 무료 평가판 모드에서 나타나는 워터마크를 방지할 수 있습니다. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Step 2 – 새 빈 문서 만들기 + +이제 실제로 **Aspose를 사용한 Word 문서 만들기**를 수행합니다. 이 객체가 도형을 그릴 캔버스 역할을 합니다. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` 클래스는 문단, 섹션 및 물론 그리기 객체 등 모든 작업의 진입점입니다. + +--- + +## Step 3 – 사각형 도형 삽입 + +문서가 준비되었으니 도형을 추가합니다. 여기서는 간단한 사각형을 선택하지만, 동일한 논리로 원, 선, 사용자 정의 다각형에도 적용할 수 있습니다. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **왜 도형인가?** Aspose.Words에서 `Shape` 객체는 텍스트, 이미지 또는 단순히 장식 요소로 사용할 수 있습니다. 도형에 그림자를 추가하는 것이 사진 프레임을 조작하는 것보다 훨씬 쉽습니다. + +--- + +## Step 4 – 그림자 구성 (Add Shadow to Shape) + +이 부분이 튜토리얼의 핵심—**도형에 그림자 추가**와 외관 미세 조정 방법입니다. `ShadowFormat` 속성을 통해 완전한 제어가 가능합니다. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### 각 속성의 역할 + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | 그림자를 켜거나 끕니다. | `true` / `false` | +| **Blur** | 그림자 가장자리를 부드럽게 합니다. | `0`(선명)부터 `10`(매우 부드러움)까지 | +| **Distance** | 그림자를 도형에서 떨어뜨립니다. | 일반적으로 `1`–`5` 포인트 | +| **Angle** | 오프셋 방향을 제어합니다. | `0`–`360`도 | +| **Transparency** | 그림자를 부분적으로 투명하게 합니다. | `0`(불투명)부터 `1`(투명)까지 | + +> **예외 상황:** `Transparency`를 `1`로 설정하면 그림자가 완전히 사라집니다—프로그램matically 토글할 때 유용합니다. + +--- + +## Step 5 – 도형을 문서에 추가 + +이제 도형을 문서 본문의 첫 번째 문단에 연결합니다. Aspose는 문단이 없을 경우 자동으로 생성합니다. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +문서에 이미 내용이 있다면 `InsertAfter` 또는 `InsertBefore`를 사용해 원하는 노드에 도형을 삽입할 수 있습니다. + +--- + +## Step 6 – 문서 저장 + +마지막으로 파일을 디스크에 씁니다. 지원되는 형식(`.docx`, `.pdf`, `.odt` 등) 중 원하는 것을 선택할 수 있지만, 이번 튜토리얼에서는 기본 Word 형식으로 저장합니다. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +생성된 `ShadowedShape.docx`를 Microsoft Word에서 열면 45도 각도에 30 % 투명한 부드러운 그림자가 적용된 사각형을 확인할 수 있습니다—우리가 설정한 그대로입니다. + +--- + +## 전체 작업 예제 + +아래는 **복사‑붙여넣기 바로 사용 가능한** 전체 프로그램입니다. `Program.cs`로 저장하고 `dotnet run`으로 실행하세요. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**예상 출력:** `ShadowedShape.docx`라는 파일이 생성되며, 45° 각도에 약간 투명한 드롭 섀도우가 적용된 사각형 하나가 포함됩니다. + +--- + +## 변형 및 고급 팁 + +### 그림자 색상 변경 + +기본적으로 그림자는 도형의 채우기 색을 상속하지만, 사용자 지정 색을 설정할 수 있습니다: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 서로 다른 그림자를 가진 다중 도형 + +여러 도형이 필요하면 생성 및 구성 단계를 반복하면 됩니다. 나중에 참조할 계획이라면 각 도형에 고유한 이름을 부여하세요. + +### 그림자 보존된 PDF 내보내기 + +Aspose.Words는 PDF 저장 시 그림자 효과를 유지합니다: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### 흔히 발생하는 문제 + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| 그림자가 보이지 않음 | `ShadowFormat.Visible`이 `false` 상태 | `true`로 설정 | +| 그림자가 너무 날카로움 | `Blur`가 `0`으로 설정 | `Blur`를 3–6으로 증가 | +| PDF에서 그림자 사라짐 | 오래된 Aspose.Words 버전(< 22.9) 사용 | 최신 라이브러리로 업그레이드 | + +--- + +## 결론 + +우리는 Aspose.Words를 사용해 **도형에 그림자 추가** 방법을 다루었습니다. 문서 초기화부터 흐림, 거리, 각도, **그림자 투명도 적용**까지 전체 과정을 살펴보았으며, 완전한 예제는 어떤 도형이나 레이아웃에도 적용 가능한 생산 준비된 접근 방식을 보여줍니다. + +**Aspose를 사용한 Word 문서 만들기**에 대한 더 복잡한 시나리오(예: 그림자가 있는 표, 동적 데이터 기반 도형 등)가 궁금하시면 아래 댓글을 남기거나 Aspose.Words 이미지 처리 및 문단 서식 관련 튜토리얼을 확인하세요. + +코딩을 즐기시고, Word 문서에 한층 더 멋진 시각적 효과를 부여해 보세요! + +--- + +![도형에 그림자 추가 예시](shadowed_shape.png "도형에 그림자 추가 예시") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/polish/words/_index.md b/content/polish/words/_index.md new file mode 100644 index 000000000..d22ef2add --- /dev/null +++ b/content/polish/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "polish" +type: "family" +--- + +# Words Tutorials diff --git a/content/polish/words/net/_index.md b/content/polish/words/net/_index.md new file mode 100644 index 000000000..70cfd539d --- /dev/null +++ b/content/polish/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "polish" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/polish/words/net/getting-started/_index.md b/content/polish/words/net/getting-started/_index.md new file mode 100644 index 000000000..cef9a7bbb --- /dev/null +++ b/content/polish/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "polish" +type: "category" +--- + +# Getting Started diff --git a/content/polish/words/net/getting-started/tutorial/_index.md b/content/polish/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..cececd061 --- /dev/null +++ b/content/polish/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: pl +url: /polish/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Wykrywanie brakujących czcionek w dokumentach Aspose.Words – kompletny przewodnik C# + +Zastanawiałeś się kiedyś, jak **wykrywać brakujące czcionki** podczas ładowania pliku Word przy użyciu Aspose.Words? W mojej codziennej pracy natknąłem się na kilka plików PDF, które wyglądały nieprawidłowo, ponieważ oryginalny dokument używał czcionki, której nie miałem zainstalowanej. Dobra wiadomość? Aspose.Words może dokładnie poinformować, kiedy zastępuje czcionkę, i możesz przechwycić tę informację za pomocą prostego wywołania zwrotnego ostrzeżenia. + +W tym samouczku przeprowadzimy Cię przez **kompletny, działający przykład**, który pokaże, jak rejestrować każdą zamianę czcionki, dlaczego wywołanie zwrotne ma znaczenie oraz kilka dodatkowych sztuczek dla solidnego wykrywania brakujących czcionek. Bez zbędnych wstępów, tylko kod i uzasadnienie, które potrzebujesz, aby uruchomić to już dziś. + +--- + +## Czego się nauczysz + +- Jak zaimplementować **Aspose.Words warning callback**, aby przechwycić zdarzenia zamiany czcionki. +- Jak skonfigurować **LoadOptions C#**, aby wywołanie zwrotne było uruchamiane podczas ładowania dokumentu. +- Jak zweryfikować, że wykrywanie brakujących czcionek naprawdę zadziałało i jak wygląda wyjście w konsoli. +- Opcjonalne dostosowania dla dużych partii lub środowisk bez interfejsu graficznego. + +**Wymagania wstępne** – Potrzebujesz aktualnej wersji Aspose.Words dla .NET (kod testowano z wersją 23.12), .NET 6 lub nowszego oraz podstawowej znajomości C#. Jeśli masz to wszystko, możesz zaczynać. + +--- + +## Wykrywanie brakujących czcionek za pomocą wywołania zwrotnego ostrzeżenia + +Sednem rozwiązania jest implementacja `IWarningCallback`. Aspose.Words generuje obiekt `WarningInfo` w wielu sytuacjach, ale nas interesuje tylko `WarningType.FontSubstitution`. Zobaczmy, jak się do tego podłączyć. + +### Krok 1: Utwórz kolektor ostrzeżeń czcionek + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Dlaczego to ważne*: Filtrując po `WarningType.FontSubstitution` unikamy bałaganu spowodowanego niepowiązanymi ostrzeżeniami (np. przestarzałe funkcje). `info.Description` już zawiera nazwę oryginalnej czcionki oraz użyty zamiennik, co daje przejrzysty ślad audytu. + +--- + +## Skonfiguruj LoadOptions, aby używać wywołania zwrotnego + +Teraz informujemy Aspose.Words, aby używał naszego kolektora podczas ładowania pliku. + +### Krok 2: Skonfiguruj LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Dlaczego to ważne*: `LoadOptions` to jedyne miejsce, w którym możesz podłączyć wywołanie zwrotne, hasła szyfrowania i inne zachowania ładowania. Trzymanie go oddzielnie od konstruktora `Document` sprawia, że kod jest wielokrotnego użytku w wielu plikach. + +--- + +## Załaduj dokument i przechwyć brakujące czcionki + +Po podłączeniu wywołania zwrotnego, następnym krokiem jest po prostu załadowanie dokumentu. + +### Krok 3: Załaduj swój DOCX (lub dowolny obsługiwany format) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Gdy konstruktor `Document` parsuje plik, każda brakująca czcionka wywołuje nasz `FontWarningCollector`. Konsola wyświetli linie takie jak: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Ta linia jest konkretnym dowodem, że **wykrywanie brakujących czcionek** zadziałało. + +--- + +## Zweryfikuj wyjście – czego się spodziewać + +Uruchom program z terminala lub Visual Studio. Jeśli dokument źródłowy zawiera czcionkę, której nie masz zainstalowanej, zobaczysz przynajmniej jedną linię „Font substituted”. Jeśli dokument używa wyłącznie zainstalowanych czcionek, wywołanie zwrotne pozostanie ciche i otrzymasz jedynie komunikat „Document loaded successfully.”. + +**Wskazówka**: Aby podwójnie sprawdzić, otwórz plik Word w Microsoft Word i przyjrzyj się liście czcionek. Każda czcionka, która pojawia się w *Replace Fonts* pod grupą *Home → Font*, jest kandydatem do zamiany. + +--- + +## Zaawansowane: Wykrywanie brakujących czcionek w partiach + +Często trzeba przeskanować dziesiątki plików. Ten sam wzorzec skaluje się dobrze: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Ponieważ `FontWarningCollector` zapisuje do konsoli przy każdym wywołaniu, otrzymasz raport per‑plik bez dodatkowego kodu. W scenariuszach produkcyjnych możesz chcieć logować do pliku lub bazy danych – po prostu zamień `Console.WriteLine` na wybrany logger. + +--- + +## Częste pułapki i wskazówki profesjonalne + +| Problem | Dlaczego się dzieje | Rozwiązanie | +|-------|----------------|-----| +| **Brak ostrzeżeń** | Dokument faktycznie zawiera tylko zainstalowane czcionki. | Sprawdź, otwierając plik w Wordzie lub celowo usuwając czcionkę z systemu. | +| **Callback nie wywołany** | `LoadOptions.WarningCallback` nigdy nie został przypisany lub później użyto nowej instancji `LoadOptions`. | Utrzymuj pojedynczy obiekt `LoadOptions` i używaj go przy każdym ładowaniu. | +| **Zbyt wiele niepowiązanych ostrzeżeń** | Nie filtrowałeś po `WarningType.FontSubstitution`. | Dodaj warunek `if (info.Type == WarningType.FontSubstitution)` jak pokazano. | +| **Spowolnienie wydajności przy dużych plikach** | Wywołanie zwrotne uruchamia się przy każdym ostrzeżeniu, co może być wiele w dużych dokumentach. | Wyłącz inne typy ostrzeżeń poprzez `LoadOptions.WarningCallback` lub ustaw `LoadOptions.LoadFormat` na konkretny typ, jeśli go znasz. | + +--- + +## Pełny działający przykład (gotowy do kopiowania i wklejania) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Oczekiwane wyjście w konsoli** (gdy napotkano brakującą czcionkę): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Jeśli nie nastąpi zamiana, zobaczysz tylko linię sukcesu. + +--- + +## Podsumowanie + +Masz teraz **kompletny, gotowy do produkcji sposób wykrywania brakujących czcionek** w każdym dokumencie przetwarzanym przez Aspose.Words. Korzystając z **Aspose.Words warning callback** i konfigurując **LoadOptions C#**, możesz rejestrować każdą zamianę czcionki, rozwiązywać problemy z układem i zapewnić, że Twoje PDF-y zachowają zamierzony wygląd. + +Od pojedynczego pliku po masową partię, wzorzec pozostaje ten sam — zaimplementuj `IWarningCallback`, podłącz go do `LoadOptions` i pozwól Aspose.Words wykonać ciężką pracę. + +Gotowy na kolejny krok? Spróbuj połączyć to z **font embedding** lub **fallback font families**, aby automatycznie naprawić problem, lub zbadaj API **DocumentVisitor** w celu głębszej analizy treści. Szczęśliwego kodowania i niech wszystkie Twoje czcionki pozostaną tam, gdzie ich oczekujesz! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/polish/words/net/images-and-shapes/_index.md b/content/polish/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..a739d3a0b --- /dev/null +++ b/content/polish/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "polish" +type: "category" +--- + +# Images And Shapes diff --git a/content/polish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/polish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..ed8df8621 --- /dev/null +++ b/content/polish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Szybko dodaj cień do kształtu za pomocą Aspose.Words. Dowiedz się, jak + utworzyć dokument Word przy użyciu Aspose, jak dodać cień do kształtu oraz jak zastosować + przezroczystość cienia w C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: pl +og_description: Dodaj cień do kształtu w pliku Word przy użyciu Aspose.Words. Ten + przewodnik krok po kroku pokazuje, jak utworzyć dokument, dodać kształt i zastosować + przezroczystość cienia. +og_title: Dodaj cień do kształtu – Poradnik Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Dodaj cień do kształtu w dokumencie Word – Kompletny przewodnik Aspose.Words +url: /polish/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Dodaj cień do kształtu – Kompletny przewodnik Aspose.Words + +Kiedykolwiek potrzebowałeś **dodać cień do kształtu** w pliku Word, ale nie byłeś pewien, które wywołania API użyć? Nie jesteś sam. Wielu programistów napotyka trudności, gdy po raz pierwszy próbują dodać prostokątowi lub innemu elementowi rysunkowemu właściwy cień, szczególnie pracując z Aspose.Words dla .NET. + +W tym samouczku przeprowadzimy Cię przez wszystko, co musisz wiedzieć: od **tworzenia dokumentu Word przy użyciu Aspose** po konfigurowanie cienia, dostosowywanie jego rozmycia, odległości, kąta oraz nawet **stosowanie przezroczystości cienia**. Na końcu będziesz mieć gotowy do uruchomienia program w C#, który generuje plik `.docx` z ładnie przyciemnionym prostokątem — bez ręcznego manipulowania w Wordzie. + +--- + +## Czego się nauczysz + +- Jak skonfigurować projekt Aspose.Words w Visual Studio. +- Dokładne kroki do **tworzenia dokumentu Word przy użyciu Aspose** i wstawiania kształtu. +- **Jak dodać cień do kształtu** z pełną kontrolą nad rozmyciem, odległością, kątem i przezroczystością. +- Wskazówki dotyczące rozwiązywania typowych problemów (np. brak licencji, nieprawidłowe jednostki). +- Pełny, gotowy do skopiowania i wklejenia przykład kodu, który możesz uruchomić już dziś. + +> **Wymagania wstępne:** .NET 6+ (lub .NET Framework 4.7.2+), ważna licencja Aspose.Words (lub wersja próbna), oraz podstawowa znajomość C#. + +--- + +## Krok 1 – Skonfiguruj projekt i dodaj Aspose.Words + +Na początek. Otwórz Visual Studio, utwórz nową **Console App (.NET Core)** i dodaj pakiet NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Wskazówka:** Jeśli masz plik licencji (`Aspose.Words.lic`), skopiuj go do katalogu głównego projektu i załaduj przy uruchamianiu. Zapobiega to pojawianiu się znaku wodnego w trybie darmowej oceny. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Krok 2 – Utwórz nowy pusty dokument + +Teraz faktycznie **tworzymy dokument Word przy użyciu Aspose**. Ten obiekt będzie służył jako płótno dla naszego kształtu. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Klasa `Document` jest punktem wejścia dla wszystkiego — akapity, sekcje i oczywiście obiekty rysunkowe. + +--- + +## Krok 3 – Wstaw prostokąt jako kształt + +Gdy dokument jest gotowy, możemy dodać kształt. Tutaj wybieramy prosty prostokąt, ale ta sama logika działa dla kół, linii lub własnych wielokątów. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Dlaczego kształt?** W Aspose.Words obiekt `Shape` może zawierać tekst, obrazy lub po prostu pełnić rolę elementu dekoracyjnego. Dodanie cienia do kształtu jest znacznie prostsze niż próba manipulacji ramką obrazu. + +--- + +## Krok 4 – Skonfiguruj cień (Dodaj cień do kształtu) + +To jest sedno samouczka — **jak dodać cień do kształtu** i precyzyjnie dostroić jego wygląd. Właściwość `ShadowFormat` daje pełną kontrolę. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Co robi każda właściwość + +| Właściwość | Efekt | Typowe wartości | +|------------|-------|-----------------| +| **Visible** | Włącza/wyłącza cień. | `true` / `false` | +| **Blur** | Zmiękcza krawędzie cienia. | `0` (twardy) do `10` (bardzo miękki) | +| **Distance** | Oddala cień od kształtu. | `1`–`5` punktów jest typowe | +| **Angle** | Kontroluje kierunek przesunięcia. | `0`–`360` stopni | +| **Transparency** | Sprawia, że cień jest częściowo przezroczysty. | `0` (nieprzezroczysty) do `1` (niewidzialny) | + +> **Przypadek brzegowy:** Jeśli ustawisz `Transparency` na `1`, cień zniknie całkowicie — przydatne przy przełączaniu go programowo. + +--- + +## Krok 5 – Dodaj kształt do dokumentu + +Teraz dołączamy kształt do pierwszego akapitu ciała dokumentu. Aspose automatycznie tworzy akapit, jeśli nie istnieje. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Jeśli Twój dokument już zawiera treść, możesz wstawić kształt w dowolnym węźle używając `InsertAfter` lub `InsertBefore`. + +--- + +## Krok 6 – Zapisz dokument + +Na koniec zapisz plik na dysku. Możesz wybrać dowolny obsługiwany format (`.docx`, `.pdf`, `.odt` itp.), ale w tym samouczku pozostaniemy przy natywnym formacie Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Otwórz powstały plik `ShadowedShape.docx` w Microsoft Word i zobaczysz prostokąt z miękkim, 45‑stopniowym cieniem, który jest w 30 % przezroczysty — dokładnie tak, jak skonfigurowaliśmy. + +--- + +## Pełny działający przykład + +Poniżej znajduje się **kompletny, gotowy do skopiowania i wklejenia** program, który zawiera wszystkie powyższe kroki. Zapisz go jako `Program.cs` i uruchom poleceniem `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Oczekiwany wynik:** Plik o nazwie `ShadowedShape.docx` zawierający pojedynczy prostokąt z subtelnym, półprzezroczystym cieniem skierowanym pod kątem 45°. + +--- + +## Warianty i zaawansowane wskazówki + +### Zmiana koloru cienia + +Domyślnie cień dziedziczy kolor wypełnienia kształtu, ale możesz ustawić własny kolor: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Wiele kształtów z różnymi cieniami + +Jeśli potrzebujesz kilku kształtów, po prostu powtórz kroki tworzenia i konfiguracji. Pamiętaj, aby nadać każdemu kształtowi unikalną nazwę, jeśli zamierzasz odwoływać się do nich później. + +### Eksport do PDF z zachowanymi cieniami + +Aspose.Words zachowuje efekty cieni przy zapisywaniu do PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Typowe problemy + +| Objaw | Prawdopodobna przyczyna | Rozwiązanie | +|-------|--------------------------|-------------| +| Cień nie jest widoczny | `ShadowFormat.Visible` pozostawiono jako `false` | Ustaw na `true`. | +| Cień wygląda zbyt twardo | `Blur` ustawiono na `0` | Zwiększ `Blur` do 3–6. | +| Cień znika w PDF | Używana jest stara wersja Aspose.Words (< 22.9) | Zaktualizuj do najnowszej biblioteki. | + +--- + +## Podsumowanie + +Omówiliśmy **jak dodać cień do kształtu** przy użyciu Aspose.Words, od inicjalizacji dokumentu po precyzyjne dostosowanie rozmycia, odległości, kąta i **stosowanie przezroczystości cienia**. Pełny przykład pokazuje czyste, gotowe do produkcji podejście, które możesz dostosować do dowolnego kształtu lub układu dokumentu. + +Masz pytania dotyczące **create word document using aspose** w bardziej złożonych scenariuszach — np. tabel z cieniami lub dynamicznie generowanych kształtów? Dodaj komentarz poniżej lub sprawdź powiązane samouczki o obsłudze obrazów i formatowaniu akapitów w Aspose.Words. + +Miłego kodowania i ciesz się nadawaniem swoim dokumentom Word dodatkowego wykończenia wizualnego! + +--- + +![przykład dodawania cienia do kształtu](shadowed_shape.png "przykład dodawania cienia do kształtu") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/portuguese/words/_index.md b/content/portuguese/words/_index.md new file mode 100644 index 000000000..c889af05d --- /dev/null +++ b/content/portuguese/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "portuguese" +type: "family" +--- + +# Words Tutorials diff --git a/content/portuguese/words/net/_index.md b/content/portuguese/words/net/_index.md new file mode 100644 index 000000000..953f60354 --- /dev/null +++ b/content/portuguese/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "portuguese" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/portuguese/words/net/getting-started/_index.md b/content/portuguese/words/net/getting-started/_index.md new file mode 100644 index 000000000..9a564c9d3 --- /dev/null +++ b/content/portuguese/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "portuguese" +type: "category" +--- + +# Getting Started diff --git a/content/portuguese/words/net/getting-started/tutorial/_index.md b/content/portuguese/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..7b0585252 --- /dev/null +++ b/content/portuguese/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: pt +url: /portuguese/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Detectar Fontes Ausentes em Documentos Aspose.Words – Guia Completo em C# + +Já se perguntou como **detectar fontes ausentes** ao carregar um arquivo Word com Aspose.Words? No meu dia a dia, encontrei alguns PDFs que pareciam estranhos porque o documento original usava uma fonte que eu não tinha instalada. A boa notícia? Aspose.Words pode dizer exatamente quando substitui uma fonte, e você pode capturar essa informação com um simples callback de aviso. + +Neste tutorial, percorreremos um **exemplo completo e executável** que mostra como registrar cada substituição de fonte, por que o callback é importante e alguns truques extras para uma detecção robusta de fontes ausentes. Sem enrolação, apenas o código e o raciocínio que você precisa para fazê-lo funcionar hoje. + +--- + +## O que você aprenderá + +- Como implementar **Aspose.Words warning callback** para capturar eventos de substituição de fonte. +- Como configurar **LoadOptions C#** para que o callback seja invocado ao carregar um documento. +- Como verificar se a detecção de fontes ausentes realmente funcionou e como é a saída no console. +- Ajustes opcionais para lotes grandes ou ambientes sem interface gráfica. + +**Pré-requisitos** – Você precisa de uma versão recente do Aspose.Words para .NET (o código foi testado com 23.12), .NET 6 ou posterior, e um conhecimento básico de C#. Se você tem isso, está pronto para começar. + +--- + +## Detectar Fontes Ausentes com um Callback de Aviso + +O núcleo da solução é uma implementação de `IWarningCallback`. Aspose.Words dispara um objeto `WarningInfo` para muitas situações, mas nos interessamos apenas em `WarningType.FontSubstitution`. Vamos ver como conectar a isso. + +### Etapa 1: Criar um Coletor de Avisos de Fonte + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Por que isso importa*: Ao filtrar por `WarningType.FontSubstitution` evitamos ruído de avisos não relacionados (como recursos obsoletos). O `info.Description` já contém o nome da fonte original e a fonte de substituição usada, fornecendo um registro de auditoria claro. + +--- + +## Configurar LoadOptions para Usar o Callback + +Agora informamos ao Aspose.Words para usar nosso coletor ao carregar um arquivo. + +### Etapa 2: Configurar LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Por que isso importa*: `LoadOptions` é o único local onde você pode conectar o callback, senhas de criptografia e outros comportamentos de carregamento. Mantê‑lo separado do construtor `Document` torna o código reutilizável em vários arquivos. + +--- + +## Carregar o Documento e Capturar Fontes Ausentes + +Com o callback configurado, o próximo passo é simplesmente carregar o documento. + +### Etapa 3: Carregar seu DOCX (ou qualquer formato suportado) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Quando o construtor `Document` analisa o arquivo, qualquer fonte ausente aciona nosso `FontWarningCollector`. O console exibirá linhas como: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Essa linha é a evidência concreta de que **detectar fontes ausentes** funcionou. + +--- + +## Verificar a Saída – O que Esperar + +Execute o programa a partir de um terminal ou do Visual Studio. Se o documento fonte contiver uma fonte que você não tem instalada, verá ao menos uma linha “Font substituted”. Se o documento usar apenas fontes instaladas, o callback permanecerá silencioso e você verá apenas a mensagem “Document loaded successfully.”. + +**Dica**: Para confirmar, abra o arquivo Word no Microsoft Word e verifique a lista de fontes. Qualquer fonte que apareça em *Replace Fonts* sob o grupo *Home → Font* é candidata à substituição. + +--- + +## Avançado: Detectar Fontes Ausentes em Lote + +Frequentemente você precisa analisar dezenas de arquivos. O mesmo padrão escala bem: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Como o `FontWarningCollector` grava no console a cada invocação, você obterá um relatório por arquivo sem necessidade de infraestrutura extra. Para cenários de produção, talvez queira registrar em um arquivo ou banco de dados – basta substituir `Console.WriteLine` pelo seu logger preferido. + +--- + +## Armadilhas Comuns & Dicas Profissionais + +| Problema | Por que acontece | Solução | +|----------|------------------|---------| +| **Nenhum aviso aparece** | O documento realmente contém apenas fontes instaladas. | Verifique abrindo o arquivo no Word ou removendo deliberadamente uma fonte do seu sistema. | +| **Callback não chamado** | `LoadOptions.WarningCallback` nunca foi atribuído ou uma nova instância de `LoadOptions` foi usada posteriormente. | Mantenha um único objeto `LoadOptions` e reutilize‑o para cada carregamento. | +| **Muitos avisos não relacionados** | Você não filtrou por `WarningType.FontSubstitution`. | Adicione a verificação `if (info.Type == WarningType.FontSubstitution)` conforme mostrado. | +| **Desempenho reduzido em arquivos grandes** | O callback é executado em cada aviso, o que pode ser muitos em documentos grandes. | Desative outros tipos de aviso via `LoadOptions.WarningCallback` ou defina `LoadOptions.LoadFormat` para um tipo específico se você souber. | + +--- + +## Exemplo Completo Funcional (Pronto para Copiar‑Colar) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Saída esperada no console** (quando uma fonte ausente é encontrada): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Se nenhuma substituição ocorrer, você verá apenas a linha de sucesso. + +--- + +## Conclusão + +Agora você tem uma **solução completa e pronta para produção para detectar fontes ausentes** em qualquer documento processado pelo Aspose.Words. Ao aproveitar o **callback de aviso do Aspose.Words** e configurar **LoadOptions C#**, você pode registrar cada substituição de fonte, solucionar problemas de layout e garantir que seus PDFs mantenham a aparência pretendida. + +De um único arquivo a um lote massivo, o padrão permanece o mesmo — implemente `IWarningCallback`, conecte‑o ao `LoadOptions` e deixe o Aspose.Words fazer o trabalho pesado. + +Pronto para o próximo passo? Tente combinar isso com **incorporação de fontes** ou **famílias de fontes de fallback** para corrigir o problema automaticamente, ou explore a API **DocumentVisitor** para uma análise de conteúdo mais profunda. Feliz codificação, e que todas as suas fontes permaneçam onde você espera! + +--- + +![Detectar fontes ausentes em Aspose.Words – captura de tela da saída do console](https://example.com/images/detect-missing-fonts.png "saída do console de detecção de fontes ausentes") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/portuguese/words/net/images-and-shapes/_index.md b/content/portuguese/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..5d09244f2 --- /dev/null +++ b/content/portuguese/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "portuguese" +type: "category" +--- + +# Images And Shapes diff --git a/content/portuguese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/portuguese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..67f5c946d --- /dev/null +++ b/content/portuguese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2025-12-08 +description: Adicione sombra a formas rapidamente com Aspose.Words. Aprenda como criar + um documento Word usando Aspose, como adicionar sombra a formas e aplicar transparência + de sombra em C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: pt +og_description: Adicione sombra à forma em um arquivo Word usando Aspose.Words. Este + guia passo a passo mostra como criar um documento, adicionar uma forma e aplicar + transparência à sombra. +og_title: Adicionar sombra à forma – Tutorial Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Adicionar Sombra a uma Forma em um Documento Word – Guia Completo do Aspose.Words +url: /portuguese/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Adicionar Sombra a Forma – Guia Completo do Aspose.Words + +Já precisou **adicionar sombra a forma** em um arquivo Word, mas não sabia quais chamadas de API usar? Você não está sozinho. Muitos desenvolvedores se deparam com dificuldades ao tentar dar a um retângulo ou qualquer elemento de desenho uma sombra adequada, especialmente quando trabalham com Aspose.Words para .NET. + +Neste tutorial, percorreremos tudo o que você precisa saber: desde **criar um documento Word usando Aspose** até configurar a sombra, ajustar seu desfoque, distância, ângulo e até **aplicar transparência à sombra**. Ao final, você terá um programa C# pronto‑para‑executar que gera um arquivo `.docx` com um retângulo bem sombreado — sem necessidade de ajustes manuais no Word. + +--- + +## O que Você Vai Aprender + +- Como configurar um projeto Aspose.Words no Visual Studio. +- Os passos exatos para **criar documento Word usando Aspose** e inserir uma forma. +- **Como adicionar sombra a forma** com controle total sobre desfoque, distância, ângulo e transparência. +- Dicas para solucionar armadilhas comuns (por exemplo, licença ausente, unidades incorretas). +- Um exemplo completo de código copy‑and‑paste que você pode executar hoje. + +> **Pré‑requisitos:** .NET 6+ (ou .NET Framework 4.7.2+), uma licença válida do Aspose.Words (ou o teste gratuito) e familiaridade básica com C#. + +## Etapa 1 – Configure Seu Projeto e Adicione Aspose.Words + +Primeiro, abra o Visual Studio, crie um novo **Console App (.NET Core)** e adicione o pacote NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Dica profissional:** Se você tem um arquivo de licença (`Aspose.Words.lic`), copie‑o para a raiz do projeto e carregue‑o na inicialização. Isso evita a marca d'água que aparece no modo de avaliação gratuito. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Etapa 2 – Crie um Novo Documento em Branco + +Agora vamos realmente **criar documento Word usando Aspose**. Este objeto servirá como a tela para nossa forma. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +A classe `Document` é o ponto de entrada para tudo mais — parágrafos, seções e, claro, objetos de desenho. + +--- + +## Etapa 3 – Insira uma Forma Retângulo + +Com o documento pronto, podemos adicionar uma forma. Aqui escolhemos um retângulo simples, mas a mesma lógica funciona para círculos, linhas ou polígonos personalizados. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Por que uma forma?** No Aspose.Words, um objeto `Shape` pode conter texto, imagens ou simplesmente atuar como um elemento decorativo. Adicionar sombra a uma forma é muito mais fácil do que tentar manipular uma moldura de imagem. + +--- + +## Etapa 4 – Configure a Sombra (Adicionar Sombra à Forma) + +Este é o coração do tutorial — **como adicionar sombra a forma** e ajustar finamente sua aparência. A propriedade `ShadowFormat` lhe dá controle total. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### O Que Cada Propriedade Faz + +| Propriedade | Efeito | Valores Típicos | +|-------------|--------|-----------------| +| **Visible** | Ativa/desativa a sombra. | `true` / `false` | +| **Blur** | Suaviza as bordas da sombra. | `0` (duro) a `10` (muito suave) | +| **Distance** | Move a sombra para longe da forma. | `1`–`5` pontos é comum | +| **Angle** | Controla a direção do deslocamento. | `0`–`360` graus | +| **Transparency** | Torna a sombra parcialmente translúcida. | `0` (opaco) a `1` (invisível) | + +> **Caso extremo:** Se você definir `Transparency` como `1`, a sombra desaparece completamente — útil para alterná‑la programaticamente. + +--- + +## Etapa 5 – Adicione a Forma ao Documento + +Agora anexamos a forma ao primeiro parágrafo do corpo do documento. O Aspose cria automaticamente um parágrafo se não houver nenhum. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Se seu documento já contém conteúdo, você pode inserir a forma em qualquer nó usando `InsertAfter` ou `InsertBefore`. + +--- + +## Etapa 6 – Salve o Documento + +Finalmente, grave o arquivo no disco. Você pode escolher qualquer formato suportado (`.docx`, `.pdf`, `.odt`, etc.), mas para este tutorial usaremos o formato nativo do Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Abra o `ShadowedShape.docx` resultante no Microsoft Word e você verá um retângulo com uma sombra suave de 45 graus e 30 % de transparência — exatamente o que configuramos. + +--- + +## Exemplo Completo Funcional + +Abaixo está o programa **completo, pronto para copiar e colar** que incorpora todas as etapas acima. Salve‑o como `Program.cs` e execute com `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Saída esperada:** Um arquivo chamado `ShadowedShape.docx` contendo um único retângulo com uma sombra discreta, semi‑transparente, inclinada a 45°. + +--- + +## Variações e Dicas Avançadas + +### Alterando a Cor da Sombra + +Por padrão, a sombra herda a cor de preenchimento da forma, mas você pode definir uma cor personalizada: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Múltiplas Formas com Sombras Diferentes + +Se precisar de várias formas, basta repetir as etapas de criação e configuração. Lembre‑se de dar a cada forma um nome único se pretender referenciá‑las mais tarde. + +### Exportando para PDF com Sombras Preservadas + +O Aspose.Words preserva os efeitos de sombra ao salvar em PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Armadilhas Comuns + +| Sintoma | Causa Provável | Correção | +|---------|----------------|----------| +| Sombra não visível | `ShadowFormat.Visible` deixado como `false` | Defina como `true`. | +| Sombra parece muito dura | `Blur` definido como `0` | Aumente `Blur` para 3–6. | +| Sombra desaparece no PDF | Uso de uma versão antiga do Aspose.Words (< 22.9) | Atualize para a biblioteca mais recente. | + +--- + +## Conclusão + +Cobremos **como adicionar sombra a forma** usando Aspose.Words, desde a inicialização de um documento até o ajuste fino de desfoque, distância, ângulo e **aplicação de transparência à sombra**. O exemplo completo demonstra uma abordagem limpa e pronta para produção que você pode adaptar a qualquer forma ou layout de documento. + +Tem perguntas sobre **criar documento Word usando aspose** para cenários mais complexos — como tabelas com sombras ou formas geradas dinamicamente por dados? Deixe um comentário abaixo ou confira os tutoriais relacionados sobre manipulação de imagens e formatação de parágrafos no Aspose.Words. + +Feliz codificação, e aproveite para dar aos seus documentos Word aquele toque visual extra! + +--- + +![exemplo de adicionar sombra à forma](shadowed_shape.png "exemplo de adicionar sombra à forma") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/russian/words/_index.md b/content/russian/words/_index.md new file mode 100644 index 000000000..760ec0bee --- /dev/null +++ b/content/russian/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "russian" +type: "family" +--- + +# Words Tutorials diff --git a/content/russian/words/net/_index.md b/content/russian/words/net/_index.md new file mode 100644 index 000000000..9b4aa562b --- /dev/null +++ b/content/russian/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "russian" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/russian/words/net/getting-started/_index.md b/content/russian/words/net/getting-started/_index.md new file mode 100644 index 000000000..bf665f66f --- /dev/null +++ b/content/russian/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "russian" +type: "category" +--- + +# Getting Started diff --git a/content/russian/words/net/getting-started/tutorial/_index.md b/content/russian/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..e1e96e464 --- /dev/null +++ b/content/russian/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: ru +url: /russian/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Обнаружение отсутствующих шрифтов в документах Aspose.Words – Полное руководство на C# + +Вы когда‑нибудь задумывались, как **обнаружить отсутствующие шрифты** при загрузке Word‑файла с помощью Aspose.Words? В своей повседневной работе я сталкивался с несколькими PDF, которые выглядели некорректно, потому что исходный документ использовал шрифт, которого у меня не было установлено. Хорошая новость? Aspose.Words может точно сообщить, когда он заменяет шрифт, и вы можете захватить эту информацию с помощью простого обратного вызова предупреждения. + +В этом руководстве мы пройдём через **полный, готовый к запуску пример**, который покажет, как вести журнал каждой замены шрифта, почему обратный вызов важен, а также несколько дополнительных приёмов для надёжного обнаружения отсутствующих шрифтов. Без лишних слов — только код и объяснения, необходимые для работы уже сегодня. + +--- + +## Что вы узнаете + +- Как реализовать **Aspose.Words warning callback** для перехвата событий замены шрифтов. +- Как настроить **LoadOptions C#**, чтобы обратный вызов вызывался при загрузке документа. +- Как проверить, что обнаружение отсутствующего шрифта действительно сработало, и как выглядит вывод в консоли. +- Опциональные настройки для больших пакетов или безголовых (headless) сред. + +**Требования** – Вам нужна актуальная версия Aspose.Words для .NET (код тестировался с 23.12), .NET 6 или новее, а также базовые знания C#. Если всё это у вас есть, можно начинать. + +--- + +## Обнаружение отсутствующих шрифтов с помощью обратного вызова предупреждения + +Суть решения — реализация `IWarningCallback`. Aspose.Words генерирует объект `WarningInfo` во многих ситуациях, но нас интересует только `WarningType.FontSubstitution`. Давайте посмотрим, как подключиться к этому событию. + +### Шаг 1: Создать сборщик предупреждений о шрифтах + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Почему это важно*: Фильтруя по `WarningType.FontSubstitution`, мы избегаем захламления от нерелевантных предупреждений (например, устаревших функций). `info.Description` уже содержит оригинальное название шрифта и используемый запасной, предоставляя вам чёткую аудиторскую запись. + +--- + +## Настройка LoadOptions для использования обратного вызова + +Теперь мы укажем Aspose.Words использовать наш сборщик при загрузке файла. + +### Шаг 2: Настроить LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Почему это важно*: `LoadOptions` — единственное место, где можно подключить обратный вызов, пароли шифрования и другие параметры загрузки. Хранение его отдельно от конструктора `Document` делает код переиспользуемым для множества файлов. + +--- + +## Загрузка документа и захват отсутствующих шрифтов + +С подключённым обратным вызовом следующий шаг — просто загрузить документ. + +### Шаг 3: Загрузите ваш DOCX (или любой поддерживаемый формат) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Когда конструктор `Document` разбирает файл, любой отсутствующий шрифт активирует наш `FontWarningCollector`. В консоли появятся строки вроде: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Эта строка является конкретным доказательством того, что **обнаружение отсутствующих шрифтов** сработало. + +--- + +## Проверка вывода – чего ожидать + +Запустите программу из терминала или Visual Studio. Если исходный документ содержит шрифт, которого нет у вас в системе, вы увидите хотя бы одну строку «Font substituted». Если документ использует только установленные шрифты, обратный вызов будет молчать, и вы увидите лишь сообщение «Document loaded successfully.». + +**Подсказка**: Чтобы убедиться, откройте файл Word в Microsoft Word и посмотрите список шрифтов. Любой шрифт, который появляется в *Replace Fonts* в группе *Home → Font*, является кандидатом на замену. + +--- + +## Продвинутое: Обнаружение отсутствующих шрифтов пакетно + +Часто требуется просканировать десятки файлов. Та же схема легко масштабируется: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Поскольку `FontWarningCollector` пишет в консоль каждый раз, когда вызывается, вы получаете отчёт по каждому файлу без дополнительного кода. Для production‑сценариев вы можете логировать в файл или базу данных — просто замените `Console.WriteLine` на ваш предпочтительный логгер. + +--- + +## Распространённые ошибки и профессиональные советы + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| **Нет предупреждений** | Документ действительно содержит только установленные шрифты. | Проверьте, открыв файл в Word, или умышленно удалив шрифт из системы. | +| **Обратный вызов не вызывается** | `LoadOptions.WarningCallback` никогда не был назначен или позже использовался новый экземпляр `LoadOptions`. | Сохраните один объект `LoadOptions` и переиспользуйте его для каждой загрузки. | +| **Слишком много нерелевантных предупреждений** | Вы не фильтруете по `WarningType.FontSubstitution`. | Добавьте условие `if (info.Type == WarningType.FontSubstitution)` как показано. | +| **Снижение производительности на больших файлах** | Обратный вызов выполняется для каждого предупреждения, их может быть много в больших документах. | Отключите другие типы предупреждений через `LoadOptions.WarningCallback` или задайте `LoadOptions.LoadFormat` конкретный тип, если он известен. | + +--- + +## Полный рабочий пример (готовый к копированию) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Ожидаемый вывод в консоли** (когда обнаружен отсутствующий шрифт): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Если замена не происходит, вы увидите только строку успеха. + +--- + +## Заключение + +Теперь у вас есть **полный, готовый к продакшну способ обнаружения отсутствующих шрифтов** в любом документе, обрабатываемом Aspose.Words. Используя **Aspose.Words warning callback** и настраивая **LoadOptions C#**, вы можете вести журнал каждой замены шрифта, устранять проблемы с разметкой и гарантировать, что ваши PDF сохраняют задуманное оформление. + +От одного файла до огромного пакета шаблон остаётся тем же — реализуйте `IWarningCallback`, подключите его к `LoadOptions` и позвольте Aspose.Words выполнить тяжёлую работу. + +Готовы к следующему шагу? Попробуйте сочетать это с **font embedding** или **fallback font families**, чтобы автоматически исправлять проблему, либо изучите API **DocumentVisitor** для более глубокого анализа содержимого. Приятного кодинга, и пусть все ваши шрифты остаются там, где вы их ожидаете! + +--- + +![Обнаружение отсутствующих шрифтов в Aspose.Words – скриншот вывода в консоль](https://example.com/images/detect-missing-fonts.png "вывод обнаружения отсутствующих шрифтов в консоли") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/russian/words/net/images-and-shapes/_index.md b/content/russian/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..59c4a0418 --- /dev/null +++ b/content/russian/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "russian" +type: "category" +--- + +# Images And Shapes diff --git a/content/russian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/russian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..eb57efff8 --- /dev/null +++ b/content/russian/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Быстро добавьте тень к фигуре с помощью Aspose.Words. Узнайте, как создать + документ Word, используя Aspose, как добавить тень к фигуре и применить прозрачность + тени в C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: ru +og_description: Добавьте тень к фигуре в файле Word с помощью Aspose.Words. Это пошаговое + руководство показывает, как создать документ, добавить фигуру и применить прозрачность + тени. +og_title: Добавить тень к фигуре – учебник Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Добавить тень к фигуре в документе Word – Полное руководство Aspose.Words +url: /russian/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Добавление тени к фигуре – Полное руководство по Aspose.Words + +Когда‑то вам нужно **добавить тень к фигуре** в файле Word, но вы не знали, какие вызовы API использовать? Вы не одиноки. Многие разработчики сталкиваются с проблемой, пытаясь добавить правильную падающую тень к прямоугольнику или любому элементу рисунка, особенно при работе с Aspose.Words для .NET. + +В этом руководстве мы пройдём всё, что вам нужно знать: от **создания документа Word с помощью Aspose** до настройки тени, изменения её размытия, расстояния, угла и даже **применения прозрачности тени**. К концу вы получите готовую к запуску программу на C#, которая создаёт файл `.docx` с аккуратно затенённым прямоугольником — без ручных правок в Word. + +--- + +## Что вы узнаете + +- Как настроить проект Aspose.Words в Visual Studio. +- Точные шаги для **создания документа Word с помощью Aspose** и вставки фигуры. +- **Как добавить тень к фигуре** с полным контролем над размитием, расстоянием, углом и прозрачностью. +- Советы по устранению распространённых проблем (например, отсутствие лицензии, неверные единицы измерения). +- Полный пример кода, готовый к копированию и запуску сегодня. + +> **Требования:** .NET 6+ (или .NET Framework 4.7.2+), действующая лицензия Aspose.Words (или бесплатная пробная версия) и базовые знания C#. + +--- + +## Шаг 1 – Настройте проект и добавьте Aspose.Words + +Сначала откройте Visual Studio, создайте новое **Console App (.NET Core)** и добавьте пакет Aspose.Words через NuGet: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** Если у вас есть файл лицензии (`Aspose.Words.lic`), скопируйте его в корень проекта и загрузите при старте. Это избавит от водяного знака, появляющегося в режиме бесплатной оценки. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Шаг 2 – Создайте новый пустой документ + +Теперь мы действительно **создаём документ Word с помощью Aspose**. Этот объект будет служить холстом для нашей фигуры. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Класс `Document` — точка входа для всего остального: абзацев, секций и, конечно же, графических объектов. + +--- + +## Шаг 3 – Вставьте прямоугольную фигуру + +Когда документ готов, мы можем добавить фигуру. Здесь мы выбираем простой прямоугольник, но та же логика работает для кругов, линий или пользовательских полигонов. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Почему фигура?** В Aspose.Words объект `Shape` может содержать текст, изображения или просто выступать в качестве декоративного элемента. Добавление тени к фигуре гораздо проще, чем попытка изменить рамку изображения. + +--- + +## Шаг 4 – Настройте тень (Add Shadow to Shape) + +Это сердце руководства — **как добавить тень к фигуре** и точно настроить её внешний вид. Свойство `ShadowFormat` даёт вам полный контроль. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Что делает каждое свойство + +| Свойство | Эффект | Типичные значения | +|----------|--------|-------------------| +| **Visible** | Включает/выключает тень. | `true` / `false` | +| **Blur** | Смягчает края тени. | `0` (жёсткая) до `10` (очень мягкая) | +| **Distance** | Отодвигает тень от фигуры. | обычно `1`–`5` пунктов | +| **Angle** | Управляет направлением смещения. | `0`–`360` градусов | +| **Transparency** | Делает тень полупрозрачной. | `0` (непрозрачная) до `1` (невидимая) | + +> **Edge case:** Если установить `Transparency` в `1`, тень полностью исчезнет — удобно для программного переключения. + +--- + +## Шаг 5 – Добавьте фигуру в документ + +Теперь мы присоединяем фигуру к первому абзацу тела документа. Aspose автоматически создаёт абзац, если его нет. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Если ваш документ уже содержит контент, вы можете вставить фигуру в любой узел с помощью `InsertAfter` или `InsertBefore`. + +--- + +## Шаг 6 – Сохраните документ + +Наконец, запишите файл на диск. Вы можете выбрать любой поддерживаемый формат (`.docx`, `.pdf`, `.odt` и т.д.), но в этом руководстве мы останемся с нативным форматом Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Откройте полученный `ShadowedShape.docx` в Microsoft Word, и вы увидите прямоугольник с мягкой тенью под углом 45° и прозрачностью 30 % — именно так, как мы настроили. + +--- + +## Полный рабочий пример + +Ниже представлен **полный готовый к копированию** код, включающий все шаги выше. Сохраните его как `Program.cs` и запустите командой `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Ожидаемый результат:** Файл `ShadowedShape.docx`, содержащий один прямоугольник с лёгкой, полупрозрачной падающей тенью под углом 45°. + +--- + +## Вариации и продвинутые советы + +### Изменение цвета тени + +По умолчанию тень наследует цвет заливки фигуры, но вы можете задать собственный цвет: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Несколько фигур с разными тенями + +Если требуется несколько фигур, просто повторите шаги создания и настройки. Не забудьте дать каждой фигуре уникальное имя, если планируете обращаться к ним позже. + +### Экспорт в PDF с сохранёнными тенями + +Aspose.Words сохраняет эффекты тени при сохранении в PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Распространённые ошибки + +| Симптом | Вероятная причина | Решение | +|---------|-------------------|---------| +| Тень не видна | `ShadowFormat.Visible` оставлен `false` | Установите `true`. | +| Тень выглядит слишком жёстко | `Blur` установлен в `0` | Увеличьте `Blur` до 3–6. | +| Тень исчезает в PDF | Используется старая версия Aspose.Words (< 22.9) | Обновите библиотеку до последней версии. | + +--- + +## Заключение + +Мы рассмотрели **как добавить тень к фигуре** с помощью Aspose.Words, от инициализации документа до тонкой настройки размытия, расстояния, угла и **применения прозрачности тени**. Полный пример демонстрирует чистый, готовый к продакшену подход, который можно адаптировать под любую фигуру или макет документа. + +Есть вопросы о **создании документа Word с помощью Aspose** для более сложных сценариев — например, таблиц с тенями или динамически генерируемых фигур? Оставляйте комментарий ниже или смотрите связанные руководства по работе с изображениями и форматированием абзацев в Aspose.Words. + +Счастливого кодинга и приятного добавления визуального блеска вашим документам Word! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/spanish/words/_index.md b/content/spanish/words/_index.md new file mode 100644 index 000000000..b40c728f0 --- /dev/null +++ b/content/spanish/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "spanish" +type: "family" +--- + +# Words Tutorials diff --git a/content/spanish/words/net/_index.md b/content/spanish/words/net/_index.md new file mode 100644 index 000000000..2b22a3067 --- /dev/null +++ b/content/spanish/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "spanish" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/spanish/words/net/getting-started/_index.md b/content/spanish/words/net/getting-started/_index.md new file mode 100644 index 000000000..03ff966fe --- /dev/null +++ b/content/spanish/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "spanish" +type: "category" +--- + +# Getting Started diff --git a/content/spanish/words/net/getting-started/tutorial/_index.md b/content/spanish/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..ad201f25c --- /dev/null +++ b/content/spanish/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: es +url: /spanish/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Detectar fuentes faltantes en documentos Aspose.Words – Guía completa en C# + +¿Alguna vez te has preguntado cómo **detectar fuentes faltantes** al cargar un archivo Word con Aspose.Words? En mi trabajo diario, me he encontrado con algunos PDFs que se veían extraños porque el documento original usaba una fuente que no tenía instalada. ¿La buena noticia? Aspose.Words puede indicarte exactamente cuándo sustituye una fuente, y puedes capturar esa información con una simple devolución de llamada de advertencia. + +En este tutorial repasaremos un **ejemplo completo y ejecutable** que muestra cómo registrar cada sustitución de fuente, por qué es importante la devolución de llamada y un par de trucos adicionales para una detección robusta de fuentes faltantes. Sin rodeos, solo el código y el razonamiento que necesitas para hacerlo funcionar hoy. + +--- + +## Lo que aprenderás + +- Cómo implementar **Aspose.Words warning callback** para capturar eventos de sustitución de fuentes. +- Cómo configurar **LoadOptions C#** para que la devolución de llamada se invoque al cargar un documento. +- Cómo verificar que la detección de fuentes faltantes realmente funcionó y cómo se ve la salida en la consola. +- Ajustes opcionales para lotes grandes o entornos sin interfaz. + +**Prerequisitos** – Necesitas una versión reciente de Aspose.Words para .NET (el código se probó con la 23.12), .NET 6 o posterior, y un conocimiento básico de C#. Si los tienes, estás listo para comenzar. + +--- + +## Detectar fuentes faltantes con una devolución de llamada de advertencia + +El núcleo de la solución es una implementación de `IWarningCallback`. Aspose.Words genera un objeto `WarningInfo` para muchas situaciones, pero solo nos interesan los de tipo `WarningType.FontSubstitution`. Veamos cómo engancharlo. + +### Paso 1: Crear un recolector de advertencias de fuentes + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Por qué es importante*: Al filtrar por `WarningType.FontSubstitution` evitamos el desorden de advertencias no relacionadas (como características obsoletas). `info.Description` ya contiene el nombre de la fuente original y la fuente de reemplazo utilizada, proporcionándote una pista de auditoría clara. + +--- + +## Configurar LoadOptions para usar la devolución de llamada + +Ahora le indicamos a Aspose.Words que use nuestro recolector al cargar un archivo. + +### Paso 2: Configurar LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Por qué es importante*: `LoadOptions` es el único lugar donde puedes conectar la devolución de llamada, contraseñas de cifrado y otros comportamientos de carga. Mantenerlo separado del constructor `Document` hace que el código sea reutilizable en muchos archivos. + +--- + +## Cargar el documento y capturar fuentes faltantes + +Con la devolución de llamada configurada, el siguiente paso es simplemente cargar el documento. + +### Paso 3: Cargar tu DOCX (o cualquier formato compatible) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Cuando el constructor `Document` analiza el archivo, cualquier fuente faltante activa nuestro `FontWarningCollector`. La consola mostrará líneas como: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Esa línea es la evidencia concreta de que **detect missing fonts** funcionó. + +--- + +## Verificar la salida – Qué esperar + +Ejecuta el programa desde una terminal o Visual Studio. Si el documento fuente contiene una fuente que no tienes instalada, verás al menos una línea “Font substituted”. Si el documento usa solo fuentes instaladas, la devolución de llamada permanecerá silenciosa y solo obtendrás el mensaje “Document loaded successfully.”. + +**Consejo**: Para comprobarlo, abre el archivo Word en Microsoft Word y revisa la lista de fuentes. Cualquier fuente que aparezca en *Replace Fonts* bajo el grupo *Home → Font* es una candidata para sustitución. + +--- + +## Avanzado: Detectar fuentes faltantes en lote + +A menudo necesitas escanear docenas de archivos. El mismo patrón escala sin problemas: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Debido a que `FontWarningCollector` escribe en la consola cada vez que se invoca, obtendrás un informe por archivo sin tuberías adicionales. Para escenarios de producción podrías registrar en un archivo o base de datos – simplemente reemplaza `Console.WriteLine` por tu registrador preferido. + +--- + +## Errores comunes y consejos profesionales + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **No aparecen advertencias** | El documento en realidad solo contiene fuentes instaladas. | Verifícalo abriendo el archivo en Word o eliminando deliberadamente una fuente de tu sistema. | +| **Devolución de llamada no invocada** | `LoadOptions.WarningCallback` nunca se asignó o se utilizó una nueva instancia de `LoadOptions` más tarde. | Mantén un único objeto `LoadOptions` y reutilízalo para cada carga. | +| **Demasiadas advertencias no relacionadas** | No filtraste por `WarningType.FontSubstitution`. | Añade la condición `if (info.Type == WarningType.FontSubstitution)` como se muestra. | +| **Ralentización del rendimiento en archivos grandes** | La devolución de llamada se ejecuta en cada advertencia, lo que puede ser muchas en documentos grandes. | Desactiva otros tipos de advertencia mediante `LoadOptions.WarningCallback` o establece `LoadOptions.LoadFormat` a un tipo específico si lo conoces. | + +--- + +## Ejemplo completo funcional (listo para copiar y pegar) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Salida esperada en la consola** (cuando se encuentra una fuente faltante): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Si no ocurre sustitución, solo verás la línea de éxito. + +--- + +## Conclusión + +Ahora tienes una **solución completa y lista para producción para detectar fuentes faltantes** en cualquier documento procesado por Aspose.Words. Aprovechando la **devolución de llamada de advertencia de Aspose.Words** y configurando **LoadOptions C#**, puedes registrar cada sustitución de fuente, solucionar problemas de y garantizar que tus PDFs mantengan el aspecto y la sensación previstos. + +Desde un solo archivo hasta un lote masivo, el patrón sigue siendo el mismo: implementa `IWarningCallback`, conéctalo a `LoadOptions` y deja que Aspose.Words haga el trabajo pesado. + +¿Listo para el siguiente paso? Prueba combinar esto con **font embedding** o **fallback font families** para corregir automáticamente el problema, o explora la API **DocumentVisitor** para un análisis de contenido más profundo. ¡Feliz codificación, y que todas tus fuentes permanezcan donde esperas! + +--- + +![Detectar fuentes faltantes en Aspose.Words – captura de pantalla de la salida de consola](https://example.com/images/detect-missing-fonts.png "salida de consola de detección de fuentes faltantes") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/spanish/words/net/images-and-shapes/_index.md b/content/spanish/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..ef7e04356 --- /dev/null +++ b/content/spanish/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "spanish" +type: "category" +--- + +# Images And Shapes diff --git a/content/spanish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/spanish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..82490915e --- /dev/null +++ b/content/spanish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2025-12-08 +description: Agrega sombra a una forma rápidamente con Aspose.Words. Aprende cómo + crear un documento Word usando Aspose, cómo agregar sombra a una forma y aplicar + transparencia de sombra en C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: es +og_description: Agrega sombra a una forma en un archivo de Word usando Aspose.Words. + Esta guía paso a paso muestra cómo crear un documento, añadir una forma y aplicar + transparencia a la sombra. +og_title: Añadir sombra a la forma – Tutorial de Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Agregar sombra a una forma en un documento de Word – Guía completa de Aspose.Words +url: /spanish/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Agregar sombra a forma – Guía completa de Aspose.Words + +¿Alguna vez necesitaste **agregar sombra a forma** en un archivo Word pero no estabas seguro de qué llamadas a la API usar? No estás solo. Muchos desarrolladores se topan con un obstáculo cuando intentan por primera vez dar a un rectángulo o cualquier elemento de dibujo una sombra adecuada, especialmente cuando trabajan con Aspose.Words para .NET. + +En este tutorial repasaremos todo lo que necesitas saber: desde **crear un documento Word usando Aspose** hasta configurar la sombra, ajustar su desenfoque, distancia, ángulo e incluso **aplicar transparencia a la sombra**. Al final tendrás un programa C# listo para ejecutar que produce un archivo `.docx` con un rectángulo bien sombreado—sin necesidad de manipular manualmente Word. + +--- + +## Lo que aprenderás + +- Cómo configurar un proyecto Aspose.Words en Visual Studio. +- Los pasos exactos para **crear documento Word usando Aspose** e insertar una forma. +- **Cómo agregar sombra a una forma** con control total sobre desenfoque, distancia, ángulo y transparencia. +- Consejos para solucionar problemas comunes (p. ej., licencia faltante, unidades incorrectas). +- Un ejemplo completo de código copy‑and‑paste que puedes ejecutar hoy. + +> **Requisitos previos:** .NET 6+ (o .NET Framework 4.7.2+), una licencia válida de Aspose.Words (o la prueba gratuita), y una familiaridad básica con C#. + +## Paso 1 – Configura tu proyecto y agrega Aspose.Words + +Primero lo primero. Abre Visual Studio, crea una nueva **Aplicación de consola (.NET Core)** y agrega el paquete NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Consejo profesional:** Si tienes un archivo de licencia (`Aspose.Words.lic`), cópialo al directorio raíz del proyecto y cárgalo al iniciar. Esto evita la marca de agua que aparece en el modo de evaluación gratuito. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## Paso 2 – Crear un nuevo documento en blanco + +Ahora realmente **creamos un documento Word usando Aspose**. Este objeto servirá como lienzo para nuestra forma. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +La clase `Document` es el punto de entrada para todo lo demás—párrafos, secciones y, por supuesto, objetos de dibujo. + +## Paso 3 – Insertar una forma rectangular + +Con el documento listo, podemos agregar una forma. Aquí elegimos un rectángulo simple, pero la misma lógica funciona para círculos, líneas o polígonos personalizados. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **¿Por qué una forma?** En Aspose.Words un objeto `Shape` puede contener texto, imágenes o simplemente actuar como un elemento decorativo. Agregar una sombra a una forma es mucho más fácil que intentar manipular un marco de imagen. + +## Paso 4 – Configurar la sombra (Agregar sombra a forma) + +Este es el corazón del tutorial—**cómo agregar sombra a una forma** y afinar su apariencia. La propiedad `ShadowFormat` te brinda control total. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Qué hace cada propiedad + +| Propiedad | Efecto | Valores típicos | +|----------|--------|----------------| +| **Visible** | Activa o desactiva la sombra. | `true` / `false` | +| **Blur** | Suaviza los bordes de la sombra. | `0` (duro) a `10` (muy suave) | +| **Distance** | Aleja la sombra de la forma. | `1`–`5` puntos es común | +| **Angle** | Controla la dirección del desplazamiento. | `0`–`360` grados | +| **Transparency** | Hace que la sombra sea parcialmente translúcida. | `0` (opaco) a `1` (invisible) | + +> **Caso límite:** Si estableces `Transparency` a `1`, la sombra desaparece por completo—útil para alternarla programáticamente. + +## Paso 5 – Añadir la forma al documento + +Ahora adjuntamos la forma al primer párrafo del cuerpo del documento. Aspose crea automáticamente un párrafo si no existe. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Si tu documento ya contiene contenido, puedes insertar la forma en cualquier nodo usando `InsertAfter` o `InsertBefore`. + +## Paso 6 – Guardar el documento + +Finalmente, escribe el archivo en disco. Puedes elegir cualquier formato compatible (`.docx`, `.pdf`, `.odt`, etc.), pero para este tutorial nos quedaremos con el formato nativo de Word. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Abre el `ShadowedShape.docx` resultante en Microsoft Word, y verás un rectángulo con una sombra suave de 45 grados que es 30 % transparente—exactamente lo que configuramos. + +## Ejemplo completo funcional + +A continuación está el programa **completo, listo para copiar y pegar** que incorpora todos los pasos anteriores. Guárdalo como `Program.cs` y ejecútalo con `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Salida esperada:** Un archivo llamado `ShadowedShape.docx` que contiene un solo rectángulo con una sombra discreta, semi‑transparente, inclinada a 45°. + +## Variaciones y consejos avanzados + +### Cambiar el color de la sombra + +Por defecto la sombra hereda el color de relleno de la forma, pero puedes establecer un color personalizado: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Múltiples formas con sombras diferentes + +Si necesitas varias formas, simplemente repite los pasos de creación y configuración. Recuerda dar a cada forma un nombre único si planeas referenciarlas más tarde. + +### Exportar a PDF con sombras preservadas + +Aspose.Words conserva los efectos de sombra al guardar en PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Problemas comunes + +| Síntoma | Causa probable | Solución | +|---------|----------------|----------| +| La sombra no es visible | `ShadowFormat.Visible` dejado como `false` | Establecer a `true`. | +| La sombra parece demasiado dura | `Blur` establecido en `0` | Incrementar `Blur` a 3–6. | +| La sombra desaparece en PDF | Uso de una versión antigua de Aspose.Words (< 22.9) | Actualizar a la última biblioteca. | + +## Conclusión + +Hemos cubierto **cómo agregar sombra a una forma** usando Aspose.Words, desde la inicialización de un documento hasta afinar desenfoque, distancia, ángulo y **aplicar transparencia a la sombra**. El ejemplo completo muestra un enfoque limpio y listo para producción que puedes adaptar a cualquier forma o diseño de documento. + +¿Tienes preguntas sobre **crear documento Word usando Aspose** para escenarios más complejos—como tablas con sombras o formas impulsadas por datos dinámicos? Deja un comentario abajo o revisa los tutoriales relacionados sobre manejo de imágenes y formato de párrafos en Aspose.Words. + +¡Feliz codificación, y disfruta dando a tus documentos Word ese toque visual extra! + +--- + +![ejemplo de agregar sombra a forma](shadowed_shape.png "ejemplo de agregar sombra a forma") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/swedish/words/_index.md b/content/swedish/words/_index.md new file mode 100644 index 000000000..ba92f08b5 --- /dev/null +++ b/content/swedish/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "swedish" +type: "family" +--- + +# Words Tutorials diff --git a/content/swedish/words/net/_index.md b/content/swedish/words/net/_index.md new file mode 100644 index 000000000..504c96d10 --- /dev/null +++ b/content/swedish/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "swedish" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/swedish/words/net/getting-started/_index.md b/content/swedish/words/net/getting-started/_index.md new file mode 100644 index 000000000..3ac09db86 --- /dev/null +++ b/content/swedish/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "swedish" +type: "category" +--- + +# Getting Started diff --git a/content/swedish/words/net/getting-started/tutorial/_index.md b/content/swedish/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..62afebf05 --- /dev/null +++ b/content/swedish/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: sv +url: /swedish/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Upptäck saknade teckensnitt i Aspose.Words‑dokument – Komplett C#‑guide + +Har du någonsin funderat på hur du **upptäcker saknade teckensnitt** när du laddar en Word‑fil med Aspose.Words? I mitt dagliga arbete har jag stött på några PDF‑filer som såg felaktiga ut eftersom originaldokumentet använde ett teckensnitt jag inte hade installerat. Den goda nyheten? Aspose.Words kan berätta exakt när det ersätter ett teckensnitt, och du kan fånga den informationen med ett enkelt varnings‑callback. + +I den här handledningen går vi igenom ett **komplett, körbart exempel** som visar hur du loggar varje teckensnittsersättning, varför callbacken är viktig, och ett par extra knep för robust upptäckt av saknade teckensnitt. Inga onödiga utsvävningar, bara koden och resonemanget du behöver för att få det att fungera idag. + +--- + +## Vad du kommer att lära dig + +- Hur du implementerar **Aspose.Words varnings‑callback** för att fånga teckensnittsersättnings‑händelser. +- Hur du konfigurerar **LoadOptions C#** så att callbacken anropas när ett dokument laddas. +- Hur du verifierar att upptäckten av saknade teckensnitt verkligen fungerade, och hur konsolutdata ser ut. +- Valfria justeringar för stora batcher eller huvudlösa miljöer. + +**Förkunskaper** – Du behöver en aktuell version av Aspose.Words för .NET (koden testades med 23.12), .NET 6 eller senare, och en grundläggande förståelse för C#. Om du har detta är du redo att köra. + +--- + +## Upptäck saknade teckensnitt med en varnings‑callback + +Kärnan i lösningen är en implementation av `IWarningCallback`. Aspose.Words avfyrar ett `WarningInfo`‑objekt för många situationer, men vi är bara intresserade av `WarningType.FontSubstitution`. Låt oss se hur vi kopplar in det. + +### Steg 1: Skapa en teckensnitt‑varningssamling + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Varför detta är viktigt*: Genom att filtrera på `WarningType.FontSubstitution` undviker vi skräp från orelaterade varningar (som föråldrade funktioner). `info.Description` innehåller redan det ursprungliga teckensnittets namn och ersättningen, vilket ger dig ett tydligt revisionsspår. + +--- + +## Konfigurera LoadOptions för att använda callbacken + +Nu säger vi åt Aspose.Words att använda vår samlare när den laddar en fil. + +### Steg 2: Ställ in LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Varför detta är viktigt*: `LoadOptions` är den enda platsen där du kan ansluta callbacken, krypteringslösenord och andra laddningsbeteenden. Att hålla den separerad från `Document`‑konstruktorn gör koden återanvändbar för många filer. + +--- + +## Ladda dokumentet och fånga saknade teckensnitt + +Med callbacken på plats är nästa steg helt enkelt att ladda dokumentet. + +### Steg 3: Ladda ditt DOCX (eller något annat stödd format) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +När `Document`‑konstruktorn parsar filen triggas vår `FontWarningCollector` för varje saknat teckensnitt. Konsolen visar rader som: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Den raden är det konkreta beviset på att **upptäcka saknade teckensnitt** fungerade. + +--- + +## Verifiera utdata – Vad du kan förvänta dig + +Kör programmet från en terminal eller Visual Studio. Om källdokumentet innehåller ett teckensnitt du inte har installerat kommer du att se minst en rad med “Font substituted”. Om dokumentet bara använder installerade teckensnitt förblir callbacken tyst och du får bara meddelandet “Document loaded successfully.” + +**Tips**: För att dubbelkolla, öppna Word‑filen i Microsoft Word och titta på teckensnittlistan. Alla teckensnitt som visas i *Replace Fonts* under *Home → Font*‑gruppen är kandidater för ersättning. + +--- + +## Avancerat: Upptäck saknade teckensnitt i bulk + +Ofta behöver du skanna dussintals filer. Samma mönster skalar bra: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Eftersom `FontWarningCollector` skriver till konsolen varje gång den anropas får du en per‑fil‑rapport utan extra kod. För produktionsscenarier kanske du vill logga till en fil eller en databas – byt helt enkelt ut `Console.WriteLine` mot din föredragna logger. + +--- + +## Vanliga fallgropar & Pro‑tips + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| **Inga varningar visas** | Dokumentet innehåller faktiskt bara installerade teckensnitt. | Verifiera genom att öppna filen i Word eller genom att medvetet ta bort ett teckensnitt från ditt system. | +| **Callbacken anropas inte** | `LoadOptions.WarningCallback` tilldelades aldrig eller en ny `LoadOptions`‑instans användes senare. | Behåll ett enda `LoadOptions`‑objekt och återanvänd det för varje laddning. | +| **För många orelaterade varningar** | Du filtrerade inte på `WarningType.FontSubstitution`. | Lägg till villkoret `if (info.Type == WarningType.FontSubstitution)` som visas. | +| **Prestandaförsämring på stora filer** | Callbacken körs för varje varning, vilket kan vara många för stora dokument. | Inaktivera andra varningstyper via `LoadOptions.WarningCallback` eller sätt `LoadOptions.LoadFormat` till en specifik typ om du vet den. | + +--- + +## Fullt fungerande exempel (Kopiera‑klistra‑klart) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Förväntad konsolutdata** (när ett saknat teckensnitt påträffas): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Om ingen ersättning sker ser du bara framgångsmeddelandet. + +--- + +## Slutsats + +Du har nu ett **komplett, produktionsklart sätt att upptäcka saknade teckensnitt** i vilket dokument som helst som bearbetas av Aspose.Words. Genom att utnyttja **Aspose.Words varnings‑callback** och konfigurera **LoadOptions C#**, kan du logga varje teckensnittsersättning, felsöka layout‑problem och säkerställa att dina PDF‑filer behåller det avsedda utseendet. + +Från en enskild fil till en massiv batch förblir mönstret detsamma – implementera `IWarningCallback`, anslut den till `LoadOptions`, och låt Aspose.Words göra det tunga lyftet. + +Redo för nästa steg? Prova att kombinera detta med **font embedding** eller **fallback font families** för att automatiskt åtgärda problemet, eller utforska **DocumentVisitor**‑API:t för djupare innehållsanalys. Lycka till med kodningen, och må alla dina teckensnitt stanna där du förväntar dig dem! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/swedish/words/net/images-and-shapes/_index.md b/content/swedish/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..6c4c04672 --- /dev/null +++ b/content/swedish/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "swedish" +type: "category" +--- + +# Images And Shapes diff --git a/content/swedish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/swedish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..62b06134d --- /dev/null +++ b/content/swedish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,250 @@ +--- +category: general +date: 2025-12-08 +description: Lägg snabbt till skugga på en form med Aspose.Words. Lär dig hur du skapar + ett Word‑dokument med Aspose, hur du lägger till skugga på en form och hur du applicerar + skuggtransparens i C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: sv +og_description: Lägg till skugga på en form i en Word‑fil med Aspose.Words. Denna + steg‑för‑steg‑guide visar hur du skapar ett dokument, lägger till en form och applicerar + skuggans transparens. +og_title: Lägg till skugga på form – Aspose.Words C#-handledning +tags: +- Aspose.Words +- C# +- Word Automation +title: Lägg till skugga på form i ett Word-dokument – Komplett Aspose.Words-guide +url: /swedish/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Lägg till skugga på form – Komplett Aspose.Words‑guide + +Har du någonsin behövt **lägga till skugga på form** i en Word‑fil men varit osäker på vilka API‑anrop du ska använda? Du är inte ensam. Många utvecklare stöter på problem när de för första gången försöker ge en rektangel eller något ritnings‑element en riktig drop‑shadow, särskilt när de arbetar med Aspose.Words för .NET. + +I den här handledningen går vi igenom allt du behöver veta: från **skapa ett Word‑dokument med Aspose** till att konfigurera skuggan, justera dess suddighet, avstånd, vinkel och till och med **tillämpa skuggegenskaper för transparens**. I slutet har du ett färdigt C#‑program som producerar en `.docx`‑fil med en snyggt skuggad rektangel—utan manuellt krångel i Word. + +--- + +## Vad du kommer att lära dig + +- Hur du sätter upp ett Aspose.Words‑projekt i Visual Studio. +- De exakta stegen för att **skapa Word‑dokument med Aspose** och infoga en form. +- **Hur du lägger till skugga på form** med full kontroll över suddighet, avstånd, vinkel och transparens. +- Tips för felsökning av vanliga fallgropar (t.ex. saknad licens, felaktiga enheter). +- Ett komplett, kopiera‑och‑klistra kodexempel som du kan köra idag. + +> **Förutsättningar:** .NET 6+ (eller .NET Framework 4.7.2+), en giltig Aspose.Words‑licens (eller gratis provversion), och en grundläggande kunskap om C#. + +## Steg 1 – Ställ in ditt projekt och lägg till Aspose.Words + +Först och främst. Öppna Visual Studio, skapa en ny **Console App (.NET Core)** och lägg till Aspose.Words‑NuGet‑paketet: + +```bash +dotnet add package Aspose.Words +``` + +> **Proffstips:** Om du har en licensfil (`Aspose.Words.lic`), kopiera den till projektets rot och ladda den vid start. Detta undviker vattenstämpeln som visas i gratisutvärderingsläget. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## Steg 2 – Skapa ett nytt tomt dokument + +Nu **skapar vi Word‑dokument med Aspose**. Detta objekt kommer att fungera som en duk för vår form. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Klassen `Document` är ingångspunkten för allt annat—paragrafer, sektioner och naturligtvis ritobjekt. + +## Steg 3 – Infoga en rektangel‑form + +När dokumentet är klart kan vi lägga till en form. Här väljer vi en enkel rektangel, men samma logik fungerar för cirklar, linjer eller anpassade polygoner. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Varför en form?** I Aspose.Words kan ett `Shape`‑objekt innehålla text, bilder eller bara fungera som ett dekorativt element. Att lägga till en skugga på en form är mycket enklare än att försöka manipulera en bildram. + +## Steg 4 – Konfigurera skuggan (Lägg till skugga på form) + +Detta är hjärtat i handledningen—**hur du lägger till skugga på form** och finjusterar dess utseende. `ShadowFormat`‑egenskapen ger dig full kontroll. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Vad varje egenskap gör + +| Egenskap | Effekt | Vanliga värden | +|----------|--------|----------------| +| **Visible** | Slår på/av skuggan. | `true` / `false` | +| **Blur** | Mjukgör skuggans kanter. | `0` (hård) till `10` (mycket mjuk) | +| **Distance** | Flyttar skuggan bort från formen. | `1`–`5` punkter är vanligt | +| **Angle** | Styr riktningen på förskjutningen. | `0`–`360` grader | +| **Transparency** | Gör skuggan delvis genomskinlig. | `0` (opak) till `1` (osynlig) | + +> **Edge case:** Om du sätter `Transparency` till `1` försvinner skuggan helt—användbart för att slå på/av den programatiskt. + +## Steg 5 – Lägg till formen i dokumentet + +Vi fäster nu formen till det första stycket i dokumentets kropp. Aspose skapar automatiskt ett stycke om inget finns. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Om ditt dokument redan innehåller innehåll kan du infoga formen vid vilken nod som helst med `InsertAfter` eller `InsertBefore`. + +## Steg 6 – Spara dokumentet + +Slutligen skriver du filen till disk. Du kan välja vilket som helst av de stödjade formaten (`.docx`, `.pdf`, `.odt`, etc.), men för den här handledningen håller vi oss till det inhemska Word‑formatet. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Öppna den resulterande `ShadowedShape.docx` i Microsoft Word, så ser du en rektangel med en mjuk, 45‑gradig skugga som är 30 % transparent—precis som vi konfigurerade. + +## Fullt fungerande exempel + +Nedan är det **kompletta, kopiera‑och‑klistra‑klara** programmet som innehåller alla stegen ovan. Spara det som `Program.cs` och kör det med `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Förväntad output:** En fil med namnet `ShadowedShape.docx` som innehåller en enda rektangel med en subtil, semi‑transparent drop‑shadow vinklad 45°. + +## Variationer & avancerade tips + +### Ändra skuggfärg + +Som standard ärver skuggan formens fyllningsfärg, men du kan ange en egen färg: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Flera former med olika skuggor + +Om du behöver flera former, upprepa bara skapande‑ och konfigurationsstegen. Kom ihåg att ge varje form ett unikt namn om du planerar att referera till dem senare. + +### Exportera till PDF med bevarade skuggor + +Aspose.Words bevarar skuggeffekter när du sparar till PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Vanliga fallgropar + +| Symptom | Trolig orsak | Åtgärd | +|---------|--------------|--------| +| Skugga syns inte | `ShadowFormat.Visible` lämnades som `false` | Sätt till `true`. | +| Skuggan ser för hård ut | `Blur` satt till `0` | Öka `Blur` till 3–6. | +| Skuggan försvinner i PDF | Använder en gammal Aspose.Words‑version (< 22.9) | Uppgradera till det senaste biblioteket. | + +## Slutsats + +Vi har gått igenom **hur du lägger till skugga på form** med Aspose.Words, från att initiera ett dokument till att finjustera suddighet, avstånd, vinkel och **tillämpa skuggegenskaper för transparens**. Det fullständiga exemplet visar ett rent, produktionsklart tillvägagångssätt som du kan anpassa till vilken form eller dokumentlayout som helst. + +Har du frågor om **create word document using aspose** för mer komplexa scenarier—som tabeller med skuggor eller dynamiskt data‑drivna former? Lämna en kommentar nedanför eller kolla in de relaterade handledningarna om Aspose.Words bildhantering och styckeformatering. + +Lycka till med kodningen, och njut av att ge dina Word‑dokument den extra visuella poleringen! + +--- + +![add shadow to shape example](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/thai/words/_index.md b/content/thai/words/_index.md new file mode 100644 index 000000000..2380e8a10 --- /dev/null +++ b/content/thai/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "thai" +type: "family" +--- + +# Words Tutorials diff --git a/content/thai/words/net/_index.md b/content/thai/words/net/_index.md new file mode 100644 index 000000000..54a579d8e --- /dev/null +++ b/content/thai/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "thai" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/thai/words/net/getting-started/_index.md b/content/thai/words/net/getting-started/_index.md new file mode 100644 index 000000000..779ce6c91 --- /dev/null +++ b/content/thai/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "thai" +type: "category" +--- + +# Getting Started diff --git a/content/thai/words/net/getting-started/tutorial/_index.md b/content/thai/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..a489e06c9 --- /dev/null +++ b/content/thai/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: th +url: /thai/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# ตรวจจับฟอนต์ที่หายไปในเอกสาร Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ + +เคยสงสัยไหมว่า **ตรวจจับฟอนต์ที่หายไป** อย่างไรเมื่อคุณโหลดไฟล์ Word ด้วย Aspose.Words? ในงานประจำวันของฉัน ฉันเคยเจอ PDF บางไฟล์ที่ดูแปลกเพราะเอกสารต้นฉบับใช้ฟอนต์ที่ฉันไม่ได้ติดตั้ง ข่าวดีคือ Aspose.Words สามารถบอกคุณได้อย่างแม่นยำเมื่อมันทำการแทนที่ฟอนต์ และคุณสามารถจับข้อมูลนั้นด้วย callback คำเตือนแบบง่าย + +ในบทแนะนำนี้เราจะพาคุณผ่าน **ตัวอย่างที่สมบูรณ์และสามารถรันได้** ที่แสดงวิธีบันทึกการแทนที่ฟอนต์ทุกครั้ง เหตุผลที่ callback มีความสำคัญ และเทคนิคเพิ่มเติมสองสามอย่างสำหรับการตรวจจับฟอนต์ที่หายไปอย่างมั่นคง ไม่ได้มีเนื้อหาเกินความจำเป็น เพียงโค้ดและเหตุผลที่คุณต้องการเพื่อให้ทำงานได้ทันที + +--- + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีการทำ **Aspose.Words warning callback** เพื่อดักจับเหตุการณ์การแทนที่ฟอนต์ +- วิธีการกำหนดค่า **LoadOptions C#** เพื่อให้ callback ถูกเรียกขณะโหลดเอกสาร +- วิธีตรวจสอบว่าการตรวจจับฟอนต์ที่หายไปทำงานจริงหรือไม่ และผลลัพธ์ที่แสดงในคอนโซลเป็นอย่างไร +- การปรับแต่งเพิ่มเติมสำหรับการประมวลผลเป็นกลุ่มใหญ่หรือสภาพแวดล้อมแบบ headless + +**ข้อกำหนดเบื้องต้น** – คุณต้องมี Aspose.Words for .NET รุ่นล่าสุด (โค้ดทดสอบกับเวอร์ชัน 23.12) , .NET 6 หรือใหม่กว่า และความเข้าใจพื้นฐานเกี่ยวกับ C# หากคุณมีทั้งหมดนี้ คุณก็พร้อมเริ่มใช้งานแล้ว + +--- + +## ตรวจจับฟอนต์ที่หายไปด้วย Warning Callback + +หัวใจของวิธีแก้คือการทำงานของ `IWarningCallback` Aspose.Words จะส่งอ็อบเจ็กต์ `WarningInfo` สำหรับหลายสถานการณ์ แต่เราสนใจเฉพาะ `WarningType.FontSubstitution` เท่านั้น มาดูกันว่าจะเชื่อมต่ออย่างไร + +### ขั้นตอน 1: สร้าง Font‑Warning Collector + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*เหตุผล*: การกรองด้วย `WarningType.FontSubstitution` จะช่วยหลีกเลี่ยงคำเตือนที่ไม่เกี่ยวข้อง (เช่นฟีเจอร์ที่เลิกใช้) `info.Description` มีชื่อฟอนต์ต้นฉบับและฟอนต์สำรองที่ใช้แล้ว ทำให้คุณได้บันทึกข้อมูลที่ชัดเจน + +--- + +## กำหนดค่า LoadOptions เพื่อใช้ Callback + +ต่อไปเราจะบอก Aspose.Words ให้ใช้ collector ของเราขณะโหลดไฟล์ + +### ขั้นตอน 2: ตั้งค่า LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*เหตุผล*: `LoadOptions` เป็นจุดเดียวที่คุณสามารถต่อ callback, รหัสผ่านการเข้ารหัส, และพฤติกรรมการโหลดอื่น ๆ การแยกออกจากคอนสตรัคเตอร์ `Document` ทำให้โค้ดสามารถนำไปใช้ซ้ำได้หลายไฟล์ + +--- + +## โหลดเอกสารและจับฟอนต์ที่หายไป + +เมื่อเชื่อมต่อ callback แล้ว ขั้นตอนต่อไปคือการโหลดเอกสาร + +### ขั้นตอน 3: โหลดไฟล์ DOCX (หรือรูปแบบที่สนับสนุนอื่น) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +ขณะคอนสตรัคเตอร์ `Document` วิเคราะห์ไฟล์ ฟอนต์ที่หายไปใด ๆ จะทำให้ `FontWarningCollector` ของเราถูกเรียก คอนโซลจะแสดงบรรทัดเช่น: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +บรรทัดนั้นเป็นหลักฐานที่ชัดเจนว่า **การตรวจจับฟอนต์ที่หายไป** ทำงานสำเร็จ + +--- + +## ตรวจสอบผลลัพธ์ – สิ่งที่ควรคาดหวัง + +เรียกโปรแกรมจากเทอร์มินัลหรือ Visual Studio หากเอกสารต้นทางมีฟอนต์ที่คุณไม่ได้ติดตั้ง คุณจะเห็นอย่างน้อยหนึ่งบรรทัด “Font substituted” หากเอกสารใช้ฟอนต์ที่ติดตั้งอยู่แล้ว callback จะเงียบและคุณจะเห็นข้อความ “Document loaded successfully.” เท่านั้น + +**เคล็ดลับ**: เพื่อตรวจสอบอีกครั้ง ให้เปิดไฟล์ Word ด้วย Microsoft Word แล้วดูรายการฟอนต์ ฟอนต์ใดที่ปรากฏใน *Replace Fonts* ภายใต้กลุ่ม *Home → Font* จะเป็นผู้สมัครสำหรับการแทนที่ + +--- + +## ขั้นสูง: ตรวจจับฟอนต์ที่หายไปเป็นกลุ่มใหญ่ + +บ่อยครั้งที่คุณต้องสแกนหลายสิบไฟล์ รูปแบบเดียวกันสามารถขยายได้อย่างราบรื่น: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +เพราะ `FontWarningCollector` เขียนผลลัพธ์ลงคอนโซลทุกครั้งที่ถูกเรียก คุณจะได้รายงานต่อไฟล์โดยไม่ต้องเขียนโค้ดเพิ่มเติม สำหรับสถานการณ์การผลิตคุณอาจต้องการบันทึกลงไฟล์หรือฐานข้อมูล – เพียงเปลี่ยน `Console.WriteLine` เป็น logger ที่คุณต้องการ + +--- + +## ข้อผิดพลาดทั่วไป & เคล็ดลับระดับมืออาชีพ + +| ปัญหา | สาเหตุ | วิธีแก้ | +|-------|--------|--------| +| **ไม่มีคำเตือนใดปรากฏ** | เอกสารจริง ๆ มีเพียงฟอนต์ที่ติดตั้งอยู่ | ตรวจสอบโดยเปิดไฟล์ใน Word หรือโดยการลบฟอนต์ออกจากระบบโดยเจตนา | +| **Callback ไม่ถูกเรียก** | `LoadOptions.WarningCallback` ไม่ได้ถูกกำหนดหรือมีการใช้ `LoadOptions` ตัวใหม่หลังจากนั้น | ใช้วัตถุ `LoadOptions` ตัวเดียวและนำไปใช้ซ้ำทุกครั้งที่โหลด | +| **คำเตือนที่ไม่เกี่ยวข้องมากเกินไป** | คุณไม่ได้กรองด้วย `WarningType.FontSubstitution` | เพิ่มเงื่อนไข `if (info.Type == WarningType.FontSubstitution)` ตามที่แสดง | +| **ประสิทธิภาพช้าบนไฟล์ขนาดใหญ่** | Callback ทำงานกับทุกคำเตือน ซึ่งอาจมีจำนวนมากในเอกสารใหญ่ | ปิดคำเตือนประเภทอื่นผ่าน `LoadOptions.WarningCallback` หรือกำหนด `LoadOptions.LoadFormat` ให้เป็นประเภทที่คุณรู้ล่วงหน้า | + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (พร้อมคัดลอก‑วาง) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**ผลลัพธ์คอนโซลที่คาดหวัง** (เมื่อพบฟอนต์ที่หายไป): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +หากไม่มีการแทนที่ใดเกิดขึ้น คุณจะเห็นเพียงบรรทัดแสดงความสำเร็จเท่านั้น + +--- + +## สรุป + +คุณมี **วิธีตรวจจับฟอนต์ที่หายไปในเอกสารใด ๆ ที่ประมวลผลด้วย Aspose.Words** อย่างครบถ้วนและพร้อมใช้งานในระดับการผลิตแล้ว โดยใช้ **Aspose.Words warning callback** และกำหนด **LoadOptions C#** คุณสามารถบันทึกการแทนที่ฟอนต์ทุกครั้ง แก้ไขปัญหาเลย์เอาต์ และทำให้ PDF ของคุณคงรูปลักษณ์ตามที่ต้องการ + +ไม่ว่าจะเป็นไฟล์เดียวหรือหลายร้อยไฟล์ รูปแบบก็เหมือนเดิม – implement `IWarningCallback`, plug it into `LoadOptions`, แล้วให้ Aspose.Words จัดการส่วนที่เหลือ + +พร้อมก้าวต่อไปหรือยัง? ลองผสานวิธีนี้กับ **font embedding** หรือ **fallback font families** เพื่อแก้ปัญหาโดยอัตโนมัติ หรือสำรวจ API **DocumentVisitor** เพื่อวิเคราะห์เนื้อหาอย่างละเอียด ขอให้เขียนโค้ดสนุกและฟอนต์ของคุณอยู่ในที่ที่คาดหวัง! + +--- + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/thai/words/net/images-and-shapes/_index.md b/content/thai/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..469b5e2b2 --- /dev/null +++ b/content/thai/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "thai" +type: "category" +--- + +# Images And Shapes diff --git a/content/thai/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/thai/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..db6bce4f2 --- /dev/null +++ b/content/thai/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2025-12-08 +description: เพิ่มเงาให้กับรูปทรงอย่างรวดเร็วด้วย Aspose.Words. เรียนรู้วิธีสร้างเอกสาร + Word ด้วย Aspose, วิธีเพิ่มเงาให้รูปทรง, และการใช้ความโปร่งใสของเงาใน C# +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: th +og_description: เพิ่มเงาให้กับรูปร่างในไฟล์ Word ด้วย Aspose.Words คู่มือแบบทีละขั้นตอนนี้แสดงวิธีสร้างเอกสาร, + เพิ่มรูปร่าง, และกำหนดความโปร่งใสของเงา. +og_title: เพิ่มเงาให้รูปร่าง – บทแนะนำ Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: เพิ่มเงาให้รูปทรงในเอกสาร Word – คู่มือ Aspose.Words ฉบับสมบูรณ์ +url: /thai/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# เพิ่มเงาให้รูปทรง – คู่มือ Aspose.Words ฉบับสมบูรณ์ + +เคยต้องการ **เพิ่มเงาให้รูปทรง** ในไฟล์ Word แต่ไม่แน่ใจว่าจะใช้ API ใด? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจออุปสรรคเมื่อลองเพิ่มเงาตกให้กับสี่เหลี่ยมหรือองค์ประกอบการวาดใด ๆ ครั้งแรก โดยเฉพาะเมื่อทำงานกับ Aspose.Words สำหรับ .NET + +ในบทแนะนำนี้เราจะพาคุณผ่านทุกอย่างที่ต้องรู้: ตั้งแต่ **การสร้างเอกสาร Word ด้วย Aspose** ไปจนถึงการกำหนดค่าเงา ปรับความเบลอ ระยะห่าง มุม และแม้กระทั่ง **การใช้ความโปร่งใสของเงา**. เมื่อจบคุณจะมีโปรแกรม C# ที่พร้อมรันซึ่งสร้างไฟล์ `.docx` ที่มีสี่เหลี่ยมที่มีเงาอย่างสวยงาม—ไม่ต้องแก้ไขด้วยตนเองใน Word + +--- + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีตั้งค่าโครงการ Aspose.Words ใน Visual Studio. +- ขั้นตอนที่แน่นอนในการ **สร้างเอกสาร Word ด้วย Aspose** และแทรกรูปทรง. +- **วิธีเพิ่มเงาให้รูปทรง** พร้อมการควบคุมเต็มที่ของความเบลอ ระยะห่าง มุม และความโปร่งใส. +- เคล็ดลับการแก้ไขปัญหาที่พบบ่อย (เช่น ไฟล์ใบอนุญาตหาย, หน่วยไม่ถูกต้อง). +- ตัวอย่างโค้ดที่ครบถ้วนพร้อมคัดลอก‑วางที่คุณสามารถรันได้วันนี้. + +> **ข้อกำหนดเบื้องต้น:** .NET 6+ (หรือ .NET Framework 4.7.2+), ใบอนุญาต Aspose.Words ที่ถูกต้อง (หรือทดลองใช้ฟรี), และความคุ้นเคยพื้นฐานกับ C#. + +## ขั้นตอนที่ 1 – ตั้งค่าโครงการของคุณและเพิ่ม Aspose.Words + +สิ่งแรกที่ต้องทำ เปิด Visual Studio, สร้าง **Console App (.NET Core)** ใหม่, และเพิ่มแพคเกจ NuGet ของ Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **เคล็ดลับ:** หากคุณมีไฟล์ใบอนุญาต (`Aspose.Words.lic`), คัดลอกไปยังโฟลเดอร์รากของโครงการและโหลดในตอนเริ่มต้น. วิธีนี้จะหลีกเลี่ยงลายน้ำที่ปรากฏในโหมดทดลองใช้ฟรี. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +## ขั้นตอนที่ 2 – สร้างเอกสารเปล่าใหม่ + +ตอนนี้เราจริง ๆ **สร้างเอกสาร Word ด้วย Aspose**. วัตถุนี้จะทำหน้าที่เป็นผ้าใบสำหรับรูปทรงของเรา. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` class เป็นจุดเริ่มต้นสำหรับทุกอย่างอื่น—ย่อหน้า, ส่วน, และแน่นอนว่าอ็อบเจกต์การวาด. + +## ขั้นตอนที่ 3 – แทรกรูปทรงสี่เหลี่ยม + +เมื่อเอกสารพร้อม เราสามารถเพิ่มรูปทรงได้ ที่นี่เราเลือกสี่เหลี่ยมง่าย ๆ แต่ตรรกะเดียวกันใช้ได้กับวงกลม, เส้น, หรือรูปหลายเหลี่ยมที่กำหนดเอง. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +**ทำไมต้องใช้รูปทรง?** ใน Aspose.Words อ็อบเจกต์ `Shape` สามารถเก็บข้อความ, รูปภาพ, หรือทำหน้าที่เป็นองค์ประกอบตกแต่ง. การเพิ่มเงาให้รูปทรงง่ายกว่าการจัดการกับกรอบรูปภาพมาก. + +## ขั้นตอนที่ 4 – กำหนดค่าเงา (เพิ่มเงาให้รูปทรง) + +นี่คือหัวใจของบทแนะนำ—**วิธีเพิ่มเงาให้รูปทรง** และปรับแต่งลักษณะอย่างละเอียด. คุณสมบัติ `ShadowFormat` ให้คุณควบคุมเต็มที่. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### สิ่งที่แต่ละคุณสมบัติทำ + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | เปิดหรือปิดเงา. | `true` / `false`| **Blur** | ทำให้ขอบเงานุ่มนวล. | `0` (hard) to `10` (very soft) | +| **Distance** | ย้ายเงาออกจากรูปทรง. | `1`–`5` points is common | +| **Angle** | ควบคุมทิศทางของการเลื่อน. | `0`–`360` degrees | +| **Transparency** | ทำให้เงาโปร่งแสงบางส่วน. | `0` (opaque) to `1` (invisible) | + +**กรณีขอบ:** หากคุณตั้งค่า `Transparency` เป็น `1` เงาจะหายไปทั้งหมด—มีประโยชน์สำหรับการสลับเงาโดยโปรแกรม. + +## ขั้นตอนที่ 5 – เพิ่มรูปทรงลงในเอกสาร + +ตอนนี้เราจะผูกรูปทรงกับย่อหน้าแรกของส่วนเนื้อหาเอกสาร. Aspose จะสร้างย่อหน้าโดยอัตโนมัติหากไม่มี. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +หากเอกสารของคุณมีเนื้อหาอยู่แล้ว คุณสามารถแทรกรูปทรงที่โหนดใดก็ได้โดยใช้ `InsertAfter` หรือ `InsertBefore`. + +## ขั้นตอนที่ 6 – บันทึกเอกสาร + +สุดท้าย เขียนไฟล์ลงดิสก์. คุณสามารถเลือกฟอร์แมตที่รองรับใดก็ได้ (`.docx`, `.pdf`, `.odt`, เป็นต้น) แต่สำหรับบทแนะนำนี้เราจะใช้ฟอร์แมต Word ดั้งเดิม. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +เปิดไฟล์ `ShadowedShape.docx` ที่สร้างขึ้นใน Microsoft Word, คุณจะเห็นสี่เหลี่ยมที่มีเงานุ่ม, มุม 45°, ความโปร่งใส 30 %—ตรงกับที่เราตั้งค่า. + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรม **ครบถ้วนพร้อมคัดลอก‑วาง** ที่รวมทุกขั้นตอนข้างต้น. บันทึกเป็น `Program.cs` แล้วรันด้วย `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง:** ไฟล์ชื่อ `ShadowedShape.docx` ที่มีสี่เหลี่ยมเดียวที่มีเงาตกแบบครึ่งโปร่งใสและมุม 45°. + +## ความแปรผันและเคล็ดลับขั้นสูง + +### การเปลี่ยนสีเงา + +โดยค่าเริ่มต้นเงาจะสืบทอดสีเติมของรูปทรง, แต่คุณสามารถตั้งค่าสีกำหนดเองได้: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### หลายรูปทรงพร้อมเงาต่างกัน + +หากต้องการหลายรูปทรง เพียงทำซ้ำขั้นตอนการสร้างและกำหนดค่า. จำไว้ว่าต้องตั้งชื่อแต่ละรูปทรงให้เป็นเอกลักษณ์หากต้องการอ้างอิงในภายหลัง. + +### การส่งออกเป็น PDF พร้อมรักษาเงา + +Aspose.Words จะรักษาเอฟเฟกต์เงาเมื่อบันทึกเป็น PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### ปัญหาที่พบบ่อย + +| อาการ | สาเหตุที่เป็นไปได้ | วิธีแก้ | +|-------|-------------------|---------| +| เงาไม่แสดง | `ShadowFormat.Visible` ถูกทิ้งไว้เป็น `false` | ตั้งค่าเป็น `true | +| เงาดูแข็งเกินไป | `Blur` ตั้งเป็น `0` | เพิ่มค่า `Blur` เป็น 3–6. | +| เงาหายไปใน PDF | ใช้เวอร์ชันเก่าของ Aspose.Words (< 22.9) | อัปเกรดเป็นไลบรารีล่าสุด. | + +## สรุป + +เราได้ครอบคลุม **วิธีเพิ่มเงาให้รูปทรง** ด้วย Aspose.Words ตั้งแต่การเริ่มต้นเอกสารจนถึงการปรับแต่งความเบลอ, ระยะ, มุม, และ **การใช้ความโปร่งใสของเงา**. ตัวอย่างเต็มแสดงวิธีที่สะอาดและพร้อมใช้งานในผลิตภัณฑ์ที่คุณสามารถปรับใช้กับรูปทรงหรือเลย์เอาต์เอกสารใดก็ได้. + +มีคำถามเกี่ยวกับ **การสร้างเอกสาร Word ด้วย Aspose** สำหรับสถานการณ์ที่ซับซ้อนกว่า—เช่น ตารางที่มีเงาหรือรูปทรงที่สร้างจากข้อมูลแบบไดนามิก? แสดงความคิดเห็นด้านล่างหรือดูบทแนะนำที่เกี่ยวข้องเกี่ยวกับการจัดการภาพและการจัดรูปแบบย่อหน้าใน Aspose.Words. + +ขอให้เขียนโค้ดอย่างสนุกสนานและเพลิดเพลินกับการเพิ่มความสวยงามให้กับเอกสาร Word ของคุณ! + +--- + +![ตัวอย่างการเพิ่มเงาให้รูปทรง](shadowed_shape.png "ตัวอย่างการเพิ่มเงาให้รูปทรง") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/turkish/words/_index.md b/content/turkish/words/_index.md new file mode 100644 index 000000000..46de91e38 --- /dev/null +++ b/content/turkish/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "turkish" +type: "family" +--- + +# Words Tutorials diff --git a/content/turkish/words/net/_index.md b/content/turkish/words/net/_index.md new file mode 100644 index 000000000..a5c6c2de3 --- /dev/null +++ b/content/turkish/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "turkish" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/turkish/words/net/getting-started/_index.md b/content/turkish/words/net/getting-started/_index.md new file mode 100644 index 000000000..d5d6963ca --- /dev/null +++ b/content/turkish/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "turkish" +type: "category" +--- + +# Getting Started diff --git a/content/turkish/words/net/getting-started/tutorial/_index.md b/content/turkish/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..9a0e44167 --- /dev/null +++ b/content/turkish/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: tr +url: /turkish/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Aspose.Words Belgelerinde Eksik Yazı Tiplerini Algılamak – Tam C# Rehberi + +Aspose.Words ile bir Word dosyasını yüklediğinizde **eksik yazı tiplerini nasıl algılayacağınızı** hiç merak ettiniz mi? Günlük işimde, orijinal belge yüklü olmayan bir yazı tipi kullandığı için birkaç PDF'nin hatalı göründüğü durumlarla karşılaştım. İyi haber? Aspose.Words, bir yazı tipini ne zaman değiştirdiğini tam olarak size söyleyebilir ve bu bilgiyi basit bir uyarı geri çağrısı (warning callback) ile yakalayabilirsiniz. + +Bu öğreticide, **tam ve çalıştırılabilir bir örnek** üzerinden her yazı tipi değişimini nasıl kaydedeceğinizi, geri çağrının neden önemli olduğunu ve sağlam eksik‑yazı tipi algılaması için birkaç ekstra ipucunu göstereceğiz. Gereksiz ayrıntı yok, sadece ihtiyacınız olan kod ve mantık, bugün çalıştırmanız için. + +--- + +## Öğrenecekleriniz + +- **Aspose.Words warning callback**'i uygulayarak yazı tipi değişim olaylarını yakalama. +- **LoadOptions C#**'ı yapılandırarak belge yüklenirken geri çağrının tetiklenmesini sağlama. +- Eksik‑yazı tipi algılamasının gerçekten çalıştığını doğrulama ve konsol çıktısının nasıl göründüğünü anlama. +- Büyük toplular veya başsız (headless) ortamlar için isteğe bağlı ayarlamalar. + +**Önkoşullar** – .NET 6 veya üzeri, temel C# bilgisi ve Aspose.Words for .NET'in (kod 23.12 ile test edilmiştir) güncel bir sürümüne ihtiyacınız var. Bu koşullara sahipseniz, hemen başlayabilirsiniz. + +--- + +## Eksik Yazı Tiplerini Uyarı Geri Çağrısı ile Algılamak + +Çözümün kalbi, `IWarningCallback` uygulamasıdır. Aspose.Words birçok durum için bir `WarningInfo` nesnesi yayar, ancak biz sadece `WarningType.FontSubstitution` ile ilgileniyoruz. Şimdi bunu nasıl bağlayacağımıza bakalım. + +### Adım 1: Bir Font‑Uyarı Toplayıcı Oluşturun + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Bu neden önemli*: `WarningType.FontSubstitution` üzerinden filtreleme yaparak alakasız uyarılardan (örneğin kullanımdan kaldırılmış özellikler) kaynaklanan gürültüyü önlüyoruz. `info.Description` zaten orijinal yazı tipi adını ve kullanılan yedek yazı tipini içeriyor, bu da size net bir denetim izi sağlıyor. + +--- + +## Geri Çağrıyı Kullanmak İçin LoadOptions'ı Yapılandırın + +Şimdi Aspose.Words'e dosya yüklerken toplama aracımızı kullanmasını söyleyelim. + +### Adım 2: LoadOptions'ı Ayarlayın + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Bu neden önemli*: `LoadOptions`, geri çağrıyı, şifreleme parolalarını ve diğer yükleme davranışlarını takabileceğiniz tek yerdir. `Document` yapıcıdan ayrı tutmak, kodun birçok dosya için yeniden kullanılabilir olmasını sağlar. + +--- + +## Belgeyi Yükleyin ve Eksik Yazı Tiplerini Yakalayın + +Geri çağrı bağlandıktan sonra tek yapmanız gereken belgeyi yüklemek. + +### Adım 3: DOCX'inizi (veya desteklenen herhangi bir formatı) Yükleyin + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +`Document` yapıcı dosyayı ayrıştırdığında, eksik bir yazı tipi bizim `FontWarningCollector`'ımızı tetikler. Konsolda aşağıdaki gibi satırlar göreceksiniz: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Bu satır, **eksik yazı tiplerini algılamanın** çalıştığının somut kanıtıdır. + +--- + +## Çıktıyı Doğrulama – Ne Beklemelisiniz + +Programı bir terminalden ya da Visual Studio'dan çalıştırın. Kaynak belge yüklü olmayan bir yazı tipi içeriyorsa, en az bir “Font substituted” satırı göreceksiniz. Belge yalnızca yüklü yazı tipleri kullanıyorsa, geri çağrı sessiz kalır ve sadece “Document loaded successfully.” mesajını alırsınız. + +**İpucu**: Çift kontrol için Word dosyasını Microsoft Word'de açın ve yazı tipi listesini inceleyin. *Home → Font* grubundaki *Replace Fonts* altında görünen herhangi bir yazı tipi, değişim adayıdır. + +--- + +## İleri Seviye: Toplu Olarak Eksik Yazı Tiplerini Algılamak + +Çoğu zaman onlarca dosyayı taramanız gerekir. Aynı desen büyük ölçekte de sorunsuz çalışır: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +`FontWarningCollector` her tetiklendiğinde konsola yazdığından, ekstra bir altyapı eklemeden dosya başına rapor alırsınız. Üretim senaryolarında çıktıyı bir dosyaya ya da veritabanına yönlendirmek isteyebilirsiniz – sadece `Console.WriteLine` ifadesini tercih ettiğiniz logger ile değiştirin. + +--- + +## Yaygın Tuzaklar & Profesyonel İpuçları + +| Sorun | Neden Oluşur | Çözüm | +|-------|--------------|-------| +| **Uyarı çıkmaz** | Belge aslında yalnızca yüklü yazı tiplerini içeriyor. | Word'de dosyayı açarak ya da sisteminizden kasıtlı olarak bir yazı tipini kaldırarak doğrulayın. | +| **Geri çağrı çalışmaz** | `LoadOptions.WarningCallback` hiç atanmadı ya da daha sonra yeni bir `LoadOptions` örneği kullanıldı. | Tek bir `LoadOptions` nesnesi tutun ve her yüklemede aynı nesneyi yeniden kullanın. | +| **Alakalı olmayan çok fazla uyarı** | `WarningType.FontSubstitution` ile filtreleme yapmadınız. | Gösterildiği gibi `if (info.Type == WarningType.FontSubstitution)` koşulunu ekleyin. | +| **Büyük dosyalarda performans düşüşü** | Geri çağrı her uyarıda çalışıyor, büyük belgelerde bu sayısı artabiliyor. | Diğer uyarı türlerini `LoadOptions.WarningCallback` üzerinden devre dışı bırakın veya dosyanın tipini biliyorsanız `LoadOptions.LoadFormat`'ı belirli bir tipe ayarlayın. | + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Beklenen konsol çıktısı** (eksik bir yazı tipiyle karşılaşıldığında): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Değişim gerçekleşmezse sadece başarı satırını göreceksiniz. + +--- + +## Sonuç + +Artık **herhangi bir belgeyi Aspose.Words ile işlerken eksik yazı tiplerini algılamak** için tam, üretim‑hazır bir yönteme sahipsiniz. **Aspose.Words warning callback**'i ve **LoadOptions C#** yapılandırmasını kullanarak her yazı tipi değişimini kaydedebilir, düzen sorunlarını tespit edebilir ve PDF'lerinizin istenen görünümünü koruyabilirsiniz. + +Tek bir dosyadan büyük bir toplu işleme kadar desen aynı kalır—`IWarningCallback`'i uygulayın, `LoadOptions`'a takın ve Aspose.Words'ün ağır işini yapmasına izin verin. + +Bir sonraki adım için ne yapacaksınız? Bu yöntemi **yazı tipi gömme** veya **yedek yazı tipi aileleri** ile birleştirerek sorunu otomatik olarak çözebilir, ya da daha derin içerik analizi için **DocumentVisitor** API'sini keşfedebilirsiniz. Kodlamanın tadını çıkarın, ve tüm yazı tipleriniz her zaman beklendiği gibi olsun! + +--- + +![Aspose.Words'ta eksik yazı tiplerini algılamak – konsol çıktısı ekran görüntüsü](https://example.com/images/detect-missing-fonts.png "eksik yazı tiplerini algılayan konsol çıktısı") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/turkish/words/net/images-and-shapes/_index.md b/content/turkish/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..aca5ed64c --- /dev/null +++ b/content/turkish/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "turkish" +type: "category" +--- + +# Images And Shapes diff --git a/content/turkish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/turkish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..bc0d5385e --- /dev/null +++ b/content/turkish/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Aspose.Words ile şekle hızlıca gölge ekleyin. Aspose kullanarak Word + belgesi oluşturmayı, şekle gölge eklemeyi ve C#'ta gölge şeffaflığını uygulamayı + öğrenin. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: tr +og_description: Word dosyasında bir şekle gölge ekleyin Aspose.Words kullanarak. Bu + adım adım kılavuz, bir belge oluşturmayı, bir şekil eklemeyi ve gölge şeffaflığını + uygulamayı gösterir. +og_title: Şekle Gölge Ekle – Aspose.Words C# Öğreticisi +tags: +- Aspose.Words +- C# +- Word Automation +title: Word Belgesindeki Şekle Gölge Ekle – Tam Aspose.Words Rehberi +url: /turkish/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Şekle Gölge Ekle – Tam Aspose.Words Rehberi + +Bir Word dosyasında **şekle gölge ekleme** ihtiyacı duyup hangi API çağrılarını kullanacağınızdan emin olmadınız mı? Yalnız değilsiniz. Birçok geliştirici, özellikle Aspose.Words for .NET ile çalışırken, bir dikdörtgen ya da herhangi bir çizim öğesine doğru bir drop‑shadow vermeye çalıştıklarında bir engelle karşılaşıyor. + +Bu öğreticide, bilmeniz gereken her şeyi adım adım inceleyeceğiz: **Aspose kullanarak Word belgesi oluşturma**'dan gölgeyi yapılandırmaya, bulanıklığını, mesafesini, açısını ayarlamaya ve hatta **gölge şeffaflığını uygulamaya** kadar. Sonunda, Word'de manuel ayarlama yapmadan güzel gölgeli bir dikdörtgen üreten, çalıştırmaya hazır bir C# programına sahip olacaksınız. + +--- + +## Öğrenecekleriniz + +- Visual Studio'da bir Aspose.Words projesi nasıl kurulur. +- Aspose kullanarak **Word belgesi oluşturma** ve bir şekil ekleme adımları. +- **Şekle gölge ekleme** ve bulanıklık, mesafe, açı ve şeffaflık üzerinde tam kontrol. +- Yaygın sorunları giderme ipuçları (ör. eksik lisans, hatalı birimler). +- Bugün çalıştırabileceğiniz eksiksiz, kopyala‑yapıştır kod örneği. + +> **Önkoşullar:** .NET 6+ (veya .NET Framework 4.7.2+), geçerli bir Aspose.Words lisansı (veya ücretsiz deneme), ve C# hakkında temel bir aşinalık. + +--- + +## Adım 1 – Projenizi Kurun ve Aspose.Words Ekleyin + +İlk olarak, Visual Studio'yu açın, yeni bir **Console App (.NET Core)** oluşturun ve Aspose.Words NuGet paketini ekleyin: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro ipucu:** Eğer bir lisans dosyanız (`Aspose.Words.lic`) varsa, proje kök dizinine kopyalayın ve başlangıçta yükleyin. Bu, ücretsiz değerlendirme modunda görülen filigranı önler. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Adım 2 – Yeni Boş Bir Belge Oluşturun + +Şimdi gerçekten **Aspose kullanarak Word belgesi oluşturuyoruz**. Bu nesne, şeklimiz için bir tuval görevi görecek. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` sınıfı, diğer her şeyin—paragraflar, bölümler ve tabii ki çizim nesneleri—giriş noktasıdır. + +--- + +## Adım 3 – Bir Dikdörtgen Şekil Ekleyin + +Belge hazır olduğunda bir şekil ekleyebiliriz. Burada basit bir dikdörtgen seçiyoruz, ancak aynı mantık daireler, çizgiler veya özel çokgenler için de çalışır. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Neden bir şekil?** Aspose.Words'ta bir `Shape` nesnesi metin, resim tutabilir ya da sadece dekoratif bir öğe olarak işlev görebilir. Bir şekle gölge eklemek, bir resim çerçevesini manipüle etmeye çalışmaktan çok daha kolaydır. + +--- + +## Adım 4 – Gölgeyi Yapılandırın (Şekle Gölge Ekle) + +Bu, öğreticinin kalbidir—**şekle gölge ekleme** ve görünümünü ince ayarlama. `ShadowFormat` özelliği size tam kontrol sağlar. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Her Özelliğin Ne İş Yaptığı + +| Property | Effect | Typical Values | +|----------|--------|----------------| +| **Visible** | Gölgeyi açar/kapatır. | `true` / `false` | +| **Blur** | Gölge kenarlarını yumuşatır. | `0` (sert) to `10` (çok yumuşak) | +| **Distance** | Gölgeyi şekilden uzaklaştırır. | `1`–`5` nokta yaygındır | +| **Angle** | Ofset yönünü kontrol eder. | `0`–`360` derece | +| **Transparency** | Gölgeyi kısmen şeffaf yapar. | `0` (opak) to `1` (görünmez) | + +> **Köşe durumu:** `Transparency` değerini `1` olarak ayarlarsanız, gölge tamamen kaybolur—programatik olarak geçiş yapmak için kullanışlıdır. + +--- + +## Adım 5 – Şekli Belgeye Ekleyin + +Şimdi şekli belgenin gövdesindeki ilk paragrafa ekliyoruz. Aspose, eğer paragraf yoksa otomatik olarak bir paragraf oluşturur. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Belgenizde zaten içerik varsa, şekli `InsertAfter` veya `InsertBefore` kullanarak istediğiniz herhangi bir düğüme ekleyebilirsiniz. + +--- + +## Adım 6 – Belgeyi Kaydedin + +Son olarak, dosyayı diske yazın. Herhangi bir desteklenen formatı (`.docx`, `.pdf`, `.odt`, vb.) seçebilirsiniz, ancak bu öğreticide yerel Word formatını kullanacağız. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Oluşan `ShadowedShape.docx` dosyasını Microsoft Word'de açın ve 30 % şeffaf, 45 derece yumuşak bir gölgeye sahip bir dikdörtgen göreceksiniz—tam olarak yapılandırdığımız gibi. + +--- + +## Tam Çalışan Örnek + +Aşağıda, yukarıdaki tüm adımları içeren **tam, kopyala‑yapıştır hazır** program bulunmaktadır. `Program.cs` olarak kaydedin ve `dotnet run` ile çalıştırın. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Beklenen çıktı:** `ShadowedShape.docx` adlı bir dosya, 45° açıyla hafif, yarı şeffaf bir drop shadow içeren tek bir dikdörtgen içerir. + +--- + +## Varyasyonlar ve İleri Düzey İpuçları + +### Gölge Rengini Değiştirme + +Varsayılan olarak gölge, şeklin dolgu rengini devralır, ancak özel bir renk ayarlayabilirsiniz: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Farklı Gölgelere Sahip Birden Çok Şekil + +Birden fazla şekle ihtiyacınız varsa, oluşturma ve yapılandırma adımlarını tekrarlayın. Daha sonra referans vermeyi planlıyorsanız, her şekle benzersiz bir ad vermeyi unutmayın. + +### Gölge Efektleri Korunarak PDF'ye Dışa Aktarma + +Aspose.Words, PDF'ye kaydederken gölge efektlerini korur: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Yaygın Tuzaklar + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Gölge görünmüyor | `ShadowFormat.Visible` `false` olarak bırakılmış | `true` olarak ayarlayın. | +| Gölge çok sert görünüyor | `Blur` `0` olarak ayarlanmış | `Blur` değerini 3–6'ya artırın. | +| Gölge PDF'de kayboluyor | Eski bir Aspose.Words sürümü (< 22.9) kullanılıyor | En son kütüphaneye yükseltin. | + +--- + +## Sonuç + +Aspose.Words kullanarak **şekle gölge ekleme** konusunu, bir belge başlatmaktan bulanıklık, mesafe, açı ve **gölge şeffaflığını uygulamaya** kadar ele aldık. Tam örnek, herhangi bir şekil veya belge düzenine uyarlayabileceğiniz temiz, üretim‑hazır bir yaklaşımı gösteriyor. + +**Aspose kullanarak Word belgesi oluşturma** gibi daha karmaşık senaryolar hakkında sorularınız mı var—örneğin gölgelere sahip tablolar veya dinamik veri‑tabanlı şekiller? Aşağıya bir yorum bırakın ya da Aspose.Words görüntü işleme ve paragraf biçimlendirme ile ilgili ilgili öğreticilere göz atın. + +Kodlamaktan keyif alın ve Word belgelerinize ekstra görsel bir parlaklık katmanın tadını çıkarın! + +--- + +![şekle gölge ekleme örneği](shadowed_shape.png "şekle gölge ekleme örneği") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/urdu/words/_index.md b/content/urdu/words/_index.md new file mode 100644 index 000000000..ebec53757 --- /dev/null +++ b/content/urdu/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "urdu" +type: "family" +--- + +# Words Tutorials diff --git a/content/urdu/words/net/_index.md b/content/urdu/words/net/_index.md new file mode 100644 index 000000000..f40bd96cb --- /dev/null +++ b/content/urdu/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "urdu" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/urdu/words/net/getting-started/_index.md b/content/urdu/words/net/getting-started/_index.md new file mode 100644 index 000000000..e4ee642ff --- /dev/null +++ b/content/urdu/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "urdu" +type: "category" +--- + +# Getting Started diff --git a/content/urdu/words/net/getting-started/tutorial/_index.md b/content/urdu/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..dcc7008fb --- /dev/null +++ b/content/urdu/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,231 @@ +--- +language: ur +url: /urdu/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Aspose.Words دستاویزات میں غائب فونٹس کا پتہ لگائیں – مکمل C# گائیڈ + +کبھی سوچا ہے کہ Aspose.Words کے ساتھ Word فائل لوڈ کرتے وقت **غائب فونٹس کا پتہ کیسے لگایا جائے**؟ میرے روزمرہ کے کام میں، میں نے کچھ PDFs دیکھے ہیں جو خراب لگ رہے تھے کیونکہ اصل دستاویز میں کوئی ایسا فونٹ استعمال ہوا تھا جو میرے سسٹم میں نصب نہیں تھا۔ خوشخبری یہ ہے کہ Aspose.Words آپ کو بالکل بتا سکتا ہے کہ کب یہ فونٹ کی تبدیلی کرتا ہے، اور آپ اس معلومات کو ایک سادہ warning callback کے ذریعے حاصل کر سکتے ہیں۔ + +اس tutorial میں ہم ایک **مکمل، قابلِ چلانے والا مثال** دیکھیں گے جو آپ کو ہر فونٹ کی تبدیلی کو لاگ کرنے کا طریقہ دکھائے گا، callback کیوں اہم ہے، اور مضبوط غائب‑فونٹ کی شناخت کے لیے چند اضافی ٹرکس۔ کوئی فضول بات نہیں، صرف وہ کوڈ اور منطق جو آپ کو آج ہی کام کرنے کے لیے درکار ہے۔ + +--- + +## آپ کیا سیکھیں گے + +- کیسے **Aspose.Words warning callback** کو نافذ کریں تاکہ فونٹ کی تبدیلی کے واقعات کو پکڑا جا سکے۔ +- کیسے **LoadOptions C#** کو ترتیب دیں تاکہ دستاویز لوڈ کرتے وقت callback چلایا جائے۔ +- کیسے اس بات کی تصدیق کریں کہ غائب‑فونٹ کی شناخت واقعی کام کر رہی ہے، اور کنسول آؤٹ پٹ کیسا دکھائی دیتا ہے۔ +- بڑے بیچز یا headless ماحول کے لیے اختیاری ایڈجسٹمنٹ۔ + +**Prerequisites** – آپ کو Aspose.Words for .NET کا تازہ ورژن (کوڈ 23.12 کے ساتھ ٹیسٹ کیا گیا)، .NET 6 یا اس کے بعد کا ورژن، اور C# کی بنیادی سمجھ بوجھ کی ضرورت ہے۔ اگر یہ سب ہے تو آپ تیار ہیں۔ + +--- + +## Warning Callback کے ساتھ غائب فونٹس کا پتہ لگائیں + +حل کا دل `IWarningCallback` کی ایک عمل درآمد ہے۔ Aspose.Words کئی حالات کے لیے `WarningInfo` آبجیکٹ جاری کرتا ہے، لیکن ہمیں صرف `WarningType.FontSubstitution` کی پرواہ ہے۔ آئیں دیکھتے ہیں کہ اس سے کیسے جڑا جائے۔ + +### قدم 1: Font‑Warning Collector بنائیں + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*کیوں اہم ہے*: `WarningType.FontSubstitution` پر فلٹرنگ کرنے سے ہم غیر متعلقہ وارننگز (جیسے پرانی خصوصیات) کی گندگی سے بچتے ہیں۔ `info.Description` میں پہلے سے ہی اصل فونٹ کا نام اور استعمال شدہ بیک اپ شامل ہوتا ہے، جو آپ کو واضح آڈٹ ٹریل فراہم کرتا ہے۔ + +## Callback استعمال کرنے کے لیے LoadOptions کی ترتیب دیں + +اب ہم Aspose.Words کو بتاتے ہیں کہ فائل لوڈ کرتے وقت ہمارا collector استعمال کرے۔ + +### قدم 2: LoadOptions سیٹ اپ کریں + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*کیوں اہم ہے*: `LoadOptions` وہ واحد جگہ ہے جہاں آپ callback، encryption passwords، اور دیگر لوڈنگ رویے شامل کر سکتے ہیں۔ اسے `Document` کنسٹرکٹر سے الگ رکھنا کوڈ کو متعدد فائلوں کے لیے دوبارہ استعمال کے قابل بناتا ہے۔ + +## دستاویز لوڈ کریں اور غائب فونٹس کو کیپچر کریں + +Callback کو جوڑنے کے بعد، اگلا قدم صرف دستاویز کو لوڈ کرنا ہے۔ + +### قدم 3: اپنا DOCX (یا کوئی بھی سپورٹ شدہ فارمیٹ) لوڈ کریں + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +جب `Document` کنسٹرکٹر فائل کو پارس کرتا ہے، تو کوئی بھی غائب فونٹ ہمارے `FontWarningCollector` کو ٹرگر کرتا ہے۔ کنسول میں اس طرح کی لائنیں دکھائی دیں گی: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +یہ لائن اس بات کا واضح ثبوت ہے کہ **غائب فونٹس کا پتہ لگانا** کام کر گیا۔ + +## آؤٹ پٹ کی تصدیق – کیا توقع رکھیں + +پروگرام کو ٹرمینل یا Visual Studio سے چلائیں۔ اگر سورس دستاویز میں کوئی ایسا فونٹ ہو جو آپ کے سسٹم میں نصب نہ ہو، تو آپ کم از کم ایک “Font substituted” لائن دیکھیں گے۔ اگر دستاویز صرف نصب شدہ فونٹس استعمال کرتی ہے، تو callback خاموش رہتا ہے اور آپ کو صرف “Document loaded successfully.” کا پیغام ملے گا۔ + +**Tip**: دوبارہ چیک کرنے کے لیے، Word فائل کو Microsoft Word میں کھولیں اور فونٹ لسٹ دیکھیں۔ کوئی بھی فونٹ جو *Home → Font* گروپ کے تحت *Replace Fonts* میں ظاہر ہوتا ہے، تبدیلی کے لیے امیدوار ہے۔ + +## ایڈوانسڈ: بڑے پیمانے پر غائب فونٹس کا پتہ لگائیں + +اکثر آپ کو درجنوں فائلوں کو اسکین کرنا پڑتا ہے۔ یہی پیٹرن آسانی سے اسکیل ہو جاتا ہے: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +کیونکہ `FontWarningCollector` ہر بار کال ہونے پر کنسول پر لکھتا ہے، آپ کو ہر فائل کی رپورٹ بغیر کسی اضافی کوڈ کے مل جائے گی۔ پروڈکشن کے حالات میں آپ فائل یا ڈیٹا بیس میں لاگ کرنا چاہ سکتے ہیں – صرف `Console.WriteLine` کو اپنے پسندیدہ لاگر سے بدل دیں۔ + +## عام مشکلات اور پیشہ ورانہ ٹپس + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **کوئی وارننگ نہیں دکھائی دیتی** | دستاویز میں اصل میں صرف نصب شدہ فونٹس ہیں۔ | Word میں فائل کھول کر یا نظام سے جان بوجھ کر کوئی فونٹ ہٹا کر تصدیق کریں۔ | +| **Callback کال نہیں ہو رہا** | `LoadOptions.WarningCallback` کبھی تفویض نہیں کیا گیا یا بعد میں نیا `LoadOptions` انسٹنس استعمال ہوا۔ | ایک ہی `LoadOptions` آبجیکٹ رکھیں اور ہر لوڈ کے لیے اسے دوبارہ استعمال کریں۔ | +| **بہت زیادہ غیر متعلقہ وارننگز** | آپ نے `WarningType.FontSubstitution` کے ذریعے فلٹر نہیں کیا۔ | `if (info.Type == WarningType.FontSubstitution)` گارڈ شامل کریں جیسا کہ دکھایا گیا ہے۔ | +| **بڑی فائلوں پر کارکردگی سست** | Callback ہر وارننگ پر چلتا ہے، جو بڑی دستاویزات کے لیے بہت ہو سکتا ہے۔ | `LoadOptions.WarningCallback` کے ذریعے دیگر وارننگ ٹائپس کو غیر فعال کریں یا اگر آپ کو معلوم ہو تو `LoadOptions.LoadFormat` کو مخصوص ٹائپ پر سیٹ کریں۔ | + +## مکمل کام کرنے والی مثال (Copy‑Paste کے لیے تیار) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**متوقع کنسول آؤٹ پٹ** (جب کوئی غائب فونٹ ملے): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +اگر کوئی تبدیلی نہ ہو تو آپ صرف کامیابی کی لائن دیکھیں گے۔ + +## نتیجہ + +آپ کے پاس اب **مکمل، پروڈکشن‑ریڈی طریقہ** ہے Aspose.Words کے ذریعے کسی بھی دستاویز میں غائب فونٹس کا پتہ لگانے کا۔ **Aspose.Words warning callback** اور **LoadOptions C#** کی ترتیب کے ذریعے، آپ ہر فونٹ کی تبدیلی کو لاگ کر سکتے ہیں، لے آؤٹ کے مسائل حل کر سکتے ہیں، اور یہ یقینی بناتے ہیں کہ آپ کے PDFs مطلوبہ شکل و صورت برقرار رکھیں۔ + +ایک فائل سے لے کر بڑے بیچ تک، پیٹرن ایک ہی رہتا ہے—`IWarningCallback` کو نافذ کریں، اسے `LoadOptions` میں لگائیں، اور Aspose.Words کو بھاری کام کرنے دیں۔ + +اگلے قدم کے لیے تیار ہیں؟ اس کو **font embedding** یا **fallback font families** کے ساتھ ملائیں تاکہ مسئلہ خودکار طور پر حل ہو، یا گہرائی سے مواد کے تجزیے کے لیے **DocumentVisitor** API دیکھیں۔ خوش کوڈنگ، اور امید ہے کہ آپ کے تمام فونٹس وہیں رہیں جہاں آپ توقع کرتے ہیں! + +![Detect missing fonts in Aspose.Words – console output screenshot](https://example.com/images/detect-missing-fonts.png "detect missing fonts console output") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/urdu/words/net/images-and-shapes/_index.md b/content/urdu/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..e07fa03c9 --- /dev/null +++ b/content/urdu/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "urdu" +type: "category" +--- + +# Images And Shapes diff --git a/content/urdu/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/urdu/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..e7d68acf7 --- /dev/null +++ b/content/urdu/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Aspose.Words کے ساتھ شکل پر جلدی شیڈو لگائیں۔ Aspose استعمال کرتے ہوئے + ورڈ دستاویز کیسے بنائیں، شکل پر شیڈو کیسے شامل کریں، اور C# میں شیڈو کی شفافیت کیسے + لاگو کریں، سیکھیں۔ +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: ur +og_description: Aspose.Words استعمال کرتے ہوئے Word فائل میں شکل پر سایہ شامل کریں۔ + یہ مرحلہ وار رہنمائی دکھاتی ہے کہ دستاویز کیسے بنائی جائے، شکل کیسے شامل کی جائے، + اور سایہ کی شفافیت کیسے لاگو کی جائے۔ +og_title: شیپ پر سایہ شامل کریں – Aspose.Words C# ٹیوٹوریل +tags: +- Aspose.Words +- C# +- Word Automation +title: ورڈ دستاویز میں شکل پر سایہ شامل کریں – مکمل Aspose.Words گائیڈ +url: /urdu/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# shape پر سایہ شامل کریں – مکمل Aspose.Words گائیڈ + +کبھی Word فائل میں **shape پر سایہ شامل کرنا** ضروری ہوا لیکن آپ کو نہیں پتہ تھا کہ کون سی API کالز استعمال کریں؟ آپ اکیلے نہیں ہیں۔ بہت سے ڈویلپرز کو پہلی بار جب وہ کسی مستطیل یا کسی بھی ڈرائنگ ایلیمنٹ پر مناسب ڈراپ‑شیڈو دینے کی کوشش کرتے ہیں تو رکاوٹ ملتی ہے، خاص طور پر جب وہ Aspose.Words for .NET کے ساتھ کام کر رہے ہوں۔ + +اس ٹیوٹوریل میں ہم آپ کو ہر وہ چیز سکھائیں گے جو آپ کو جاننی ضروری ہے: **Aspose استعمال کرتے ہوئے Word دستاویز بنانے** سے لے کر سایہ کی ترتیب، اس کے بلر، فاصلہ، زاویہ، اور حتیٰ کہ **سایہ کی شفافیت لگانے** تک۔ آخر تک آپ کے پاس ایک تیار‑چلانے کے قابل C# پروگرام ہوگا جو ایک `.docx` فائل بنائے گا جس میں ایک خوبصورت سایہ دار مستطیل ہو—Word میں کسی دستی مداخلت کی ضرورت نہیں۔ + +--- + +## آپ کیا سیکھیں گے + +- Visual Studio میں Aspose.Words پروجیکٹ کیسے سیٹ اپ کریں۔ +- بالکل درست قدم **Aspose استعمال کرتے ہوئے Word دستاویز بنانے** اور ایک shape داخل کرنے کے۔ +- **shape پر سایہ شامل کرنے** کے طریقے کے ساتھ بلر، فاصلہ، زاویہ، اور شفافیت پر مکمل کنٹرول۔ +- عام مسائل کی ٹroubleshooting کے لیے نکات (مثلاً، لائسنس غائب، غلط یونٹس)۔ +- ایک مکمل، کاپی‑اینڈ‑پیسٹ کوڈ نمونہ جو آپ آج ہی چلا سکتے ہیں۔ + +> **Prerequisites:** .NET 6+ (or .NET Framework 4.7.2+), ایک معتبر Aspose.Words لائسنس (یا مفت ٹرائل), اور C# کی بنیادی واقفیت۔ + +--- + +## قدم 1 – اپنے پروجیکٹ کو سیٹ اپ کریں اور Aspose.Words شامل کریں + +سب سے پہلے۔ Visual Studio کھولیں، ایک نیا **Console App (.NET Core)** بنائیں، اور Aspose.Words NuGet پیکج شامل کریں: + +```bash +dotnet add package Aspose.Words +``` + +> **Pro tip:** اگر آپ کے پاس لائسنس فائل (`Aspose.Words.lic`) ہے تو اسے پروجیکٹ کی جڑ میں کاپی کریں اور اسٹارٹ اپ پر لوڈ کریں۔ یہ مفت ایویلیوئیشن موڈ میں ظاہر ہونے والے واٹرمارک سے بچاتا ہے۔ + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## قدم 2 – نیا خالی دستاویز بنائیں + +اب ہم واقعی **Aspose استعمال کرتے ہوئے Word دستاویز بنائیں**۔ یہ آبجیکٹ ہماری shape کے لیے کینوس کے طور پر کام کرے گا۔ + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +`Document` کلاس باقی سب کے لیے انٹری پوائنٹ ہے—پیراگراف، سیکشن، اور یقیناً، ڈرائنگ آبجیکٹس۔ + +--- + +## قدم 3 – ایک مستطیل shape داخل کریں + +دستاویز تیار ہونے کے بعد، ہم ایک shape شامل کر سکتے ہیں۔ یہاں ہم ایک سادہ مستطیل منتخب کرتے ہیں، لیکن یہی منطق دائرے، لائنیں، یا کسٹم پولیگون کے لیے بھی کام کرتی ہے۔ + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **shape کیوں؟** Aspose.Words میں `Shape` آبجیکٹ ٹیکسٹ، امیجز رکھ سکتا ہے، یا صرف ایک سجاوٹی عنصر کے طور پر کام کر سکتا ہے۔ shape پر سایہ شامل کرنا تصویر کے فریم کو تبدیل کرنے سے کہیں آسان ہے۔ + +--- + +## قدم 4 – سایہ کی ترتیب (shape پر سایہ شامل کریں) + +یہ ٹیوٹوریل کا دل ہے—**shape پر سایہ کیسے شامل کریں** اور اس کی ظاہری شکل کو باریک‑باریک ایڈجسٹ کریں۔ `ShadowFormat` پراپرٹی آپ کو مکمل کنٹرول دیتی ہے۔ + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### ہر پراپرٹی کا کیا کام ہے + +| پراپرٹی | اثر | عام اقدار | +|----------|--------|----------------| +| **Visible** | سایہ کو آن/آف کرتا ہے۔ | `true` / `false` | +| **Blur** | سایہ کے کناروں کو نرم کرتا ہے۔ | `0` (hard) to `10` (very soft) | +| **Distance** | سایہ کو shape سے دور لے جاتا ہے۔ | `1`–`5` points is common | +| **Angle** | آفسیٹ کی سمت کو کنٹرول کرتا ہے۔ | `0`–`360` degrees | +| **Transparency** | سایہ کو جزوی طور پر شفاف بناتا ہے۔ | `0` (opaque) to `1` (invisible) | + +> **Edge case:** اگر آپ `Transparency` کو `1` پر سیٹ کریں تو سایہ مکمل طور پر غائب ہو جاتا ہے—یہ پروگرام کے ذریعے ٹوگل کرنے کے لیے مفید ہے۔ + +--- + +## قدم 5 – shape کو دستاویز میں شامل کریں + +اب ہم shape کو دستاویز کے باڈی کے پہلے پیراگراف سے منسلک کرتے ہیں۔ اگر کوئی پیراگراف موجود نہ ہو تو Aspose خود بخود ایک پیراگراف بناتا ہے۔ + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +اگر آپ کی دستاویز میں پہلے سے مواد موجود ہے تو آپ `InsertAfter` یا `InsertBefore` استعمال کر کے shape کو کسی بھی نوڈ پر داخل کر سکتے ہیں۔ + +--- + +## قدم 6 – دستاویز محفوظ کریں + +آخر میں، فائل کو ڈسک پر لکھیں۔ آپ کوئی بھی سپورٹ شدہ فارمیٹ (`.docx`, `.pdf`, `.odt`, وغیرہ) منتخب کر سکتے ہیں، لیکن اس ٹیوٹوریل کے لیے ہم نیٹو Word فارمیٹ پر رہیں گے۔ + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +نتیجہ میں بنے `ShadowedShape.docx` کو Microsoft Word میں کھولیں، اور آپ کو ایک مستطیل دکھائی دے گی جس پر نرم، 45‑ڈگری کا سایہ ہے جو 30 % شفاف ہے—بالکل وہی جو ہم نے ترتیب دیا تھا۔ + +--- + +## مکمل کام کرنے والی مثال + +نیچے **مکمل، کاپی‑اینڈ‑پیسٹ کے لیے تیار** پروگرام ہے جو اوپر دیے گئے تمام قدموں کو شامل کرتا ہے۔ اسے `Program.cs` کے طور پر محفوظ کریں اور `dotnet run` کے ساتھ چلائیں۔ + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**متوقع نتیجہ:** ایک فائل جس کا نام `ShadowedShape.docx` ہے، جس میں ایک واحد مستطیل ہے جس پر ہلکا، نیم‑شفاف ڈراپ شیڈو 45° کے زاویے پر ہے۔ + +--- + +## مختلف صورتیں اور ایڈوانس ٹپس + +### سایہ کا رنگ تبدیل کرنا + +ڈیفالٹ طور پر سایہ shape کے فل رنگ سے وراثت میں ملتا ہے، لیکن آپ ایک کسٹم رنگ سیٹ کر سکتے ہیں: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### مختلف سایوں کے ساتھ متعدد shapes + +اگر آپ کو کئی shapes کی ضرورت ہے تو صرف تخلیق اور ترتیب کے قدموں کو دہراتے رہیں۔ اگر آپ بعد میں ان کا حوالہ دینا چاہتے ہیں تو ہر shape کو ایک منفرد نام دیں۔ + +### PDF میں ایکسپورٹ کرنا اور سایے محفوظ رکھنا + +Aspose.Words PDF میں محفوظ کرتے وقت سایہ کے اثرات کو برقرار رکھتا ہے: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### عام مشکلات + +| علامت | ممکنہ وجہ | حل | +|---------|--------------|-----| +| سایہ نظر نہیں آ رہا | `ShadowFormat.Visible` کو `false` پر چھوڑ دیا گیا | اسے `true` پر سیٹ کریں۔ | +| سایہ بہت سخت لگ رہا ہے | `Blur` کو `0` پر سیٹ کیا گیا | `Blur` کو 3–6 تک بڑھائیں۔ | +| PDF میں سایہ غائب ہو جاتا ہے | پرانا Aspose.Words ورژن (< 22.9) استعمال کرنا | لائبریری کو جدید ترین ورژن پر اپگریڈ کریں۔ | + +--- + +## نتیجہ + +ہم نے Aspose.Words کے ذریعے **shape پر سایہ کیسے شامل کریں** کا احاطہ کیا ہے، دستاویز کی ابتدا سے لے کر بلر، فاصلہ، زاویہ، اور **سایہ کی شفافیت لگانے** تک۔ مکمل مثال ایک صاف، پروڈکشن‑ریڈی طریقہ دکھاتی ہے جسے آپ کسی بھی shape یا دستاویز کے لے آؤٹ کے لیے اپناؤ سکتے ہیں۔ + +اگر آپ کے پاس **Aspose استعمال کرتے ہوئے Word دستاویز بنانے** کے بارے میں مزید پیچیدہ مناظر—جیسے سایہ والے جدول یا ڈائنامک ڈیٹا‑ڈرائیوڈ shapes—کے بارے میں سوالات ہیں تو نیچے تبصرہ کریں یا Aspose.Words کی امیج ہینڈلنگ اور پیراگراف فارمیٹنگ کے متعلقہ ٹیوٹوریلز دیکھیں۔ + +کوڈنگ کا لطف اٹھائیں، اور اپنے Word دستاویزات کو ایک اضافی بصری چمک دینے کا مزہ لیں! + +--- + +![shape پر سایہ کی مثال](shadowed_shape.png "shape پر سایہ کی مثال") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/vietnamese/words/_index.md b/content/vietnamese/words/_index.md new file mode 100644 index 000000000..d9a6a85e4 --- /dev/null +++ b/content/vietnamese/words/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words" +language: "vietnamese" +type: "family" +--- + +# Words Tutorials diff --git a/content/vietnamese/words/net/_index.md b/content/vietnamese/words/net/_index.md new file mode 100644 index 000000000..ab41072ce --- /dev/null +++ b/content/vietnamese/words/net/_index.md @@ -0,0 +1,7 @@ +--- +title: "Words Net" +language: "vietnamese" +type: "platform" +--- + +# Words Net Tutorials diff --git a/content/vietnamese/words/net/getting-started/_index.md b/content/vietnamese/words/net/getting-started/_index.md new file mode 100644 index 000000000..7d6b26abd --- /dev/null +++ b/content/vietnamese/words/net/getting-started/_index.md @@ -0,0 +1,7 @@ +--- +title: "Getting Started" +language: "vietnamese" +type: "category" +--- + +# Getting Started diff --git a/content/vietnamese/words/net/getting-started/tutorial/_index.md b/content/vietnamese/words/net/getting-started/tutorial/_index.md new file mode 100644 index 000000000..3ed62580b --- /dev/null +++ b/content/vietnamese/words/net/getting-started/tutorial/_index.md @@ -0,0 +1,247 @@ +--- +language: vi +url: /vietnamese/net/getting-started/tutorial/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +```yaml +--- +title: "Detect Missing Fonts in Aspose.Words Documents – Complete C# Guide" +description: "Detect missing fonts in your Aspose.Words documents using a warning callback. Learn how to log font substitutions with C# and keep your PDFs looking right." +date: 2025-12-08 +draft: false +language: "en" +category: "general" +url: "PLACEHOLDER_URL" +keywords: + - detect missing fonts + - Aspose.Words warning callback + - font substitution + - LoadOptions C# + - document loading C# + - missing font detection +tags: + - Aspose.Words + - C# + - Font Management +og_title: "Detect Missing Fonts in Aspose.Words – Step‑by‑Step C# Guide" +og_description: "Detect missing fonts in Aspose.Words documents instantly. Follow this guide to set up a warning callback and capture font substitution events in C#." +--- +``` + +# Phát hiện phông chữ thiếu trong tài liệu Aspose.Words – Hướng dẫn C# đầy đủ + +Bạn đã bao giờ tự hỏi làm thế nào để **phát hiện phông chữ thiếu** khi tải một tệp Word bằng Aspose.Words chưa? Trong công việc hàng ngày, tôi đã gặp một vài PDF trông không đúng vì tài liệu gốc sử dụng một phông chữ mà tôi không cài đặt. Tin tốt là gì? Aspose.Words có thể cho bạn biết chính xác khi nó thay thế một phông chữ, và bạn có thể ghi lại thông tin đó bằng một callback cảnh báo đơn giản. + +Trong hướng dẫn này, chúng ta sẽ đi qua một **ví dụ đầy đủ, có thể chạy được** cho thấy cách ghi lại mọi lần thay thế phông, lý do tại sao callback quan trọng, và một vài mẹo bổ sung để phát hiện phông chữ thiếu một cách chắc chắn. Không có phần thừa thãi, chỉ có mã và lý giải bạn cần để làm cho nó hoạt động ngay hôm nay. + +--- + +## Những gì bạn sẽ học + +- Cách triển khai **callback cảnh báo Aspose.Words** để bắt các sự kiện thay thế phông chữ. +- Cách cấu hình **LoadOptions C#** để callback được gọi khi tải tài liệu. +- Cách xác minh rằng việc phát hiện phông chữ thiếu thực sự hoạt động, và cách đầu ra console trông như thế nào. +- Các điều chỉnh tùy chọn cho các lô lớn hoặc môi trường không giao diện. + +**Yêu cầu trước** – Bạn cần một phiên bản mới của Aspose.Words cho .NET (mã đã được kiểm tra với 23.12), .NET 6 trở lên, và kiến thức cơ bản về C#. Nếu bạn đã có những thứ này, bạn đã sẵn sàng. + +--- + +## Phát hiện phông chữ thiếu bằng Callback cảnh báo + +Trọng tâm của giải pháp là việc triển khai `IWarningCallback`. Aspose.Words phát ra một đối tượng `WarningInfo` cho nhiều tình huống, nhưng chúng ta chỉ quan tâm đến `WarningType.FontSubstitution`. Hãy xem cách kết nối vào đó. + +### Bước 1: Tạo Bộ Thu Thập Cảnh Báo Phông Chữ + +```csharp +using Aspose.Words; +using Aspose.Words.LoadOptions; + +/// +/// Collects font‑substitution warnings emitted by Aspose.Words. +/// +class FontWarningCollector : IWarningCallback +{ + // The Warning method is called automatically by the library. + public void Warning(WarningInfo info) + { + // Filter only font‑substitution warnings. + if (info.Type == WarningType.FontSubstitution) + { + // Write a helpful message to the console. + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} +``` + +*Tại sao điều này quan trọng*: Bằng cách lọc theo `WarningType.FontSubstitution` chúng ta tránh được sự lộn xộn từ các cảnh báo không liên quan (như các tính năng đã lỗi thời). `info.Description` đã chứa tên phông chữ gốc và phông chữ dự phòng được sử dụng, cung cấp cho bạn một chuỗi kiểm tra rõ ràng. + +--- + +## Cấu hình LoadOptions để sử dụng Callback + +Bây giờ chúng ta cho Aspose.Words biết sử dụng bộ thu thập của chúng ta khi nó tải một tệp. + +### Bước 2: Thiết lập LoadOptions + +```csharp +// Create a LoadOptions instance – this controls how the document is read. +LoadOptions loadOptions = new LoadOptions +{ + // Assign our custom warning callback. + WarningCallback = new FontWarningCollector() +}; +``` + +*Tại sao điều này quan trọng*: `LoadOptions` là nơi duy nhất bạn có thể gắn callback, mật khẩu mã hoá và các hành vi tải khác. Giữ nó tách biệt khỏi hàm khởi tạo `Document` giúp mã có thể tái sử dụng cho nhiều tệp. + +--- + +## Tải tài liệu và ghi lại phông chữ thiếu + +Với callback đã được kết nối, bước tiếp theo chỉ là tải tài liệu. + +### Bước 3: Tải DOCX của bạn (hoặc bất kỳ định dạng hỗ trợ nào) + +```csharp +// Replace the path with the location of your test document. +string inputPath = @"C:\Docs\input.docx"; + +try +{ + // The warning callback fires automatically during this call. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); +} +catch (Exception ex) +{ + // Handle file‑not‑found, access‑denied, etc. + Console.WriteLine($"Error loading document: {ex.Message}"); +} +``` + +Khi hàm khởi tạo `Document` phân tích tệp, bất kỳ phông chữ nào thiếu sẽ kích hoạt `FontWarningCollector` của chúng ta. Console sẽ hiển thị các dòng như: + +``` +Font substituted: Arial (substituted with Liberation Sans) +Document loaded successfully. +``` + +Dòng đó là bằng chứng cụ thể rằng **phát hiện phông chữ thiếu** đã hoạt động. + +--- + +## Xác minh đầu ra – Những gì mong đợi + +Chạy chương trình từ terminal hoặc Visual Studio. Nếu tài liệu nguồn chứa một phông chữ mà bạn không cài đặt, bạn sẽ thấy ít nhất một dòng “Font substituted”. Nếu tài liệu chỉ sử dụng các phông chữ đã cài đặt, callback sẽ im lặng và bạn chỉ nhận được thông báo “Document loaded successfully.”. + +**Mẹo**: Để kiểm tra lại, mở tệp Word trong Microsoft Word và xem danh sách phông chữ. Bất kỳ phông chữ nào xuất hiện trong *Replace Fonts* dưới nhóm *Home → Font* đều là ứng cử viên cho việc thay thế. + +--- + +## Nâng cao: Phát hiện phông chữ thiếu hàng loạt + +Thường bạn cần quét hàng chục tệp. Mẫu tương tự mở rộng tốt: + +```csharp +string[] files = Directory.GetFiles(@"C:\Docs\Batch", "*.docx"); + +foreach (var file in files) +{ + Console.WriteLine($"\nProcessing: {Path.GetFileName(file)}"); + Document doc = new Document(file, loadOptions); +} +``` + +Vì `FontWarningCollector` ghi ra console mỗi khi được gọi, bạn sẽ nhận được báo cáo theo từng tệp mà không cần cấu hình thêm. Đối với các kịch bản sản xuất, bạn có thể muốn ghi log vào tệp hoặc cơ sở dữ liệu – chỉ cần thay thế `Console.WriteLine` bằng logger bạn ưa thích. + +--- + +## Những lỗi thường gặp & Mẹo chuyên nghiệp + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|----------------|-----| +| **Không có cảnh báo nào xuất hiện** | Tài liệu thực tế chỉ chứa các phông chữ đã được cài đặt. | Xác minh bằng cách mở tệp trong Word hoặc cố ý gỡ bỏ một phông chữ khỏi hệ thống. | +| **Callback không được gọi** | `LoadOptions.WarningCallback` chưa bao giờ được gán hoặc một đối tượng `LoadOptions` mới đã được sử dụng sau này. | Giữ một đối tượng `LoadOptions` duy nhất và tái sử dụng nó cho mỗi lần tải. | +| **Quá nhiều cảnh báo không liên quan** | Bạn chưa lọc theo `WarningType.FontSubstitution`. | Thêm điều kiện `if (info.Type == WarningType.FontSubstitution)` như đã minh họa. | +| **Giảm hiệu năng trên các tệp lớn** | Callback chạy trên mỗi cảnh báo, có thể rất nhiều đối với tài liệu lớn. | Vô hiệu hoá các loại cảnh báo khác qua `LoadOptions.WarningCallback` hoặc đặt `LoadOptions.LoadFormat` thành một kiểu cụ thể nếu bạn biết. | + +--- + +## Ví dụ đầy đủ hoạt động (Sẵn sàng sao chép‑dán) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.LoadOptions; + +class FontWarningCollector : IWarningCallback +{ + public void Warning(WarningInfo info) + { + if (info.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substituted: {info.Description}"); + } + } +} + +class Program +{ + static void Main() + { + // Step 2 – configure LoadOptions with our warning callback. + LoadOptions loadOptions = new LoadOptions + { + WarningCallback = new FontWarningCollector() + }; + + // Path to a single document or a folder for batch processing. + string inputPath = @"C:\Docs\input.docx"; + + try + { + // Step 3 – load the document; warnings are emitted automatically. + Document doc = new Document(inputPath, loadOptions); + Console.WriteLine("Document loaded successfully."); + } + catch (Exception ex) + { + Console.WriteLine($"Error loading document: {ex.Message}"); + } + } +} +``` + +**Đầu ra console dự kiến** (khi gặp phông chữ thiếu): + +``` +Font substituted: Times New Roman (substituted with Liberation Serif) +Document loaded successfully. +``` + +Nếu không có sự thay thế nào xảy ra, bạn sẽ chỉ thấy dòng thành công. + +--- + +## Kết luận + +Bạn đã có một **cách đầy đủ, sẵn sàng cho sản xuất để phát hiện phông chữ thiếu** trong bất kỳ tài liệu nào được xử lý bởi Aspose.Words. Bằng cách tận dụng **callback cảnh báo Aspose.Words** và cấu hình **LoadOptions C#**, bạn có thể ghi lại mọi lần thay thế phông chữ, khắc phục các vấn đề bố cục, và đảm bảo PDF của bạn giữ được giao diện mong muốn. + +Từ một tệp đơn lẻ đến một lô hàng khổng lồ, mẫu vẫn giống nhau—triển khai `IWarningCallback`, gắn nó vào `LoadOptions`, và để Aspose.Words thực hiện phần công việc nặng. + +Sẵn sàng cho bước tiếp theo? Hãy thử kết hợp điều này với **font embedding** hoặc **fallback font families** để tự động khắc phục vấn đề, hoặc khám phá API **DocumentVisitor** để phân tích nội dung sâu hơn. Chúc lập trình vui vẻ, và hy vọng mọi phông chữ của bạn luôn ở nơi bạn mong đợi! + +--- + +![Phát hiện phông chữ thiếu trong Aspose.Words – ảnh chụp màn hình đầu ra console](https://example.com/images/detect-missing-fonts.png "đầu ra console phát hiện phông chữ thiếu") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file diff --git a/content/vietnamese/words/net/images-and-shapes/_index.md b/content/vietnamese/words/net/images-and-shapes/_index.md new file mode 100644 index 000000000..b9e84ee38 --- /dev/null +++ b/content/vietnamese/words/net/images-and-shapes/_index.md @@ -0,0 +1,7 @@ +--- +title: "Images And Shapes" +language: "vietnamese" +type: "category" +--- + +# Images And Shapes diff --git a/content/vietnamese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md b/content/vietnamese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md new file mode 100644 index 000000000..ff8cb8697 --- /dev/null +++ b/content/vietnamese/words/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2025-12-08 +description: Thêm bóng cho hình dạng nhanh chóng với Aspose.Words. Tìm hiểu cách tạo + tài liệu Word bằng Aspose, cách thêm bóng cho hình dạng và áp dụng độ trong suốt + của bóng trong C#. +draft: false +keywords: +- add shadow to shape +- create word document using aspose +- how to add shape shadow +- apply shadow transparency +language: vi +og_description: Thêm bóng cho hình dạng trong tệp Word bằng Aspose.Words. Hướng dẫn + từng bước này cho thấy cách tạo tài liệu, thêm hình dạng và áp dụng độ trong suốt + của bóng. +og_title: Thêm bóng cho hình dạng – Hướng dẫn Aspose.Words C# +tags: +- Aspose.Words +- C# +- Word Automation +title: Thêm bóng cho hình dạng trong tài liệu Word – Hướng dẫn đầy đủ Aspose.Words +url: /vietnamese/net/images-and-shapes/add-shadow-to-shape-in-a-word-document-complete-aspose-words/ +--- + +{{< layout-start >}} + +{{< layout-start >}} + +# Thêm Bóng Đổ cho Hình – Hướng Dẫn Toàn Diện Aspose.Words + +Bạn đã bao giờ cần **thêm bóng đổ cho hình** trong một tệp Word nhưng không chắc nên sử dụng API nào không? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp khó khăn khi lần đầu cố gắng tạo bóng đổ cho một hình chữ nhật hoặc bất kỳ phần tử vẽ nào, đặc biệt khi họ làm việc với Aspose.Words cho .NET. + +Trong tutorial này, chúng ta sẽ đi qua mọi thứ bạn cần biết: từ **tạo tài liệu Word bằng Aspose** đến việc cấu hình bóng, điều chỉnh độ mờ, khoảng cách, góc, và thậm chí **áp dụng độ trong suốt cho bóng**. Khi kết thúc, bạn sẽ có một chương trình C# sẵn sàng chạy, tạo ra tệp `.docx` với một hình chữ nhật được tô bóng đẹp mắt—không cần can thiệp thủ công trong Word. + +--- + +## Những Điều Bạn Sẽ Học + +- Cách thiết lập dự án Aspose.Words trong Visual Studio. +- Các bước chính để **tạo tài liệu Word bằng Aspose** và chèn một hình. +- **Cách thêm bóng cho hình** với kiểm soát đầy đủ về độ mờ, khoảng cách, góc và độ trong suốt. +- Mẹo khắc phục các vấn đề thường gặp (ví dụ: thiếu giấy phép, đơn vị không đúng). +- Một mẫu mã hoàn chỉnh, sao chép‑dán mà bạn có thể chạy ngay hôm nay. + +> **Yêu cầu trước:** .NET 6+ (hoặc .NET Framework 4.7.2+), một giấy phép Aspose.Words hợp lệ (hoặc bản dùng thử miễn phí), và kiến thức cơ bản về C#. + +--- + +## Bước 1 – Thiết Lập Dự Án và Thêm Aspose.Words + +Đầu tiên, mở Visual Studio, tạo một **Console App (.NET Core)** mới, và thêm gói NuGet Aspose.Words: + +```bash +dotnet add package Aspose.Words +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn có tệp giấy phép (`Aspose.Words.lic`), sao chép nó vào thư mục gốc của dự án và tải nó khi khởi động. Điều này sẽ loại bỏ dấu watermark xuất hiện trong chế độ đánh giá miễn phí. + +```csharp +// Load the license (optional but recommended) +var license = new Aspose.Words.License(); +license.SetLicense("Aspose.Words.lic"); +``` + +--- + +## Bước 2 – Tạo Tài Liệu Trống Mới + +Bây giờ chúng ta thực sự **tạo tài liệu Word bằng Aspose**. Đối tượng này sẽ làm nền cho hình của chúng ta. + +```csharp +// Step 2: Initialize a new blank document +Document doc = new Document(); // Represents an empty .docx file +``` + +Lớp `Document` là điểm khởi đầu cho mọi thứ khác—đoạn văn, phần, và dĩ nhiên, các đối tượng vẽ. + +--- + +## Bước 3 – Chèn Hình Chữ Nhật + +Với tài liệu đã sẵn sàng, chúng ta có thể thêm một hình. Ở đây chúng ta chọn một hình chữ nhật đơn giản, nhưng logic tương tự áp dụng cho vòng tròn, đường thẳng, hoặc đa giác tùy chỉnh. + +```csharp +// Step 3: Create a rectangular shape that will hold the shadow +Shape rectangle = new Shape(doc, ShapeType.Rectangle) +{ + Width = 150, // Width in points (1 point = 1/72 inch) + Height = 100 // Height in points +}; +``` + +> **Tại sao lại là hình?** Trong Aspose.Words, một đối tượng `Shape` có thể chứa văn bản, hình ảnh, hoặc chỉ đơn giản là một yếu tố trang trí. Thêm bóng cho một hình dễ dàng hơn rất nhiều so với việc thao tác khung ảnh. + +--- + +## Bước 4 – Cấu Hình Bóng Đổ (Thêm Bóng Đổ cho Hình) + +Đây là phần cốt lõi của tutorial—**cách thêm bóng cho hình** và tinh chỉnh ngoại hình của nó. Thuộc tính `ShadowFormat` cho bạn toàn quyền kiểm soát. + +```csharp +// Step 4: Enable the shadow and configure its appearance +rectangle.ShadowFormat.Visible = true; // Turn the shadow on +rectangle.ShadowFormat.Blur = 5.0; // Blur radius – higher = softer edges +rectangle.ShadowFormat.Distance = 3.0; // Offset distance from the shape +rectangle.ShadowFormat.Angle = 45; // Direction in degrees (0 = right, 90 = down) +rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent – this is how we **apply shadow transparency** +``` + +### Mô Tả Mỗi Thuộc Tính + +| Thuộc tính | Hiệu ứng | Giá trị Điển Hình | +|------------|----------|-------------------| +| **Visible** | Bật/tắt bóng. | `true` / `false` | +| **Blur** | Làm mềm các cạnh bóng. | `0` (cứng) đến `10` (rất mềm) | +| **Distance** | Đẩy bóng ra xa hình. | `1`–`5` points là phổ biến | +| **Angle** | Điều khiển hướng offset. | `0`–`360` độ | +| **Transparency** | Làm bóng trong suốt một phần. | `0` (đục) đến `1` (vô hình) | + +> **Trường hợp đặc biệt:** Nếu bạn đặt `Transparency` thành `1`, bóng sẽ biến mất hoàn toàn—hữu ích khi muốn bật/tắt bóng bằng chương trình. + +--- + +## Bước 5 – Thêm Hình Vào Tài Liệu + +Bây giờ chúng ta gắn hình vào đoạn văn đầu tiên của phần thân tài liệu. Aspose sẽ tự động tạo một đoạn văn nếu chưa có. + +```csharp +// Step 5: Append the shape to the first paragraph +doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); +``` + +Nếu tài liệu của bạn đã có nội dung, bạn có thể chèn hình vào bất kỳ node nào bằng `InsertAfter` hoặc `InsertBefore`. + +--- + +## Bước 6 – Lưu Tài Liệu + +Cuối cùng, ghi tệp ra đĩa. Bạn có thể chọn bất kỳ định dạng nào được hỗ trợ (`.docx`, `.pdf`, `.odt`, …), nhưng trong tutorial này chúng ta sẽ dùng định dạng Word gốc. + +```csharp +// Step 6: Save the document with the shadowed shape +string outputPath = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); +doc.Save(outputPath); +Console.WriteLine($"Document saved to {outputPath}"); +``` + +Mở `ShadowedShape.docx` vừa tạo trong Microsoft Word, và bạn sẽ thấy một hình chữ nhật với bóng mềm, góc 45 độ, trong suốt 30 %—đúng như chúng ta đã cấu hình. + +--- + +## Ví Dụ Hoàn Chỉnh + +Dưới đây là chương trình **đầy đủ, sao chép‑dán ngay** tích hợp tất cả các bước trên. Lưu lại dưới tên `Program.cs` và chạy bằng `dotnet run`. + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Drawing; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // OPTIONAL: Load Aspose.Words license (remove if using trial) + // ------------------------------------------------- + try + { + var license = new License(); + license.SetLicense("Aspose.Words.lic"); + } + catch (Exception ex) + { + Console.WriteLine("License not found – running in evaluation mode: " + ex.Message); + } + + // ------------------------------------------------- + // 1. Create a new blank document + // ------------------------------------------------- + Document doc = new Document(); + + // ------------------------------------------------- + // 2. Insert a rectangle shape + // ------------------------------------------------- + Shape rectangle = new Shape(doc, ShapeType.Rectangle) + { + Width = 150, + Height = 100 + }; + + // ------------------------------------------------- + // 3. Configure the shadow – this is where we **add shadow to shape** + // ------------------------------------------------- + rectangle.ShadowFormat.Visible = true; // Show the shadow + rectangle.ShadowFormat.Blur = 5.0; // Soft edges + rectangle.ShadowFormat.Distance = 3.0; // Offset distance + rectangle.ShadowFormat.Angle = 45; // Direction in degrees + rectangle.ShadowFormat.Transparency = 0.3; // 30 % transparent (apply shadow transparency) + + // ------------------------------------------------- + // 4. Add the shape to the document + // ------------------------------------------------- + doc.FirstSection.Body.FirstParagraph.AppendChild(rectangle); + + // ------------------------------------------------- + // 5. Save the file + // ------------------------------------------------- + string outFile = Path.Combine(Environment.CurrentDirectory, "ShadowedShape.docx"); + doc.Save(outFile); + Console.WriteLine($"Document created successfully: {outFile}"); + } +} +``` + +**Kết quả mong đợi:** Một tệp có tên `ShadowedShape.docx` chứa một hình chữ nhật duy nhất với bóng nhẹ, bán trong suốt, nghiêng 45°. + +--- + +## Biến Thể & Mẹo Nâng Cao + +### Thay Đổi Màu Bóng Đổ + +Mặc định bóng sẽ kế thừa màu nền của hình, nhưng bạn có thể đặt màu tùy chỉnh: + +```csharp +rectangle.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Nhiều Hình với Bóng Đổ Khác Nhau + +Nếu cần nhiều hình, chỉ cần lặp lại các bước tạo và cấu hình. Đừng quên đặt tên duy nhất cho mỗi hình nếu bạn dự định tham chiếu chúng sau này. + +### Xuất ra PDF với Bóng Đổ Được Bảo Tồn + +Aspose.Words giữ nguyên hiệu ứng bóng khi lưu ra PDF: + +```csharp +doc.Save("ShadowedShape.pdf"); +``` + +### Những Cạm Bẫy Thường Gặp + +| Triệu chứng | Nguyên Nhân Thường Gặp | Cách Khắc Phục | +|-------------|------------------------|----------------| +| Bóng không hiển thị | `ShadowFormat.Visible` để `false` | Đặt thành `true`. | +| Bóng quá cứng | `Blur` bằng `0` | Tăng `Blur` lên 3–6. | +| Bóng biến mất trong PDF | Dùng phiên bản Aspose.Words cũ (< 22.9) | Nâng cấp lên thư viện mới nhất. | + +--- + +## Kết Luận + +Chúng ta đã bao quát **cách thêm bóng đổ cho hình** bằng Aspose.Words, từ khởi tạo tài liệu đến tinh chỉnh độ mờ, khoảng cách, góc và **áp dụng độ trong suốt cho bóng**. Ví dụ đầy đủ minh họa một cách tiếp cận sạch sẽ, sẵn sàng cho môi trường sản xuất mà bạn có thể điều chỉnh cho bất kỳ hình hay bố cục tài liệu nào. + +Có câu hỏi về **tạo tài liệu Word bằng Aspose** cho các kịch bản phức tạp hơn—như bảng có bóng hoặc hình động dựa trên dữ liệu? Hãy để lại bình luận bên dưới hoặc xem các tutorial liên quan về xử lý ảnh và định dạng đoạn văn trong Aspose.Words. + +Chúc lập trình vui vẻ, và tận hưởng việc mang lại cho tài liệu Word của bạn một lớp hoàn thiện trực quan hơn! + +--- + +![ví dụ thêm bóng đổ cho hình](shadowed_shape.png "add shadow to shape example") + +{{< layout-end >}} + +{{< layout-end >}} \ No newline at end of file