diff --git a/words/arabic/net/basic-conversions/_index.md b/words/arabic/net/basic-conversions/_index.md index 4ddcead2e7..d62bb0c2a4 100644 --- a/words/arabic/net/basic-conversions/_index.md +++ b/words/arabic/net/basic-conversions/_index.md @@ -26,6 +26,7 @@ | [تحويل ملف Word إلى PDF](./docx-to-pdf/) تعرّف على كيفية تحويل ملفات Word إلى PDF بسهولة باستخدام Aspose.Words for .NET من خلال دليلنا. مثالي للمطورين الذين يبحثون عن تحويل سريع وموثوق للمستندات. | | [تحويل Word إلى PDF باستخدام C# و Aspose.Words – دليل](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | تعرّف على كيفية تحويل مستندات Word إلى PDF باستخدام C# و Aspose.Words خطوة بخطوة مع أمثلة عملية. | | [حفظ مستند Word كـ PDF باستخدام Aspose.Words – دليل C# كامل](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | تعرّف على طريقة حفظ مستندات Word بصيغة PDF باستخدام Aspose.Words في C# مع شرح مفصل وأمثلة عملية. | +| [حفظ مستند Word كـ PDF باستخدام Aspose.Words – دليل كامل](./save-word-as-pdf-with-aspose-words-complete-guide/) | تعرّف على طريقة حفظ مستندات Word بصيغة PDF باستخدام Aspose.Words في دليل شامل مع أمثلة عملية. | | [حفظ ملف Docx كـ PDF باستخدام Aspose.Words – دليل C# كامل](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | تعلّم كيفية حفظ ملفات Docx بصيغة PDF باستخدام Aspose.Words في C# مع شرح مفصل وأمثلة عملية. | | [تحويل Docx إلى بايت](./docx-to-byte/) | تعلّم كيفية تحويل ملفات Docx إلى مصفوفة بايت في .NET باستخدام Aspose.Words لمعالجة مستندات فعّالة. دليل خطوة بخطوة مُرفق. | | [تحويل Docx إلى Epub](./docx-to-epub/) حوّل ملفات DOCX إلى EPUB بسهولة باستخدام Aspose.Words لـ .NET. اتبع دليلنا التعليمي لدمجها بسلاسة في تطبيقات .NET. diff --git a/words/arabic/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/arabic/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index b65d775078..439b757b09 100644 --- a/words/arabic/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/arabic/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,22 @@ --- category: general -date: 2025-12-29 -description: كيفية تصدير LaTeX من Word باستخدام Aspose.Words – تعلم تحويل Word إلى - LaTeX، حفظ ملف docx كملف txt، ومعالجة المعادلات كنص عادي. +date: 2026-05-01 +description: تعلم كيفية تصدير LaTeX من ملف Word، وتحويل Word إلى txt، والحفاظ على + الجداول باستخدام Aspose.Words في C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: ar -og_description: كيفية تصدير LaTeX من Word باستخدام Aspose.Words. يوضح هذا الدليل كيفية - تحويل Word إلى LaTeX، وحفظ ملف docx كملف txt، والحفاظ على المعادلات دون تعديل. -og_title: كيفية تصدير LaTeX من Word – دليل C# سريع +og_description: اكتشف كيفية تصدير LaTeX من Word، وتحويل Word إلى نص عادي، والحفاظ + على تنسيق الجدول كما هو باستخدام Aspose.Words. +og_title: كيفية تصدير LaTeX من Word – دورة C# كاملة tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: كيفية تصدير LaTeX من Word – دليل خطوة بخطوة url: /ar/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,178 +26,215 @@ url: /ar/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# كيفية تصدير LaTeX من Word – دليل خطوة بخطوة +# كيفية تصدير LaTeX من Word – دليل C# كامل -هل تساءلت يومًا **كيف تصدر LaTeX من Word** دون فقدان أي من تلك المعادلات المعقدة في Office Math؟ لست وحدك. يواجه العديد من المطورين صعوبة عندما يحاولون *تحويل Word إلى LaTeX* للأوراق الأكاديمية، التقارير العلمية، أو خطوط النشر الآلية. +هل تساءلت يومًا **how to export LaTeX** من مستند Word دون فقدان أي من المعادلات الرياضية؟ لست وحدك. يحتاج العديد من المطورين إلى تحويل ملف .docx يحتوي على Office Math إلى LaTeX نظيف مع **convert Word to txt** للمعالجة اللاحقة. في هذا الدليل سنستعرض حلًا عمليًا جاهزًا للتنفيذ يحافظ على **preserves tables**، يمنحك ملف نصي عادي، ويحتفظ بترميز LaTeX تمامًا حيث تحتاجه. -في هذا الدرس سنستعرض مثالًا كاملًا وجاهزًا للتنفيذ بلغة C# يوضح **كيفية تصدير LaTeX** باستخدام Aspose.Words، ويشرح **كيفية حفظ ملفات txt** التي تحتوي على تنسيق LaTeX، ويغطي أيضًا تفاصيل **convert word equations latex** حتى لا يضيع شيء أثناء التحويل. +سنغطي كل شيء من تحميل الملف المصدر إلى تعديل `TxtSaveOptions` بحيث يكون الناتج قابلًا للقراءة من قبل الإنسان والآلة على حد سواء. بنهاية هذا الدليل ستكون قادرًا على **save docx as txt**, **convert Word to plain text**, وتعرف **how to preserve tables** أثناء التصدير. لا سكربتات خارجية، لا نسخ ولصق يدوي—فقط كود C# يمكنك وضعه في أي مشروع .NET. -> **نصيحة احترافية:** نفس النهج يعمل مع أي ملف .docx لديك—فقط وجه الكود إلى مسار ملف مختلف. +## ما ستحتاجه + +- **Aspose.Words for .NET** (أحدث نسخة، 2024.x أو أحدث). حزمة NuGet هي `Aspose.Words`. +- بيئة تطوير .NET (Visual Studio، VS Code، Rider—أي منها). +- ملف Word (`.docx`) يحتوي على معادلات Office Math وعلى الأقل جدول واحد (لرؤية سحر حفظ الجداول). + +هذا كل شيء. إذا كان لديك هذه المتطلبات، استمر في القراءة؛ وإلا قم بتحميل حزمة NuGet وعينة DOCX قبل المتابعة. --- -## ما ستحتاجه +## كيفية تصدير LaTeX من مستند Word -قبل أن نبدأ، تأكد من توفر المتطلبات التالية: +فيما يلي جوهر الدرس—ثلاث خطوات مختصرة تجيب على سؤال **how to export latex** وتتعامل أيضًا مع الأهداف الثانوية لـ **convert word to txt**, **convert word to plain text**, **save docx as txt**, و **how to preserve tables**. -| المتطلب | لماذا هو مهم | -|--------------|----------------| -| **.NET 6.0+** (أو .NET Framework 4.6+) | Aspose.Words يستهدف بيئات .NET الحديثة. | -| **حزمة NuGet Aspose.Words for .NET** (`Aspose.Words`) | المكتبة تقوم بالمعالجة الثقيلة لتحليل Word وإنتاج LaTeX. | -| **ملف .docx تجريبي** يحتوي على معادلة Office Math واحدة على الأقل | لتشاهد تحويل LaTeX عمليًا. | -| **Visual Studio 2022** (أو أي بيئة تطوير تفضلها) | يجعل من السهل تصحيح الأخطاء وتشغيل العينة. | +### الخطوة 1: تحميل ملف DOCX -إذا لم تقم بتثبيت حزمة NuGet بعد، نفّذ: +أولًا نحتاج إلى قراءة مستند Word إلى كائن `Aspose.Words.Document`. هذه الخطوة هي نفسها سواء كنت ستقوم بـ **convert word to txt** أو **save docx as txt** لاحقًا. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -هذا كل شيء—لا تحتاج إلى DLLs إضافية، ولا إلى COM interop، فقط مكتبة مُدارة نظيفة. +> **لماذا هذا مهم:** تحميل الملف ينشئ تمثيلًا في الذاكرة لجميع عناصر Word—الفقرات، الجداول، وكائنات Office Math. بدون هذا الكائن لا يمكنك تعديل خيارات التصدير. ---- +### الخطوة 2: ضبط `TxtSaveOptions` لـ LaTeX وتنسيق الجداول -## كيفية تصدير LaTeX من Word – نظرة عامة +فئة `TxtSaveOptions` تتيح لك التحكم بدقة في كيفية إنشاء ملف النص العادي. خاصيتان أساسيتان لسيناريونا: -إليك المخطط العام لما سننجزه: +| Property | What it does | Why you need it | +|----------|--------------|-----------------| +| `OfficeMathExportMode` | يحدد طريقة عرض Office Math. ضبطه على `LaTeX` يحول المعادلات إلى صيغة LaTeX. | هذا هو جوهر **how to export latex**. | +| `PreserveTableLayout` | عندما تكون `true`، يضيف Aspose مسافات بيضاء بحيث تحتفظ الجداول بمظهر شبكي. | هذا يحقق **how to preserve tables** أثناء **convert word to txt**. | -1. **تحميل** مستند Word المصدر (`.docx`). -2. **تهيئة** `TxtSaveOptions` بحيث يتم تصدير أي كائنات Office Math كرموز LaTeX. -3. **حفظ** المستند كملف نص عادي (`.txt`) يمكنك تمريره مباشرة إلى أي مُترجم LaTeX. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![مثال على تصدير LaTeX من Word](image.png "مثال على تصدير LaTeX من Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **نصيحة احترافية:** إذا كنت تحتاج فقط إلى LaTeX الخام دون أي تنسيق للجداول، اضبط `PreserveTableLayout` على `false`. يصبح الملف أصغر، لكنك تفقد إشارة الجدول البصرية. -## الخطوة 1: تحميل مستند Word +### الخطوة 3: حفظ المستند كنص عادي -أولًا، افتح ملف .docx الذي تريد تحويله. فئة `Document` تُجرد كل XML الداخلي، وتوفر لك نموذج كائن سهل الاستخدام. +الآن نكتب المستند إلى ملف `.txt` باستخدام الخيارات التي عرفناها. هذا السطر الواحد ينجز **convert word to plain text**, **save docx as txt**, وبالطبع **how to export latex** دفعة واحدة. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**لماذا هذا مهم:** -تحميل الملف مبكرًا يتيح لنا فحص محتوياته (مثل عدد المعادلات) قبل أن نقرر كيفية تسلسله. إذا كان الملف تالفًا، ستُطلق `Document` استثناءً واضحًا، مما يحفظك من مخرجات غامضة لاحقًا. +بعد انتهاء العملية، افتح `output.txt`. سترى: ---- +- مقاطع LaTeX مثل `\frac{a}{b}` لكل معادلة Office Math. +- جداول مُصوَّرة باستخدام أحرف `|` و `-`، مع الحفاظ على محاذاة الأعمدة. +- فقرات عادية كنص، جاهزة لأي محلل لاحق. -## الخطوة 2: تهيئة TxtSaveOptions لتصدير LaTeX +### مثال كامل يعمل -السحر يحدث داخل `TxtSaveOptions`. بتعيين `OfficeMathExportMode` إلى `LaTeX`، يتحول كل كائن Office Math إلى تمثيله المقابل في LaTeX. +نجمع كل ما سبق في برنامج مستقل يمكنك تجميعه وتشغيله اليوم: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**لماذا اخترنا هذه الإعدادات:** +**الناتج المتوقع** (مقتطف): -- `OfficeMathExportMode.LaTeX` هو الوضع الوحيد الذي يضمن ترجمة رياضية دقيقة. -- `PreserveTableLayout` يحافظ على مظهر الجداول كما هو في Word، وهو مفيد عندما تُدرج الناتج لاحقًا في بيئة LaTeX `tabular`. -- UTF‑8 يضمن بقاء الأحرف مثل “α”، “β”، أو “∑” عبر العملية. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -إذا احتجت يومًا **convert word to latex** بدون غلاف النص العادي، يمكنك التحويل إلى `SaveFormat.LaTeX` بدلاً من ذلك—نصيحة سريعة للسيناريوهات المتقدمة. +لاحظ كيف يحافظ الجدول على شبكته وتظهر المعادلة كـ LaTeX نظيف. هذا هو الحل المثالي عندما **convert word to txt** وتحتاج إلى تمثيل دقيق لكل من البنية والرياضيات. --- -## الخطوة 3: حفظ المستند كملف نصي +## نصائح لتحويل Word إلى TXT وحفظ الجداول -الآن نكتب النص الغني بـ LaTeX إلى القرص. يمكن لاحقًا إعادة تسمية ملف `.txt` إلى `.tex`، أو تمريره مباشرة إلى مُترجم LaTeX. +بينما يعمل نهج الثلاث خطوات في معظم الحالات، غالبًا ما تواجه المشاريع الواقعية تحديات. إليك بعض الاقتراحات العملية لجعل خط أنابيب **convert word to plain text** أكثر صلابة. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### استخدم ترميزًا موحدًا -// Save using the configured options -doc.Save(outputPath, txtOptions); +القيمة الافتراضية لـ `TxtSaveOptions` هي UTF‑8، والتي تدعم معظم الأحرف. إذا كنت تحتاج إلى صفحة ترميز مختلفة (مثلاً الأنظمة القديمة التي تتوقع Windows‑1252)، اضبط خاصية `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**ما ستجده في `output.txt`:** +### قص المسافات الزائدة -``` -\begin{equation} -E = mc^{2} -\end{equation} +الجداول ذات الأعمدة العديدة قد تولد أسطرًا طويلة. بعد الحفظ، قد ترغب في معالجة الملف لاحقًا لتقليص مسافات متعددة إلى تبويب واحد: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -جميع الفقرات الأخرى تظهر كنص عادي، بينما تُحاط أي معادلة Office Math ببيئة LaTeX `equation` (أو `inline` إذا كانت داخلية في Word). هذا يلبي متطلبات **convert word equations latex** بشكل مثالي. +### التعامل مع الجداول المتداخلة ---- +إذا كان ملف DOCX يحتوي على جداول داخل جداول، سيظل `PreserveTableLayout` يحافظ على الهرمية البصرية، لكن المسافات البادئة قد تبدو غريبة. حل سريع هو استبدال المسافات البادئة بعلامة مخصصة (مثل `>>`) حتى يتمكن المحللون اللاحقون من اكتشاف مستويات التداخل. -## الحالات الخاصة والأسئلة الشائعة +### معالجة دفعات متعددة من الملفات -| الحالة | ما الذي يجب فعله | -|-----------|------------| -| **لا توجد معادلات في المصدر** | لا يزال التحويل يعمل؛ ستحصل فقط على نص عادي. لا يُضاف أي كود LaTeX إضافي. | -| **مستندات كبيرة جدًا (>100 ميغابايت)** | فكر في تدفق الإخراج باستخدام `MemoryStream` لتقليل استهلاك الذاكرة. | -| **بنى رياضية غير مدعومة** | تغطي Aspose.Words 99 % من Office Math. للحالات النادرة، قد تحتاج إلى معالجة LaTeX يدويًا بعد التحويل. | -| **تحتاج ملف .tex بدلًا من .txt** | غيّر `outputPath` لينتهي بـ `.tex` واختياريًا اضبط `txtOptions.Encoding` إلى `Encoding.UTF8`. | -| **التشغيل على Linux/macOS** | الكود نفسه يعمل—فقط تأكد من أن مسارات الملفات تستخدم الشرطات المائلة للأمام أو `Path.Combine`. | +عندما تحتاج إلى **convert word to txt** لعشرات المستندات، ضع المنطق داخل حلقة: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +بهذه الطريقة يمكنك **save docx as txt** على نطاق واسع دون تدخل يدوي. -## ملخص سريع: كيفية حفظ TXT مع معادلات LaTeX +--- -1. **تحميل** ملف .docx (`Document`). -2. **تعيين** `OfficeMathExportMode = LaTeX` في `TxtSaveOptions`. -3. **حفظ** الملف (`doc.Save`) باستخدام هذه الخيارات. +## الأخطاء الشائعة وكيفية تجنبها -هذا هو سير العمل الكامل لـ **how to save txt** مع معادلات بصيغة LaTeX. +1. **نسيان وضع وضع تصدير LaTeX** – إذا نسيت ضبط `OfficeMathExportMode = OfficeMathExportMode.LaTeX`، ستعود المعادلات إلى نص عادي (مثل “Equation 1”). تأكد دائمًا من فحص كتلة الخيارات. +2. **فقدان تنسيق الجدول** – القيمة الافتراضية لـ `PreserveTableLayout` هي `false`. إذا ظهر الناتج كنص متكتل، ربما لم تقم بتفعيل العلامة. +3. **مسارات الملفات تحتوي على مسافات** – استخدام السلاسل الخام (`@"C:\My Folder\input.docx"`) يجنب مشاكل الهروب. وإلا ستحصل على استثناء `FileNotFoundException`. +4. **عدم توافق الإصدارات** – الإصدارات القديمة من Aspose.Words (< 21.9) لا تدعم `OfficeMathExportMode`. قم بالترقية إلى أحدث حزمة لضمان عمل **how to export latex**. +5. **أخطاء الترميز للأحرف غير ASCII** – إذا ظهرت رموز �، اضبط صراحةً `options.Encoding` إلى UTF‑8 أو صفحة الترميز المناسبة. --- -## إضافي: أتمتة التحويل لعدة ملفات +## توسيع الحل: من TXT إلى Markdown أو HTML -إذا كان لديك مجلد مليء بملفات Word، يمكنك تغليف المنطق السابق داخل حلقة بسيطة: +أحيانًا تحتاج إلى أكثر من نص عادي—ربما ملف Markdown لا يزال يحتوي على كتل LaTeX. يمكن استبدال `TxtSaveOptions` بـ `HtmlSaveOptions` أو `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -بهذا يمكنك **convert word to latex** دفعيًا—مثالي للمجموعات البحثية التي تستقبل عشرات المخطوطات يوميًا. +هذا التغيير الصغير يتيح لك الحصول على مخرجات شبيهة بـ **convert word to txt** مع الحفاظ على صيغة markdown التي تفضلها. --- -## الخاتمة +## الخلاصة + +استعرضنا إجابة كاملة وجاهزة للإنتاج على سؤال **how to export latex** من مستند Word، مع إظهار كيفية **convert word to txt**, **convert word to plain text**, **save docx as txt**, و **how to preserve tables**. النقاط الأساسية هي: -غطّينا **كيفية تصدير LaTeX من Word** خطوة بخطوة، وأظهرنا **كيفية حفظ ملفات txt** التي تحتفظ بكل معادلة Office Math، وحتى شرحنا لكيفية **convert word equations latex** دون فقدان الدقة. +- تحميل الـ DOCX باستخدام `Aspose.Words.Document`. +- ضبط `TxtSaveOptions.OfficeMathExportMode = LaTeX` و `PreserveTableLayout = true`. +- استدعاء `doc.Save(outputPath, options)` للحصول على ملف نصي غني بـ LaTeX. -بضع أسطر من C# ومكتبة Aspose.Words القوية تمكنك من تحويل أي .docx إلى نص جاهز لـ LaTeX، جاهز للإدراج في أوراق علمية، كتب دراسية، أو خطوط نشر آلية. +جرّبه على ملفاتك الخاصة، جرب تعديل الترميز، ولا تتردد في معالجة دفعات كاملة من المجلدات. إذا صادفت حالات خاصة—جداول متداخلة، أحرف غريبة، أو إصدارات قديمة من Aspose—ارجع إلى أقسام “النصائح” و“الأخطاء الشائعة” للحصول على حلول سريعة. -**ما الخطوة التالية؟** جرّب تمرير الـ `.txt` المُولد (أو أعد تسميته إلى `.tex`) إلى `pdflatex` أو `xelatex` لإنتاج PDF، أو است `SaveFormat.LaTeX` للحصول على ملف `.tex` مباشر. إذا أردت **save docx as txt** مع الحفاظ على التنسيق، جرب `PreserveTableLayout` وتخصيص معالجة فواصل الأسطر. +هل أنت مستعد للخطوة التالية؟ جرّب تحويل نفس الـ DOCX إلى Markdown، أو استخدم ملف `.txt` الناتج في مولّد مواقع ثابتة يعرض LaTeX على الويب. الاحتمالات لا حصر لها، والآن لديك أساس قوي لأي سير عمل **convert word to txt**. -هل لديك أسئلة حول الحالات الخاصة، الترخيص، أو تحسين الأداء؟ اترك تعليقًا أدناه—برمجة سعيدة! +برمجة سعيدة، ونتمنى أن تُترجم LaTeX بنجاح من المرة الأولى! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/arabic/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/arabic/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..5d5368d57c --- /dev/null +++ b/words/arabic/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-01 +description: احفظ مستند Word كملف PDF باستخدام Aspose.Words في C#. تعلم كيفية تحويل + docx إلى PDF، واكتشاف الخطوط المفقودة ومعالجة تحذيرات استبدال الخطوط بفعالية. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: ar +og_description: احفظ مستند Word كملف PDF باستخدام Aspose.Words. يوضح هذا الدليل خطوة + بخطوة كيفية تحويل ملف docx إلى PDF واكتشاف الخطوط المفقودة. +og_title: حفظ ملف Word كملف PDF باستخدام Aspose.Words – دليل كامل +tags: +- Aspose.Words +- C# +- PDF conversion +title: حفظ مستند Word كملف PDF باستخدام Aspose.Words – دليل كامل +url: /ar/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ Word كملف PDF باستخدام Aspose.Words – دليل كامل + +هل احتجت يومًا إلى **حفظ Word كملف PDF** مباشرة وتساءلت ما إذا كنت ستفتقد خطًا ما على الطريق؟ لست وحدك—المطورون يواجهون باستمرار صداع الخطوط المفقودة عند تحويل المستندات. في هذا الدليل سنستعرض حلًا عمليًا لا يقتصر فقط على **تحويل docx إلى pdf** بل أيضًا **اكتشاف الخطوط المفقودة** باستخدام تحذيرات استبدال الخطوط في Aspose.Words. + +سنغطي كل شيء من إعداد جامع التحذيرات إلى تفسير الناتج، بحيث في النهاية تعرف بالضبط كيف **تحفظ Word كملف PDF** دون مفاجآت. لا أدوات خارجية، لا إعدادات غامضة—فقط كود C# نظيف يمكنك إدراجه في أي مشروع .NET. + +## ما ستحتاجه + +- **Aspose.Words for .NET** (أحدث نسخة، مثلاً 24.10) – يمكنك الحصول عليها عبر NuGet (`Install-Package Aspose.Words`). +- بيئة تطوير .NET (Visual Studio، Rider، أو VS Code تعمل جيدًا). +- ملف DOCX تجريبي قد يحتوي على خطوط غير مثبتة على الجهاز الهدف. +هذا كل ما تحتاجه. إذا كان لديك هذه الأساسيات، فنحن جاهزون للغوص في التفاصيل. + +## حفظ Word كملف PDF – نظرة عامة خطوة بخطوة + +فيما يلي البرنامج الكامل القابل للتنفيذ. يمكنك نسخه ولصقه في مشروع تطبيق console والضغط على **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **نصيحة احترافية:** استبدل `YOUR_DIRECTORY` بمسار مطلق أو استخدم `Path.Combine(Environment.CurrentDirectory, "input.docx")` لمسار نسبي أكثر أمانًا. + +### لماذا نستخدم رد نداء التحذير (Warning Callback) + +يقوم Aspose.Words باستبدال الخطوط المفقودة صامتًا بخط احتياطي (عادةً Arial). بدون رد نداء لن تعرف أن الاستبدال حدث، مما قد يؤدي إلى تشوهات في تخطيط PDF الناتج. عبر ربط `IWarningCallback`، نحصل على قائمة واضحة برمجية بكل حدث خط مفقود—مثالية للتسجيل أو إبلاغ المستخدمين النهائيين. + +### اكتشاف الخطوط المفقودة – ما الذي يجب البحث عنه + +عند تشغيل البرنامج، أي خط مفقود سيظهر في سطر وحدة التحكم مشابهًا لـ: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +إذا كانت القائمة فارغة، تهانينا—عملية **حفظ Word كملف PDF** نجحت مع جميع الخطوط الأصلية محفوظة. + +## تحويل Docx إلى PDF – تخصيص المخرجات + +أحيانًا تحتاج إلى نسخة PDF محددة، جودة صورة معينة، أو مستوى توافق معين. يتيح لك Aspose.Words تعديل كائن `PdfSaveOptions` قبل استدعاء `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **لماذا هذا مهم:** إذا كنت تولد PDFs للأرشفة القانونية، فإن ضبط `PdfA1b` يضمن أن الملف يلتزم بالمعايير الصارمة. لا يزال التحويل نفسه يحترم رد نداء التحذير، لذا ستظل **تكتشف الخطوط المفقودة**. + +## استبدال خطوط Aspose Words – التعامل مع الحالات الخاصة + +### السيناريو 1: عدة خطوط مفقودة + +إذا كان المستند المصدر يستخدم عدة خطوط مخصصة، سيحتوي جامع التحذيرات على إدخال واحد لكل خط. يمكنك تجميعها: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### السيناريو 2: توفير مجلد خطوط احتياطي + +يمكن لـ Aspose.Words البحث في مجلدات إضافية عن الخطوط. اضبط خاصية `FontsFolder` على `FontSettings` قبل تحميل المستند: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +الآن سيحاول المكتبة أولاً البحث في مجلدك المخصص، مما يقلل من فرص الاستبدال غير المرغوب فيه. + +### السيناريو 3: تجاهل الاستبدالات + +إذا كنت تفضل فشل التحويل عندما يكون الخط مفقودًا (بدلاً من الاستبدال الصامت)، ارمِ استثناءً داخل رد النداء: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +هذا يجبرك على معالجة الخط المفقود قبل المتابعة—مفيد في خطوط CI حيث تكون الفشل الصامت غير مقبول. + +## مثال كامل من البداية إلى النهاية + +بجمع كل ما سبق، إليك نسخة مختصرة توضح **كيفية تحويل Word إلى PDF**، وتضبط خيارات PDF مخصصة، وتسجيل أي مشاكل في الخطوط: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**الناتج المتوقع في وحدة التحكم** (إذا كان خط Calibri مفقودًا): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +إذا لم تظهر أي تحذيرات، فإن عملية **حفظ Word كملف PDF** استخدمت نفس الخطوط تمامًا كما في ملف DOCX الأصلي. + +## ملخص بصري + +![مخطط سير عمل حفظ Word كملف PDF](https://example.com/diagram.png "مخطط سير عمل حفظ Word كملف PDF") + +*نص بديل للصورة:* **save word as pdf** workflow يُظهر التحميل، جمع التحذيرات، وإخراج PDF. + +## أسئلة شائعة وإجابات + +| السؤال | الجواب | +|----------|--------| +| **هل أحتاج إلى ترخيص لـ Aspose.Words؟** | ترخيص تجريبي مجاني يكفي للاختبار، لكن الاستخدام في الإنتاج يتطلب ترخيصًا مدفوعًا لإزالة علامة التقييم. | +| **هل سيعمل هذا على .NET Core / .NET 6+؟** | بالتأكيد—Aspose.Words يستهدف .NET Standard 2.0، لذا أي بيئة تشغيل .NET حديثة متوافقة. | +| **هل يمكنني تحويل عدة ملفات DOCX في حلقة؟** | نعم، فقط أنشئ كائن `Document` جديد لكل ملف وأعد استخدام نفس `WarningInfoCollector` إذا رغبت في تجميع النتائج. | +| **ماذا لو لم يكن مجلد الإخراج موجودًا؟** | `Document.Save` سيطرح استثناء `DirectoryNotFoundException`. أنشئ المجلد أولًا أو استخدم `Directory.CreateDirectory`. | +| **هل هناك طريقة لتضمين الخطوط المفقودة داخل PDF؟** | يمكن لـ Aspose.Words تضمين الخطوط تلقائيًا إذا كانت متوفرة على الجهاز؛ اضبط `PdfSaveOptions.EmbedFullFonts = true`. | + +## الخلاصة + +أصبح لديك الآن نمط جاهز للإنتاج **لحفظ Word كملف PDF** مع **اكتشاف الخطوط المفقودة** ومعالجة سيناريوهات **استبدال خطوط Aspose.Words**. عبر ربط رد نداء التحذير، تخصيص مجلدات الخطوط، وربما تعديل `PdfSaveOptions`، يمكنك تحويل docx إلى pdf بثقة وإبقاء مستخدميك على علم بأي مشاكل قد تؤثر على دقة التخطيط. + +هل أنت مستعد للخطوة التالية؟ جرّب توليد PDFs من مستندات متعددة بالتوازي، أو استكشف إضافة علامات مائية وتوقيعات رقمية—كلاهما توسيعات مباشرة للكود الذي تعلمته. برمجة سعيدة، ولتظل ملفات PDF الخاصة بك دائمًا كما تريد! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-loadoptions/_index.md b/words/arabic/net/programming-with-loadoptions/_index.md index 9cce38b1f5..ff5bd95c19 100644 --- a/words/arabic/net/programming-with-loadoptions/_index.md +++ b/words/arabic/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ | [كيفية استعادة ملف DOCX – ضبط وضع الاستعادة وفتح ملفات Word التالفة](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | تعلم كيفية ضبط وضع الاستعادة لفتح ملفات Word التالفة واستعادة مستندات DOCX باستخدام Aspose.Words لـ .NET. | | [كيفية استخدام LoadOptions في Aspose.Words – دليل شامل](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | دليل شامل يشرح كيفية استخدام LoadOptions في Aspose.Words لتحميل مستندات Word مع إعدادات مخصصة. | | [استعادة مستند تالف في C# – ضبط وضع الاستعادة وإظهار مطالبة للمستخدم](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | تعلّم كيفية استعادة مستند Word تالف باستخدام Aspose.Words في C# عبر ضبط وضع الاستعادة وإظهار مطالبة للمستخدم. | +| [استعادة ملف docx تالف – دليل كامل لتحميل ملفات Word التالفة في C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | تعلم خطوة بخطوة كيفية استعادة ملفات docx التالفة وتحميلها في C# باستخدام Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/arabic/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..4f8faef333 --- /dev/null +++ b/words/arabic/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: استعد ملفات docx التالفة بسرعة باستخدام Aspose.Words. تعلّم كيفية ضبط + وضع الاستعادة، تحميل ملفات docx بأمان، وقراءة ملفات Word التالفة في بضع خطوات فقط. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: ar +og_description: استعادة ملفات docx التالفة في C#. ضبط وضع الاسترداد، تحميل docx بأمان، + وقراءة ملفات Word التالفة باستخدام Aspose.Words. +og_title: استعادة ملف docx التالف – دليل C# السريع +tags: +- Aspose.Words +- C# +- Document Recovery +title: استعادة ملفات docx التالفة – دليل كامل لتحميل ملفات Word المتضررة في C# +url: /ar/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استعادة ملفات docx التالفة – دليل سريع C# + +هل حاولت فتح ملف Word لا يفتح أبداً وتساءلت إذا كان المحتوى قد فقد إلى الأبد؟ في العديد من المشاريع الواقعية ستقوم **recover corrupted docx** دون طلب إعادة إرسال المرفق من المستخدم. الخبر السار هو أن Aspose.Words يجعل الأمر سهلًا للغاية: ما عليك سوى ضبط وضع الاستعادة وترك المكتبة تتولى العمل الشاق. + +في هذا الدرس سنستعرض الخطوات الدقيقة لـ **recover corrupted docx**، نشرح لماذا خيار `RecoveryMode.AutoRecover` هو الأكثر أمانًا، ونظهر لك **how to load docx** التي قد تكون تالفة جزئيًا. في النهاية ستتمكن من قراءة ملف Word تالف، استخراج أي نص نجى، وحتى تسجيل الصيغة الأصلية للمراجعات المستقبلية. لا أدوات خارجية، فقط كود C# نظيف. + +## ما ستحتاجه + +- **Aspose.Words for .NET** (أي نسخة حديثة؛ الـ API الذي نستخدمه يعمل مع 23.5 وما فوق). +- بيئة تطوير .NET (Visual Studio، VS Code، أو Rider). +- ملف `.docx` التالف أو المتضرر جزئيًا الذي تريد إنقاذه. + +لا أذونات خاصة، لا COM interop، ولا حاجة لتثبيت Microsoft Office على الخادم. بسيط، أليس كذلك؟ + +## الخطوة 1: ضبط وضع الاستعادة على Auto‑Recover + +عند تلف ملف Word، السلوك الافتراضي للتحميل يرمي استثناءً ويتوقف. من خلال تكوين كائن `LoadOptions` تخبر Aspose.Words **set recovery mode** إلى `AutoRecover`، والذي يفحص حزمة zip، يتخطى الأجزاء غير القابلة للقراءة، ويعيد ما يمكن تجميعه. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **لماذا AutoRecover؟** +> يحاول قراءة أكبر قدر ممكن مع الحفاظ على قابلية استخدام كائن المستند. إذا اخترت `RecoveryMode.NoRecovery`، سيفشل التحميل عند أول فساد، مما يفسد هدف سيناريوهات **recover corrupted docx**. + +## الخطوة 2: تحميل المستند باستخدام الخيارات المكوَّنة + +الآن بعد ضبط وضع الاستعادة، يمكنك محاولة فتح الملف بأمان. استبدل `"YOUR_DIRECTORY/input.docx"` بالمسار الفعلي للملف التالف. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +إذا كان الملف تالفًا جزئيًا فقط، سيظل كائن `Document` يُنشأ. يمكنك فحص `document.IsStructureValid` لاحقًا إذا احتجت إلى تحقق إضافي. + +## الخطوة 3: التحقق من الصيغة المكتشفة + +Aspose.Words يكتشف تلقائيًا الصيغة الأصلية (DOC، DOCX، ODT، إلخ). طباعة هذه القيمة تساعدك على التأكد من أن المكتبة تعرفت على الملف بشكل صحيح، وهو فحص سريع بعد عملية **recover corrupted docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +الناتج النموذجي: + +``` +Loaded with Docx format. +``` + +حتى وإن كانت بعض الأجزاء مفقودة، يظل اكتشاف الصيغة ناجحًا—فوز آخر لعمليات **recover corrupted docx**. + +## الخطوة 4: استخراج ما يمكنك + +بعد تحميل المستند، يمكنك التعامل معه كأي ملف Word سليم. المثال التالي يختصر استخراج النص العادي ويكتب النتيجة إلى وحدة التحكم. هذا يوضح أنك تستطيع **read damaged word file** دون تعطل. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +إذا كان الملف الأصلي يحتوي على جداول أو صور تالفة، فستُحذف ببساطة من مخرجات النص. يبقى باقي المستند سليمًا. + +## الخطوة 5: حفظ نسخة نظيفة (اختياري) + +غالبًا ما ترغب في إعطاء المستخدم نسخة جديدة ونظيفة من الملف بعد الاستعادة. الحفظ بنفس الصيغة يضمن التوافق مع أي عمليات لاحقة. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +الآن لديك ملف **recover damaged docx** يمكنك إرفاقه بأمان في بريد إلكتروني أو تمريره إلى خدمة أخرى. + +## مثال عملي كامل + +نجمع كل ما سبق في برنامج جاهز للتنفيذ. الصقه في مشروع Console جديد، عدل مسارات الملفات، واضغط F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**الناتج المتوقع** (با افتراض أن الملف يحتوي على فقرة واحدة “Hello world!” وبعض XML التالف): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +لاحظ أن البرنامج لا يتعطل أبدًا—رغم أن الملف المصدر كان مكسورًا جزئيًا. هذه هي جوهر **recover corrupted docx** باستخدام Aspose.Words. + +## أسئلة شائعة وحالات خاصة + +### ماذا لو كان الملف غير قابل للقراءة تمامًا؟ + +حتى `AutoRecover` له حدود. إذا كان حاوية zip نفسها تالفة إلى حد لا يمكن إصلاحه، سيطرح Aspose.Words استثناء `CorruptedFileException`. في هذه الحالة قد تحتاج إلى أداة إصلاح zip من طرف ثالث قبل محاولة **recover corrupted docx** مرة أخرى. + +### هل يمكنني استعادة صيغ أخرى (مثل `.doc`، `.odt`)؟ + +بالتأكيد. نفس `LoadOptions` يعمل مع أي صيغة تدعمها Aspose.Words. فقط غيّر امتداد الملف وستكتشف المكتبة الصيغة الأصلية تلقائيًا. وهذا يعني أنك تستطيع أيضًا **recover damaged docx**‑like مثل ملفات `.doc` أو `.rtf` بنفس الكود. + +### كيف أتعامل مع المستندات الكبيرة دون تحميلها بالكامل في الذاكرة؟ + +لملفات بحجم عدة جيجابايت يمكنك تفعيل **load options** مثل `LoadOptions.LoadFormat` أو تدفق المستند صفحةً بصفحة. ومع ذلك، لا يزال خوارزمية الاستعادة تحتاج لقراءة الحزمة بالكامل، لذا توقع استهلاك ذاكرة أعلى للملفات التالفة الكبيرة. + +### هل هناك طريقة لمعرفة أي أجزاء فقدت؟ + +بعد التحميل، يمكنك فحص `document.GetChildNodes(NodeType.Any, true)` ومقارنة العدد مع القاعدة المتوقعة. الجداول أو الصور أو الرؤوس المفقودة ستغيب ببساطة من مجموعة العقد. هذا يتيح لك تسجيل ما تم **recover damaged docx** وإبلاغ المستخدم بدقة. + +## نصائح احترافية لاستعادة موثوقة + +- **تحقق من حجم ملف الإدخال** قبل التحميل؛ ملف بحجم صفر بايت سيفشل دائمًا. +- **سجل نتيجة `RecoveryMode`** عبر التقاط `DocumentLoadingException` وتخزين رسالة الاستثناء؛ غالبًا ما تحتوي على دلائل حول الأجزاء التي تم تخطيها. +- **نفّذ الاستعادة في خيط خلفي** إذا كنت تعالج التحميلات في خدمة ويب—هذا يحافظ على استجابة الطلب. +- **استخدم مجموعات تحقق** (مثل MD5) لتحديد ما إذا كان الملف المستعاد يختلف عن الأصلي؛ يمكنك حينها اتخاذ قرار الاحتفاظ بالإصدارين. + +## الخلاصة + +أظهرنا لك كيفية **recover corrupted docx** في C# عبر **setting recovery mode** إلى `AutoRecover`، تحميل المستند بأمان، استخراج أي نص يبقى، وحفظ نسخة نظيفة اختياريًا. هذه الطريقة تتيح لك **how to load docx** التي كانت سترمي استثناءات، وتوفر لك وسيلة موثوقة لــ **read damaged word file** دون أدوات خارجية. + +الخطوات التالية؟ جرّب استبدال `RecoveryMode.AutoRecover` بـ `RecoveryMode.NoRecovery` لتلاحظ الفرق، أو استكشف خصائص `LoadOptions` التي تتحكم في معالجة كلمات المرور واستبدال الخطوط. يمكنك أيضًا دمج روتين الاستعادة في API ASP.NET Core تستقبل تحميلات وتعيد ملفًا مُصلحًا—مثالي لأنابيب إدارة المستندات المؤسسية. + +هل لديك أسئلة إضافية حول استعادة مستندات Word، أو تريد رؤية كيفية **recover damaged docx** باستخدام ردود مخصصة؟ اترك تعليقًا أدناه، وتمنياتنا بالبرمجة السعيدة! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "استعادة مستند تالف – recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-markdownsaveoptions/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/_index.md index e4bfc46653..e0bd203eb4 100644 --- a/words/arabic/net/programming-with-markdownsaveoptions/_index.md +++ b/words/arabic/net/programming-with-markdownsaveoptions/_index.md @@ -41,9 +41,11 @@ ### [كيفية حفظ Markdown من DOCX – دليل خطوة بخطوة](./how-to-save-markdown-from-docx-step-by-step-guide/) ### [كيفية تصدير Markdown من DOCX – دليل كامل](./how-to-export-markdown-from-docx-complete-guide/) + ### [كيفية تصدير LaTeX من Word: تحويل DOCX إلى Markdown باستخدام Aspose](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) ### [تحويل Word إلى Markdown – تضمين الصور كـ Base64](./convert-word-to-markdown-embed-images-as-base64/) + ### [كيفية حفظ Markdown من Word – دليل C# كامل](./how-to-save-markdown-from-word-complete-c-guide/) ### [كيفية حفظ Markdown من Word – دليل كامل](./how-to-save-markdown-from-word-complete-guide/) @@ -58,6 +60,10 @@ ### [تحويل Word إلى Markdown في C# – دليل كامل مع استخراج الصور](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) +### [حفظ docx كـ markdown – تصدير معادلات Word إلى LaTeX باستخدام Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) + +### [تحميل الصور إلى السحابة عند تحويل Word إلى Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..d7d85abdba --- /dev/null +++ b/words/arabic/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-05-01 +description: احفظ ملف docx كـ markdown باستخدام Aspose.Words – تعرّف على تحويل Word إلى markdown، + وتصدير المعادلات إلى LaTeX، وضبط دقة الصور في markdown في سير عمل سلس واحد. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: ar +og_description: احفظ ملف docx كـ markdown باستخدام Aspose.Words. يوضح هذا الدرس كيفية + تحويل Word إلى markdown، وتصدير المعادلات إلى LaTeX، وتعيين دقة صور markdown. +og_title: حفظ ملف docx كـ markdown – دليل شامل لتصدير معادلات Word إلى LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: حفظ ملف docx كـ markdown – تصدير معادلات Word إلى LaTeX باستخدام Aspose.Words +url: /ar/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ docx كـ markdown – تصدير معادلات Word إلى LaTeX باستخدام Aspose.Words + +هل احتجت يوماً إلى **save docx as markdown** لكن واجهت صعوبة في الحفاظ على معادلات Office Math واضحة؟ لست وحدك. معظم المطورين يصطدمون بحائط عندما تقوم التحويلة الافتراضية بإسقاط المعادلات كصور ضبابية، مما يجبرهم على إعادة كتابة يدوية في LaTeX. + +خبر سار: Aspose.Words يمكنه القيام بالعمل الشاق نيابةً عنك. في هذا الدرس سنقوم **convert word to markdown**، ونخبر المحرك بـ **export equations to latex**، وحتى **set markdown image resolution** لبقية المستند. في النهاية ستحصل على أمر واحد ينتج ملف `.md` نظيف مع رياضيات جاهزة لـ LaTeX وصور عالية الدقة. + +## ما ستتعلمه + +- كيفية تحميل ملف `.docx` يحتوي على كائنات Office Math. +- ما هي خصائص `MarkdownSaveOptions` التي تتحكم في **export equations to latex** و **set markdown image resolution**. +- مقتطف C# كامل وقابل للتنفيذ يمكنك لصقه في أي مشروع .NET. +- نصائح لاستكشاف الأخطاء الشائعة، مثل الخطوط المفقودة أو ميزات المعادلات غير المدعومة. + +**المتطلبات المسبقة**: .NET 6+ (أو .NET Framework 4.6+)، رخصة لـ Aspose.Words for .NET، وإلمام أساسي بـ C#. إذا كنت مرتاحاً لإنشاء تطبيق console، فأنت جاهز للبدء. + +--- + +## الخطوة 1 – حفظ docx كـ markdown: تحميل ملف Word الخاص بك + +أول شيء نحتاجه هو كائن `Document` يشير إلى ملف `.docx` المصدر. فكر فيه كفتح الكتاب قبل أن تبدأ بنسخ الفصول. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*لماذا هذا مهم*: إذا لم يحتوي المستند على أي رياضيات، فإن خطوة **export equations to latex** ستكون بلا تأثير، لكن باقي التحويل سيستمر. هذا الفحص يحفظك من التساؤل لماذا ملف Markdown الناتج يفتقد كتل LaTeX. + +--- + +## الخطوة 2 – تكوين تصدير المعادلات إلى LaTeX + +Aspose.Words يتيح لك تحديد كيفية عرض Office Math. بشكل افتراضي يحولها إلى صور PNG، وهذا هو السبب في أن العديد من الدروس تنتهي بملف markdown ضبابي. تغيير `OfficeMathExportMode` إلى `LaTeX` يمنحك معادلات نظيفة جاهزة للنسخ واللصق. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*لماذا `OfficeMathExportMode.LaTeX`؟* LaTeX هي اللغة المشتركة للنشر العلمي. عندما تقوم لاحقاً بعرض markdown باستخدام مولد موقع ثابت أو دفتر Jupyter، ستظهر المعادلات واضحة عند أي مستوى تكبير. + +--- + +## الخطوة 3 – ضبط دقة صور Markdown (للمحتوى غير الرياضي) + +على الرغم من تركيزنا على الرياضيات، فإن معظم مستندات Word تحتوي أيضاً على صور، مخططات، أو SVG مدمجة. خاصية `ImageResolution` تتحكم في كيفية تحويل Aspose.Words لتلك الأصول إلى نقطية. قيمة **300 DPI** هي نقطة مثالية للشاشة والطباعة. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*نصيحة احترافية*: إذا كان markdown سيُعرض على الويب فقط، يمكنك خفضها إلى 150 DPI لتقليل حجم الملف. وعلى العكس، للملفات PDF الجاهزة للطباعة، ارتقِها إلى 600 DPI. + +--- + +## الخطوة 4 – تشغيل التحويل – تحويل Word Math إلى LaTeX + +الآن بعد أن تم تكوين كل شيء، التحويل الفعلي هو سطر واحد. Aspose.Words يقوم بالعمل الشاق خلف الكواليس. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**الناتج المتوقع**: افتح ملف `.md` المُولد وسترى شيئاً مثل: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +لاحظ كتل LaTeX (`$...$` و `$$...$$`) التي استبدلت مقتطفات PNG السابقة. الصورة في الأسفل لا تزال PNG، تم عرضها بدقة 300 DPI كما طلبنا. + +--- + +## الخطوة 5 – الحالات الخاصة الشائعة وكيفية التعامل معها + +| الحالة | ما يحدث | كيفية الإصلاح | +|-----------|--------------|------------| +| **Missing fonts** (مثلاً Cambria Math غير مثبت) | قد يحتوي ناتج LaTeX على رموز غير معروفة. | قم بتثبيت الخط المفقود على الخادم أو تضمينه في المستند قبل التحويل. | +| **Complex equations** (مصفوفة مع محددات مخصصة) | قد يلجأ Aspose.Words إلى صورة رغم وضع `LaTeX`. | قم بالترقية إلى أحدث إصدار من Aspose.Words؛ المكتبة تحسن باستمرار تغطية المعادلات. | +| **Large documents** ( > 50 MB ) | ضغط الذاكرة قد يسبب `OutOfMemoryException`. | استخدم `LoadOptions` مع `LoadFormat.Docx` وقم ببث الملف، أو قسّم المستند إلى أقسام قبل التحويل. | +| **Image size too big** | يصبح ملف Markdown كبيراً، مما يبطئ عمليات بناء المواقع الثابتة. | قلل `ImageResolution` إلى 150 DPI للسيناريوهات التي تُعرض على الويب فقط (انظر الخطوة 3). | + +--- + +## الخطوة 6 – جمع كل شيء معاً: مثال كامل يعمل + +فيما يلي برنامج التطبيق console *الكامل* الذي يمكنك نسخه‑ولصقه في `Program.cs`. يتضمن جميع الأجزاء التي ناقشناها، بالإضافة إلى بعض معالجة الأخطاء الإضافية. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +شغّل البرنامج (`dotnet run`) وستحصل على ملف markdown **save docx as markdown** مع الحفاظ على كل معادلة كـ LaTeX. لا نسخ‑لصق يدوي، ولا صور نقطية قبيحة للرياضيات. + +--- + +## الخلاصة + +لقد استعرضنا العملية الكاملة لـ **saving docx as markdown** باستخدام Aspose.Words، من تحميل ملف Word إلى تكوين **export equations to latex** و **set markdown image resolution**. المقتطف النهائي جاهز للإنتاج، ويمكنك إدراجه في أي مشروع .NET يحتاج إلى **convert word to markdown** مباشرة. + +ما التالي؟ جرّب إدخال ملف `.md` المُولد إلى مولد موقع ثابت مثل Hugo أو Jekyll وشاهد معادلاتك تُعرض بجمال. إذا احتجت إلى **convert word math latex** إلى صيغ أخرى (PDF، HTML)، فقط استبدل `MarkdownSaveOptions` بـ `PdfSaveOptions` أو `HtmlSaveOptions`—علامة `OfficeMathExportMode` نفسها تعمل عبرها. + +هل لديك تعديل في سير العمل، مثل سحب ملفات Word من Azure Blob storage أو بثها من API؟ النمط نفسه ينطبق؛ فقط استبدل مُنشئ `Document` القائم على نظام الملفات بواحد يعتمد على التدفق. + +لا تتردد في التجربة، وأخبرنا في التعليقات كيف حل هذا النهج مشكلات التحويل لديك. برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..3320a829c0 --- /dev/null +++ b/words/arabic/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-05-01 +description: قم بتحميل الصور إلى السحابة أثناء تحويل مستند Word إلى markdown. تعلم + كيفية استخراج الصور من ملف docx وتخزينها في Azure Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: ar +og_description: حمّل الصور إلى السحابة أثناء تحويل مستند Word إلى markdown. يوضح هذا + الدليل كيفية استخراج الصور من ملف docx وتخزينها في Azure Blob storage. +og_title: رفع الصور إلى السحابة عند تحويل Word إلى Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: رفع الصور إلى السحابة عند تحويل Word إلى Markdown +url: /ar/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# رفع الصور إلى السحابة عند تحويل Word إلى Markdown + +هل احتجت يومًا إلى **رفع الصور إلى السحابة** أثناء تحويل ملف Word إلى markdown؟ لست وحدك—المطورون يتعاملون باستمرار مع تحويل المستندات وإدارة الأصول، والقيام بالأمرين في تدفق سلس واحد قد يشعر كأنك تطارد هدفًا متحركًا. + +الأخبار السارة؟ باستخدام Aspose.Words يمكنك استخراج كل صورة، رسم بياني، أو مخطط من ملف .docx، وإرسالها مباشرة إلى Azure Blob Storage، والسماح للـ markdown المُولد بالإشارة إلى عناوين URL السحابية بدلاً من الملفات المحلية. في هذا البرنامج التعليمي سنستعرض العملية بالكامل، بدءًا من تحميل المستند المصدر وصولاً إلى الحصول على ملف markdown نظيف يشير إلى حاوية Azure الخاصة بك. + +بنهاية هذا الدليل ستكون قادرًا على **تحويل docx إلى markdown**، **استخراج الصور من docx**، و**تخزين الصور في Azure Blob**—كل ذلك ببضع أسطر فقط من C#. لا أدوات خارجية، لا نسخ‑لصق يدوي، وبالتأكيد لا روابط صور مكسورة. + +## ما ستحتاجه + +- **.NET 6.0** أو أحدث (الكود يعمل على .NET Core و .NET Framework أيضًا) +- **Aspose.Words for .NET** (حزمة NuGet `Aspose.Words`) +- حساب **Azure Storage** مع حاوية (مثال: `images`) ومفتاح وصول مشترك – ستحتاج إلى سلسلة الاتصال لتحميل الملفات. +- فهم أساسي لـ C# و async/await (اختياري لكنه مفيد). + +إذا كان لديك هذه المكونات بالفعل، رائع—لننتقل مباشرة إلى الحل. إذا لم يكن كذلك، سيشير قسم “المتطلبات المسبقة” في النهاية إلى خطوات إعداد سريعة. + +## الخطوة 1: إعداد مساعد Azure Blob (لماذا هو مهم) + +قبل أن نتعامل مع مستند Word، نحتاج إلى مساعد صغير يعرف كيفية إرسال مصفوفة بايت إلى Azure Blob Storage وإرجاع عنوان URL عام. هذه التجريدية تحافظ على نظافة منطق التحويل وتسهّل استبدال مزودي التخزين لاحقًا. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**لماذا هذا المساعد؟** +1. **فصل المسؤوليات** – يبقى كود تحويل markdown مركّزًا على معالجة المستند، وليس على تفاصيل HTTP. +2. **قابلية إعادة الاستخدام** – يمكنك استدعاء `UploadAsync` من أي مكان آخر في تطبيقك (مثال: للصور التي يرفعها المستخدم). +3. **التحضير للمستقبل** – استبدال Azure بـ Amazon S3 أو Google Cloud Storage يتطلب فقط تنفيذًا جديدًا لنفس الواجهة. + +> **نصيحة احترافية:** اضبط مستوى وصول الحاوية إلى `Blob` (عام) فقط إذا كنت لا تمانع في أن يقرأ أي شخص الصور. في السيناريوهات الخاصة، أنشئ رموز SAS لكل عملية رفع وضمّن تلك الروابط بدلاً من ذلك. + +## الخطوة 2: تعريف رد نداء حفظ الموارد (جوهر الرفع أثناء التحويل) + +يتيح لك Aspose.Words اعتراض كل مورد (صورة، رسم بياني، إلخ) كان سيُكتب عادةً إلى القرص عند حفظ المستند كـ markdown. من خلال توفير `ResourceSavingCallback`، يمكننا رفع كل مورد إلى Azure Blob واستبدال اسم الملف المحلي بعنوان URL السحابة. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**ما الذي يحدث هنا؟** + +- **استخراج** – Aspose.Words يزودنا بتدفق (stream) لكل صورة. +- **رفع** – نسلم ذلك التدفق إلى `AzureBlobUploader`. +- **استبدال** – كاتب markdown يتلقى عنوان URL العام ويكتبها في صيغة صورة markdown (`![](https://…)`). + +نظرًا لأننا عيّننا `args.AlreadyExists = true`، لا توجد ملفات مؤقتة تملأ نظام الملفات—عملية نظيفة ولا حالة لها مثالية للوظائف بدون خادم. + +## الخطوة 3: تكوين خيارات حفظ Markdown (ربط كل شيء معًا) + +الآن نقوم بدمج رد النداء في `MarkdownSaveOptions` الخاص بـ Aspose.Words. العلامات الحاسمة هي `ExportImagesAsBase64 = false` (للحصول على روابط خارجية) و `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**لماذا نُعطّل Base64؟** +عندما تكون `ExportImagesAsBase64` مفعلة، يقوم Aspose بدمج كل صورة مباشرةً في markdown كـ data URI. هذا يُفقد الهدف من **رفع الصور إلى السحابة** لأن ملف markdown يزداد حجماً وتظل الصور مخفية عن CDN. بإيقافها نحصل على روابط خارجية نظيفة تشير إلى Azure Blob—بالضبط ما يتوقعه مولد المواقع الثابتة الحديث. + +## الخطوة 4: جمع كل شيء معًا – تطبيق Console بسيط + +فيما يلي برنامج console كامل وجاهز للتنفيذ. استبدل القيم النائبة بسلسلة الاتصال الفعلية لـ Azure واسم الحاوية. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### الناتج المتوقع + +تشغيل البرنامج مع `sample.docx` الذي يحتوي على صورتين سيُنتج: + +- `output.md` يحتوي على صيغة صورة markdown مثل: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-pdfsaveoptions/_index.md b/words/arabic/net/programming-with-pdfsaveoptions/_index.md index 83737d8548..d7abc72e55 100644 --- a/words/arabic/net/programming-with-pdfsaveoptions/_index.md +++ b/words/arabic/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ | [إنشاء ملف PDF قابل للوصول في C# – دليل إمكانية الوصول إلى PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | تعلم كيفية إنشاء ملفات PDF قابلة للوصول وفق معايير WCAG باستخدام Aspose.Words لـ .NET في C# خطوة بخطوة. | | [إنشاء ملف PDF قابل للوصول من Word – دليل كامل](./create-accessible-pdf-from-word-complete-guide/) | تعلم كيفية إنشاء ملفات PDF قابلة للوصول من مستندات Word باستخدام Aspose.Words لـ .NET خطوة بخطوة. | | [إنشاء ملف PDF قابل للوصول – دليل خطوة بخطوة للامتثال لمعيار PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) |تعرف على كيفية إنشاء ملفات PDF قابلة للوصول وفقًا لمعيار PDF/UA باستخدام Aspose.Words لـ .NET من خلال دليل خطوة بخطوة. | +| [حفظ المستند كملف PDF باستخدام Aspose.Words – دليل C# كامل](./save-document-as-pdf-with-aspose-words-complete-c-guide/) |دليل شامل خطوة بخطوة لحفظ المستندات كملفات PDF باستخدام Aspose.Words في بيئة C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/arabic/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..5b61bb3745 --- /dev/null +++ b/words/arabic/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: تعلم كيفية حفظ المستند كملف PDF باستخدام Aspose.Words في C#. يغطي الدرس + أيضًا تحويل Word إلى PDF، وتصدير الرياضيات LaTeX، ومعالجة الخطوط المفقودة. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: ar +og_description: احفظ المستند بصيغة PDF بسهولة مع Aspose.Words. يوضح هذا الدليل أيضًا + كيفية تحويل Word إلى PDF، وتصدير الرياضيات بصيغة LaTeX، ومعالجة الخطوط المفقودة. +og_title: حفظ المستند كملف PDF باستخدام Aspose.Words – دليل C# الكامل +tags: +- Aspose.Words +- C# +- PDF generation +title: حفظ المستند كملف PDF باستخدام Aspose.Words – دليل C# الكامل +url: /ar/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ المستند كـ PDF باستخدام Aspose.Words – دليل C# الكامل + +هل تساءلت يومًا **كيفية حفظ المستند كـ pdf** مباشرةً من ملف Word دون فقدان ميزات إمكانية الوصول؟ لست وحدك—المطورون يطلبون باستمرار طريقة موثوقة لتحويل Word إلى PDF مع الحفاظ على المعادلات الرياضية ومعالجة الخطوط المفقودة بأناقة. + +في هذا الدرس سنستعرض حلًا خطوة بخطوة لا يقتصر فقط على **حفظ المستند كـ pdf** بل يُظهر أيضًا **convert word to pdf**، **export math latex**، و**handle missing fonts** باستخدام أحدث نسخة من Aspose.Words for .NET. في النهاية ستحصل على برنامج C# جاهز للتنفيذ ينتج ملفات متوافقة مع PDF/UA‑2، مثالية لتدقيق إمكانية الوصول. + +## ما الذي ستحتاجه + +- .NET 6 أو أحدث (الكود يعمل مع .NET Core و .NET Framework أيضًا) +- Aspose.Words for .NET 25.10 أو أحدث – يمكنك الحصول على نسخة تجريبية مجانية من موقع Aspose +- مستند Word بسيط (`input.docx`) يحتوي على شكل عائم واحد على الأقل ومعادلة رياضية (لرؤية ميزة **export‑math‑latex** قيد التنفيذ) +- Visual Studio 2022 (أو أي بيئة تطوير تفضلها) + +> **نصيحة احترافية:** إذا كنت تعمل على خط أنابيب CI/CD، أضف حزمة NuGet الخاصة بـ Aspose.Words إلى ملف المشروع: + +```xml + +``` + +الآن دعنا نغوص في الكود. + +## الخطوة 1: تحميل المستند المصدر مع الاسترداد التلقائي + +عند التعامل مع ملفات Word الواقعية قد تواجه أقسامًا تالفة أو موارد مفقودة. تمكين الاسترداد التلقائي يضمن أن عملية التحميل لا تُطلق استثناءً أبدًا. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**لماذا هذا مهم:** +`RecoveryMode.AutoRecover` يحمي خط الأنابيب الخاص بك من الانهيار عند إدخال غير صالح، وهو أمر مفيد بشكل خاص عندما **convert word to pdf** على نطاق واسع. + +## الخطوة 2: إعداد خيارات حفظ PDF لإمكانية وصول كاملة + +PDF/UA‑2 هو المعيار ISO للـ PDFs القابلة للوصول. من خلال تكوين بعض العلامات نحصل على ملف يمكن لقارئات الشاشة التنقل فيه، كما نتأكد من تصدير المعادلات الرياضية كـ LaTeX مخفي. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**نقاط رئيسية:** + +- **ExportFloatingShapesAsInlineTag** – يضمن أن PDF الناتج يحافظ على التخطيط الأصلي مع البقاء دلاليًا صحيحًا. +- **OfficeMathExportMode.LaTeX** – يلبي متطلبات **export math latex**، مما يسمح للأدوات اللاحقة باستخراج المعادلات إذا لزم الأمر. + +## الخطوة 3: التقاط التحذيرات (مثل الخطوط المفقودة) + +الخطوط المفقودة هي مصدر صداع شائع عند تحويل المستندات. يمكن لـ Aspose.Words الإبلاغ عن هذه المشكلات عبر `WarningCallback`. سنجمعها لتتمكن من تسجيلها أو اتخاذ إجراء لاحقًا. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**لماذا يهمك ذلك:** +إذا كان المصدر يستخدم خطًا غير مثبت على الخادم، سيتراجع PDF إلى خط افتراضي، مما قد يخل بالتخطيط. من خلال **handle missing fonts** يمكننا تنبيه المستخدم أو تضمين بديل. + +## الخطوة 4: حفظ المستند كـ PDF قابل للوصول + +الآن لحظة الحقيقة—تنفيذ التحويل فعليًا. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +إذا سارت الأمور بسلاسة، ستحصل على ملف PDF/UA‑2 يحتوي على LaTeX مخفي لكل معادلة وعلامات صحيحة للأشكال العائمة. + +## الخطوة 5: مراجعة التحذيرات المجمعة (اختياري لكن موصى به) + +بعد عملية الحفظ، يمكنك المرور على التحذيرات المجمعة وتسجيلها. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +قد يبدو الإخراج النموذجي هكذا: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +رؤية هذه الرسائل مبكرًا تساعدك على **handle missing fonts** قبل أن تؤثر على المستخدمين النهائيين. + +## مثال كامل يعمل + +بجمع كل ما سبق، إليك البرنامج الكامل الجاهز للتنفيذ. استبدل مسارات العناصر النائبة بمساراتك الخاصة. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**النتيجة المتوقعة:** +- `output.pdf` متوافق مع PDF/UA‑2. +- جميع الأشكال العائمة مُعلمة كرسوم توضيحية داخلية. +- كل كائن Office Math يظهر كـ LaTeX مخفي (يمكن رؤيته عند فحص بنية PDF). +- أي مشكلات متعلقة بالخطوط تُطبع على وحدة التحكم، مما يمنحك فرصة **handle missing fonts** قبل نشر الملف. + +![Diagram showing the flow from Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flow diagram for saving document as pdf") + +*نص بديل للصورة:* **مخطط يوضح كيفية حفظ المستند كـ pdf باستخدام Aspose.Words** + +## أسئلة شائعة وحالات خاصة + +### ماذا لو كنت تستخدم نسخة أقدم من Aspose.Words؟ + +تم تقديم العلامة `OfficeMathExportMode.LaTeX` في الإصدار 25.10. بالنسبة للإصدارات الأقدم لا يزال بإمكانك **convert word to pdf**، لكن الرياضيات ستُرسم كصورة بدلاً من تصديرها كـ LaTeX. قم بالترقية للحصول على أفضل إمكانية وصول. + +### هل يمكنني تضمين خطوط مخصصة لتجنب fallback؟ + +نعم. عيّن `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` قبل استدعاء `Save`. هذا يساعد أيضًا على **handle missing fonts** عن طريق إجبار PDF على احتواء الأحرف المطلوبة. + +### كيف أتحقق من توافق PDF/UA‑2؟ + +افتح الملف في Adobe Acrobat Pro → “Print Production” → “Preflight”. اختر ملف التعريف “PDF/A‑2b” أو “PDF/UA‑2”، سيُظهر Acrobat أي انتهاكات. + +### ماذا عن ملفات Word المحمية بكلمة مرور؟ + +حمّل المستند باستخدام `LoadOptions` التي تتضمن `Password`. مثال: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +بقية الخطوات تبقى دون تغيير. + +## الخلاصة + +غطينا كل ما تحتاجه لـ **save document as pdf** باستخدام Aspose.Words في C#. كما عرضنا كيف **convert word to pdf**، **export math latex**، و**handle missing fonts**—كل ذلك مع إنتاج ملف PDF/UA‑2 قابل للوصول. + +جرّب الكود، جرب إعدادات `PdfSaveOptions` المختلفة (مثل ضغط الصور، PDF/A‑2b)، ودمجه في خدمة معالجة المستندات الخاصة بك. إذا رغبت في التعمق أكثر، فكر في استكشاف مكتبة Aspose الخاصة بـ PDF للمعالجة اللاحقة أو التوقيعات الرقمية. + +هل لديك سيناريوهات أخرى ترغب في معالجتها؟ لا تتردد في ترك تعليق أو الاطلاع على أدلّتنا الأخرى حول **PDF manipulation**، **image extraction**، و**batch conversion**. برمجة سعيدة! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-shapes/_index.md b/words/arabic/net/programming-with-shapes/_index.md index ce51c2d4c9..1213d0a70d 100644 --- a/words/arabic/net/programming-with-shapes/_index.md +++ b/words/arabic/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ | [إنشاء شكل مستطيل في Word باستخدام C# – دليل خطوة بخطوة](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) |تعلم كيفية إنشاء شكل مستطيل في مستندات Word باستخدام C# من خلال دليل خطوة بخطوة. | | [دروس Aspose.Words للظل على الشكل – إضافة ظل إلى شكل Word باستخدام C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) |تعرف على كيفية إضافة ظل إلى شكل Word باستخدام Aspose.Words for .NET وC# من خلال دليل خطوة بخطوة. | | [إنشاء مستند Word فارغ مع شكل مستطيل مظلّل – دليل خطوة بخطوة](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | تعرّف على كيفية إنشاء مستند Word فارغ وإضافة شكل مستطيل مظلّل باستخدام Aspose.Words لـ .NET خطوة بخطوة. | +| [كيفية نقل الظل في Aspose.Words – دليل كامل C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | تعلم كيفية تحريك الظل في شكل Word باستخدام Aspose.Words وC# خطوة بخطوة. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/arabic/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..228d14647e --- /dev/null +++ b/words/arabic/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-01 +description: كيفية تحريك الظل على شكل في Aspose.Words باستخدام C#. تعلم إضافة الظل + إلى الشكل، تغيير الضبابية، ضبط الشفافية، وتدوير الظل في دقائق. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: ar +og_description: كيفية تحريك الظل على شكل في Aspose.Words باستخدام C#. يوضح هذا البرنامج + التعليمي كيفية إضافة ظل إلى الشكل، وتغيير الضبابية، وتعيين الشفافية، وتدوير الظل. +og_title: كيفية تحريك الظل في Aspose.Words – دليل C# الكامل +tags: +- Aspose.Words +- C# +- Document Automation +title: كيفية تحريك الظل في Aspose.Words – دليل C# الكامل +url: /ar/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية تحريك الظل في Aspose.Words – دليل C# كامل + +هل تساءلت يومًا **كيفية تحريك الظل** على شكل داخل مستند Word دون فتح Word يدويًا؟ في عملي اليومي، كثيرًا ما احتجت إلى تعديل ظل الشكل برمجيًا—سواء كان لتقرير مصقول أو قالب ديناميكي. الخبر السار؟ باستخدام Aspose.Words يمكنك القيام بذلك ببضع أسطر، وستتعلم أيضًا **إضافة ظل إلى الشكل**، **كيفية تغيير الضبابية**، **كيفية ضبط الشفافية**، و**كيفية تدوير الظل** في نفس العملية. + +في هذا الدرس سنستعرض سيناريو واقعي: تحميل ملف DOCX موجود يحتوي بالفعل على شكل، تعديل موضع الظل، نعومته، شفافيته، واتجاهه، ثم حفظ النتيجة. في النهاية ستحصل على مقتطف قابل لإعادة الاستخدام يمكنك إدراجه في أي مشروع .NET، وستفهم لماذا كل خاصية مهمة. + +## المتطلبات المسبقة – ما تحتاجه قبل البدء + +- **Aspose.Words for .NET** (الإصدار 23.12 أو أحدث). يمكنك الحصول عليه من NuGet باستخدام `Install-Package Aspose.Words`. +- بيئة تطوير .NET 6+ (Visual Studio، VS Code، Rider—أيا كان ما تفضله). +- ملف Word إدخال (`input.docx`) يحتوي بالفعل على شكل واحد على الأقل (مستطيل، دائرة، أو صورة يكفي). +- إلمام أساسي بصياغة C#—لا شيء معقد. + +إذا كان أي من هذه غير متوفر لديك، توقف لحظةً وقم بتثبيت المكتبة؛ باقي الدليل يفترض أن الحزمة مضافة بالفعل. + +## الخطوة 1: تحميل المستند والحصول على الشكل المستهدف – **كيفية تحريك الظل** تبدأ هنا + +أول ما نقوم به هو تحميل المستند المصدر وتحديد الشكل الذي نريد تعديل خصائصه. Aspose.Words يتعامل مع كل كائن (فقرات، جداول، أشكال) كعقدة في شجرة، لذا يمكننا الاستعلام عنها مباشرة. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **لماذا هذا مهم:** تحميل المستند مرة واحدة وإعادة استخدام نفس كائن `Document` يكون أكثر كفاءة. استدعاء `GetChild` آمن لأنه يُعيد `null` إذا كان الفهرس خارج النطاق، مما يتيح لنا التعامل مع الأشكال المفقودة بسلاسة. + +## الخطوة 2: تعديل نصف قطر الضبابية – إتقان **كيفية تغيير الضبابية** + +الظل الناعم يبدو احترافيًا، بينما الحافة الصلبة قد تبدو رخيصة. خاصية `BlurRadius` تتحكم في النعومة بالنقاط (1 pt ≈ 1/72 inch). لنرفعها إلى 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **نصيحة محترف:** الضبابية الافتراضية هي 0.5 pt. أي قيمة فوق 5 pt تكون ملحوظة عادةً، لكن احذر من جعلها كبيرة جدًا—فقد يجعل الشكل يبدو منفصلًا عن الصفحة. + +## الخطوة 3: ضبط الشفافية – الجواب على **كيفية ضبط الشفافية** + +الشفافية تحدد مدى شفافية الظل. القيمة `0` تعني غير شفاف تمامًا؛ `1` تعني غير مرئي تمامًا. لتأثير خفيف سنستخدم `0.3` (30 % شفاف). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **لماذا قد يهمك ذلك:** إذا كان الشكل داكنًا، ظل غير شفاف بالكامل قد يغطي النص الموجود تحته. ضبط الشفافية يحافظ على قابلية القراءة مع إضفاء العمق. + +## الخطوة 4: تحريك الظل – جوهر **كيفية تحريك الظل** + +خاصية `Distance` تحدد المسافة التي يُزاح الظل فيها عن الشكل، مقاسة بالنقاط. كلما زادت المسافة، يبتعد الظل أكثر، مما يخلق تأثيرًا أكثر دراماتيكية. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **ماذا لو احتجت إزاحة طفيفة؟** ضبط `Distance` إلى `0` يجعل الظل يجلس مباشرة خلف الشكل، وهو مفيد لتأثيرات النقش. + +## الخطوة 5: تدوير مصدر الضوء – حل **كيفية تدوير الظل** + +الظلال ليست دائمًا مباشرة إلى الأسفل؛ فهي تتبع زاوية مصدر الضوء. خاصية `Angle` (بالدرجات) تدور الظل حول الشكل. لنميله 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **تجربة سريعة:** جرّب `90` للحصول على ظل يمين أو `-30` لظل يميل إلى اليسار. التغيير البصري يكون فوريًا. + +## الخطوة 6: حفظ المستند – رؤية نتيجة **إضافة ظل إلى الشكل** + +الآن بعد أن عدلنا الظل، سنكتب المستند مرة أخرى إلى القرص. يمكنك استبدال الملف الأصلي أو إنشاء ملف جديد؛ المثال يستخدم ملف إخراج جديد. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **الناتج المتوقع:** افتح `output.docx`. سيظهر ظل الشكل أكثر نعومة، مع إزاحة طفيفة، شبه شفاف، ومائل بزاوية 45°. إذا قارنت بينه وبين `input.docx`، الفرق واضح ولا يمكن إنكاره. + +### مثال كامل يعمل (جاهز للنسخ واللصق) + +فيما يلي البرنامج بالكامل في كتلة واحدة. الصقه في مشروع Console جديد، استبدل `YOUR_DIRECTORY` بمسار مجلد فعلي، ثم شغّله. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## أسئلة شائعة وحالات حافة + +### ماذا لو كان المستند يحتوي على أشكال متعددة؟ + +يمكنك التكرار عبر جميع الأشكال: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### هل يمكنني إضافة ظل إلى شكل لا يحتوي على ظل حاليًا؟ + +بالطبع. كائن `ShadowFormat` موجود دائمًا؛ كل ما عليك هو تفعيله: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### هل يعمل هذا مع الصور وSmartArt؟ + +نعم. أي عقدة تُشتق من `Shape`—بما في ذلك الصور، المخططات، وSmartArt—تُظهر `ShadowFormat`. نفس الخصائص تنطبق. + +### كيف أتحكم في لون الظل؟ + +استخدم خاصية `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### مخاوف التوافق؟ + +Aspose.Words 23.12+ يدعم .NET 6، .NET Core 3.1، و .NET Framework 4.6.2+. الـ API المعروض ثابت عبر هذه الإصدارات. + +## الخلاصة + +لقد غطينا للتو **كيفية تحريك الظل** على شكل باستخدام Aspose.Words، وخلال ذلك أظهرنا أيضًا **إضافة ظل إلى الشكل**، **كيفية تغيير الضبابية**، **كيفية ضبط الشفافية**، و**كيفية تدوير الظل**. المثال الكامل القابل للتنفيذ يتيح لك تعديل ظل أي شكل في ثوانٍ معدودة، مما يمنح مستنداتك مظهرًا مصقولًا واحترافيًا دون الحاجة لفتح Word. + +هل أنت مستعد للخطوة التالية؟ جرّب دمج هذه التعديلات مع **التنسيق الشرطي**—على سبيل المثال، تطبيق ظل أعمق فقط على العناوين أو على المخططات التي تتجاوز حجمًا معينًا. أو استكشف **تعبئات التدرج** للشكل نفسه لإنشاء تصميم جذاب حقًا. + +إذا واجهت أي صعوبات، اترك تعليقًا أدناه. برمجة سعيدة، ولتسقط ظلالك دائمًا حيث تريدها! + +![مخطط يوضح تأثير تحريك الظل على شكل – مثال على كيفية تحريك الظل](https://example.com/images/shadow-demo.png "مثال على كيفية تحريك الظل") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/basic-conversions/_index.md b/words/chinese/net/basic-conversions/_index.md index 5b0e5a83f1..a086bb4390 100644 --- a/words/chinese/net/basic-conversions/_index.md +++ b/words/chinese/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [如何从 Word 导出 LaTeX – 步骤指南](./how-to-export-latex-from-word-step-by-step-guide/) | 学习如何使用 Aspose.Words for .NET 将 Word 文档导出为 LaTeX,提供分步指南和代码示例,帮助开发者实现文档转换。| | [使用 Aspose.Words 将 Word 转换为 PDF(C#)指南](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Word 文档转换为 PDF,提供分步指南和代码示例。| | [使用 Aspose.Words 将 Word 保存为 PDF – 完整 C# 指南](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Word 文档保存为 PDF,提供完整的分步指南和代码示例。| +| [使用 Aspose.Words 将 Word 保存为 PDF – 完整指南](./save-word-as-pdf-with-aspose-words-complete-guide/) | 学习如何使用 Aspose.Words for .NET 将 Word 文档保存为 PDF,提供完整的分步指南和代码示例。| | [使用 Aspose.Words 将 Docx 保存为 PDF – 完整 C# 指南](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Docx 文档保存为 PDF,提供完整的分步指南和代码示例。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/chinese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index dd865a6513..9b0067dc42 100644 --- a/words/chinese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/chinese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,24 +1,22 @@ --- category: general -date: 2025-12-29 -description: 如何使用 Aspose.Words 从 Word 导出 LaTeX —— 学习将 Word 转换为 LaTeX、将 docx 保存为 txt,以及在纯文本中处理公式。 +date: 2026-05-01 +description: 学习如何使用 Aspose.Words 在 C# 中从 Word 文件导出 LaTeX、将 Word 转换为 txt,并保留表格。 draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: zh -og_description: 如何使用 Aspose.Words 将 Word 导出为 LaTeX。本指南展示了如何将 Word 转换为 LaTeX,将 docx - 保存为 txt,并保持公式完整。 -og_title: 如何从 Word 导出 LaTeX – 快速 C# 教程 +og_description: 了解如何使用 Aspose.Words 将 Word 导出为 LaTeX、将 Word 转换为纯文本,并保持表格布局完整。 +og_title: 如何从 Word 导出 LaTeX – 完整的 C# 教程 tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: 如何从 Word 导出 LaTeX – 步骤指南 +title: 如何从 Word 导出 LaTeX——一步一步指南 url: /zh/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -26,160 +24,215 @@ url: /zh/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# 如何从 Word 导出 LaTeX – 步骤指南 +# 如何从 Word 导出 LaTeX – 完整 C# 教程 -是否曾经想过 **如何从 Word 导出 LaTeX** 而不丢失那些棘手的 Office Math 方程式?你并不是唯一的。许多开发者在尝试将 *Word 转换为 LaTeX* 用于学术论文、科学报告或自动化出版流水线时会遇到瓶颈。 +是否曾经想过 **如何从 Word 文档导出 LaTeX**,而且不丢失任何数学公式?你并不孤单。许多开发者需要将包含 Office Math 的 .docx 转换为干净的 LaTeX,同时 **将 Word 转换为 txt** 以便后续处理。在本指南中,我们将一步步演示一个实用、可直接运行的解决方案,**保留表格**、生成纯文本文件,并且让 LaTeX 标记恰好出现在需要的位置。 -在本教程中,我们将逐步演示一个完整、可直接运行的 C# 示例,展示如何使用 Aspose.Words **导出 LaTeX**,解释 **如何保存 txt** 带有 LaTeX 标记的文件,并且涵盖 **convert equations latex** 的细微差别,确保翻译过程中不丢失任何内容。 +我们会从加载源文件讲起,直到微调 `TxtSaveOptions`,让输出既可读又易于机器处理。结束后,你将能够 **将 docx 保存为 txt**、**将 Word 转换为纯文本**,并且了解 **如何在导出时保留表格**。无需外部脚本、手动复制粘贴——只需一段纯 C# 代码,随时可以放入任意 .NET 项目中。 -> **小贴士:** 同样的方法适用于任何 .docx 文件——只需将代码指向不同的文件路径即可。 +## 你需要准备的东西 ---- - -## 您需要的条件 - -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words 针对现代 .NET 运行时。 | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | 该库负责解析 Word 并生成 LaTeX 的繁重工作。 | -| **A sample .docx** containing at least one Office Math equation | 用于实际查看 LaTeX 转换效果。 | -| **Visual Studio 2022** (or any IDE you like) | 使调试和运行示例变得非常简单。 | - -如果您尚未安装 NuGet 包,请运行: - -```bash -dotnet add package Aspose.Words -``` - -就是这样——无需额外的 DLL、无需 COM 互操作,只需一个干净的托管库。 +- **Aspose.Words for .NET**(最新版本,2024.x 或更高)。NuGet 包名为 `Aspose.Words`。 +- 一个 .NET 开发环境(Visual Studio、VS Code、Rider——任选其一)。 +- 一个包含 Office Math 公式且至少有一个表格的 Word 文件(`.docx`),用于演示表格保留的效果。 -## 如何从 Word 导出 LaTeX – 概览 +就这些。如果你已经具备上述条件,继续阅读;否则先获取 NuGet 包并准备好示例 DOCX 再深入。 -下面是我们将要完成的整体概览: +--- -1. **加载**源 Word 文档(`.docx`)。 -2. **配置** `TxtSaveOptions`,使所有 Office Math 对象以 LaTeX 代码形式输出。 -3. **保存**文档为纯文本(`.txt`)文件,您可以直接将其输入任意 LaTeX 编译器。 +## 如何从 Word 文档导出 LaTeX -![如何从 Word 导出 LaTeX 示例](image.png "如何从 Word 导出 LaTeX 示例") +下面是本教程的核心——三个简洁步骤,回答 **如何导出 latex** 的同时,也实现 **将 word 转换为 txt**、**将 word 转换为纯文本**、**将 docx 保存为 txt**,以及 **如何保留表格** 的需求。 -## 步骤 1:加载 Word 文档 +### 步骤 1:加载 DOCX 文件 -首先——打开您想要转换的 .docx。`Document` 类抽象了所有底层 XML,为您提供友好的对象模型。 +首先需要将 Word 文档读取到 `Aspose.Words.Document` 对象中。无论后面是 **将 word 转换为 txt** 还是 **将 docx 保存为 txt**,这一步都是相同的。 ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**为什么这很重要:** -提前加载文件可以让我们检查其内容(例如,统计方程数量),再决定如何序列化。如果文件损坏,`Document` 将抛出明确的异常,避免后续出现神秘的输出。 +> **为什么重要:** 加载文件会在内存中创建 Word 所有元素的表示——段落、表格以及 Office Math 对象。没有这个对象,就无法对导出选项进行操作。 + +### 步骤 2:为 LaTeX 与表格布局配置 `TxtSaveOptions` -## 步骤 2:为 LaTeX 导出配置 TxtSaveOptions +`TxtSaveOptions` 类让你精确控制纯文本文件的生成方式。以下两个属性是本场景的关键: -`TxtSaveOptions` 中实现了魔法。将 `OfficeMathExportMode` 设置为 `LaTeX`,每个 Office Math 对象都会转换为相应的 LaTeX 表示。 +| 属性 | 作用 | 为何需要 | +|------|------|----------| +| `OfficeMathExportMode` | 决定 Office Math 的渲染方式。设为 `LaTeX` 可将公式转换为 LaTeX 语法。 | 这正是 **如何导出 latex** 的核心。 | +| `PreserveTableLayout` | 为 `true` 时,Aspose 会添加空白,使表格保持网格状外观。 | 这满足 **如何保留表格**,同时实现 **将 word 转换为 txt** 的需求。 | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**为什么选择这些设置:** +> **小技巧:** 如果只需要原始 LaTeX 而不需要表格格式,可将 `PreserveTableLayout` 设为 `false`。文件会更小,但会失去可视化的表格提示。 -- `OfficeMathExportMode.LaTeX` 是唯一能保证数学表达忠实翻译的模式。 -- `PreserveTableLayout` 保持表格在 Word 中的外观,这在您后续将输出嵌入 LaTeX `tabular` 环境时非常方便。 -- UTF‑8 确保诸如 “α”、 “β” 或 “∑” 等字符在往返过程中得以保留。 +### 步骤 3:将文档保存为纯文本 -如果您需要在没有纯文本包装的情况下 **convert word to latex**,可以改为使用 `SaveFormat.LaTeX`——这是面向高级场景的一个小技巧。 +现在使用刚才定义的选项将文档写入 `.txt` 文件。仅一行代码即可一次性完成 **将 word 转换为纯文本**、**将 docx 保存为 txt**,以及 **如何导出 latex**。 -## 步骤 3:将文档保存为文本文件 +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -现在我们将富含 LaTeX 的文本写入磁盘。生成的 `.txt` 文件以后可以重命名为 `.tex`,或直接管道输送到 LaTeX 编译器。 +doc.Save(outputPath, saveOptions); +``` -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +调用完成后,打开 `output.txt`,你会看到: -// Save using the configured options -doc.Save(outputPath, txtOptions); +- 每个 Office Math 公式都以 `\frac{a}{b}` 等 LaTeX 片段呈现。 +- 表格使用 `|` 与 `-` 字符绘制,保持列对齐。 +- 普通段落以纯文本形式出现,随时可供下游解析器使用。 -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +### 完整示例 + +将上述步骤整合在一起,下面是一个可以直接编译运行的完整程序: + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**您将在 `output.txt` 中看到的内容:** +**预期输出**(摘录): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -所有其他段落以纯文本形式出现,而任何 Office Math 方程式都会被包装在 LaTeX `equation` 环境中(如果在 Word 中是行内的,则使用 `inline`)。这完美满足了 **convert word equations latex** 的需求。 +可以看到表格保持了网格,公式以干净的 LaTeX 显示。这正是 **将 word 转换为 txt** 时,同时保留结构与数学表达的理想效果。 -## 边缘情况与常见问题 +--- -| Situation | What to do | -|-----------|------------| -| **No equations in the source** | 转换仍然有效;您只会得到纯文本。不会添加额外的 LaTeX 代码。 | -| **Very large documents (>100 MB)** | 考虑使用 `MemoryStream` 流式输出,以避免高内存占用。 | -| **Unsupported Math constructs** | Aspose.Words 覆盖了 99% 的 Office Math。对于极少数的边缘情况,您可能需要手动后处理 LaTeX。 | -| **Need a .tex file instead of .txt** | 将 `outputPath` 改为以 `.tex` 结尾,并可选地将 `txtOptions.Encoding` 设置为 `Encoding.UTF8`。 | -| **Running on Linux/macOS** | 相同的代码可运行——只需确保文件使用正斜杠或 `Path.Combine`。 | +## 将 Word 转换为 TXT 并保留表格的技巧 -## 如何保存带有 LaTeX 方程的 TXT – 快速回顾 +虽然三步法能满足大多数场景,实际项目中常会遇到各种“坑”。下面提供一些实用建议,让你的 **将 word 转换为纯文本** 流程更稳健。 -1. **加载** .docx(`Document`)。 -2. **设置** `TxtSaveOptions` 中的 `OfficeMathExportMode = LaTeX`。 -3. **保存**文件(`doc.Save`)并使用这些选项。 +### 使用统一的编码 -这就是完整的工作流,用于 **how to save txt** 包含 LaTeX 格式方程的文件。 +`TxtSaveOptions` 默认采用 UTF‑8,能够处理大多数字符。如果需要其他代码页(例如旧系统要求的 Windows‑1252),请设置 `Encoding` 属性: -## 额外:批量自动转换多个文件 +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -如果您有一个包含大量 Word 文档的文件夹,只需将上述逻辑包装在一个简单的循环中: +### 去除多余空格 + +列数较多的表格会生成很长的行。保存后,你可能想把连续空格压缩为单个制表符: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### 处理嵌套表格 + +如果 DOCX 中出现表格套表格,`PreserveTableLayout` 仍会保留视觉层级,但缩进可能显得怪异。快速解决办法是将前导空格替换为自定义标记(如 `>>`),让下游解析器能够识别嵌套层级。 - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +### 批量处理多个文件 + +当需要对数十个文档执行 **将 word 转换为 txt** 时,可将逻辑放入循环: + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -现在您可以批量 **convert word to latex**——这对每天收到数十篇手稿的研究团队非常合适。 +这样就能 **将 docx 保存为 txt** 批量完成,无需手动干预。 + +--- + +## 常见错误及规避方法 + +1. **忘记设置 LaTeX 导出模式** – 若未将 `OfficeMathExportMode = OfficeMathExportMode.LaTeX`,公式会回退为普通文本(如 “Equation 1”)。务必检查选项块。 +2. **表格布局丢失** – `PreserveTableLayout` 的默认值是 `false`。如果输出看起来像一大段文字,可能是该标志未打开。 +3. **文件路径含空格** – 使用原始字符串(`@"C:\My Folder\input.docx"`)可避免转义问题,否则会抛出 `FileNotFoundException`。 +4. **版本不匹配** – 低于 21.9 的 Aspose.Words 版本不支持 `OfficeMathExportMode`。请升级到最新包,以确保 **如何导出 latex** 正常工作。 +5. **非 ASCII 字符编码错误** – 若出现 � 符号,请显式将 `options.Encoding` 设置为 UTF‑8 或相应代码页。 + +--- + +## 拓展:从 TXT 到 Markdown 或 HTML + +有时你需要的不止纯文本——比如希望得到包含 LaTeX 块的 Markdown 文件。只需将 `TxtSaveOptions` 替换为 `HtmlSaveOptions` 或 `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +这一个小改动,就能让你得到 **类似 txt 的输出**,同时保留你喜爱的 Markdown 语法。 + +--- ## 结论 -我们已经逐步介绍了 **how to export LaTeX from Word**,演示了 **how to save txt** 能保留每个 Office Math 方程的文件,并且展示了如何 **convert word equations latex** 而不失真。 +我们已经完整演示了如何 **从 Word 导出 latex**,并同步实现 **将 word 转换为 txt**、**将 word 转换为纯文本**、**将 docx 保存为 txt**、以及 **如何保留表格**。关键要点如下: + +- 使用 `Aspose.Words.Document` 加载 DOCX。 +- 将 `TxtSaveOptions.OfficeMathExportMode = LaTeX` 并将 `PreserveTableLayout = true`。 +- 调用 `doc.Save(outputPath, options)`,即可得到包含 LaTeX 的干净纯文本文件。 -只需几行 C# 代码和强大的 Aspose.Words 库,您就可以将任何 .docx 转换为可直接用于科学论文、教材或自动化出版流水线的 LaTeX 文本。 +请在自己的文件上试一试,调整编码设置,甚至批量处理整个文件夹。如果遇到嵌套表格、特殊字符或旧版 Aspose 等边缘情况,回顾 “技巧” 与 “常见错误” 部分即可快速解决。 -**接下来怎么办?** 试着将生成的 `.txt`(或将其重命名为 `.tex`)输入 `pdflatex` 或 `xelatex` 生成 PDF,或探索 `SaveFormat.LaTeX` 选项以直接得到 `.tex` 文件。如果您需要 **save docx as txt** 并保留格式,请尝试 `PreserveTableLayout` 和自定义换行处理。 +准备好下一步了吗?尝试将同一 DOCX 转为 Markdown,或将生成的 `.txt` 输入静态站点生成器,让网页渲染 LaTeX。可能性无限,而你已经拥有了坚实的 **将 word 转换为 txt** 工作流基础。 -对边缘情况、授权或性能调优有疑问?在下方留言——祝编码愉快! +祝编码愉快,愿你的 LaTeX 首次编译即成功! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/chinese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/chinese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..a85796fe21 --- /dev/null +++ b/words/chinese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 在 C# 中将 Word 保存为 PDF。学习将 docx 转换为 PDF,检测缺失字体并高效处理字体替换警告。 +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: zh +og_description: 使用 Aspose.Words 将 Word 保存为 PDF。本分步教程展示了如何将 docx 转换为 PDF 并检测缺失的字体。 +og_title: 使用 Aspose.Words 将 Word 保存为 PDF – 完整指南 +tags: +- Aspose.Words +- C# +- PDF conversion +title: 使用 Aspose.Words 将 Word 保存为 PDF – 完全指南 +url: /zh/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.Words 将 Word 保存为 PDF – 完整指南 + +是否曾经需要即时 **save Word as PDF** 并且担心会缺少字体?你并不孤单——开发者在转换文档时经常会遇到缺失字体的麻烦。在本指南中,我们将演示一个实用的解决方案,它不仅能够 **convert docx to pdf**,还能使用 Aspose.Words 的字体替换警告 **detect missing fonts**。 + +我们将涵盖从设置警告收集器到解释输出的全部内容,最终你将准确了解如何 **save Word as PDF** 而不出现意外。无需外部工具,无需晦涩设置——只需干净的 C# 代码,直接放入任何 .NET 项目中即可。 + +## 您需要的条件 + +- **Aspose.Words for .NET**(最新版本,例如 24.10)– 你可以通过 NuGet 获取(`Install-Package Aspose.Words`)。 +- .NET 开发环境(Visual Studio、Rider 或 VS Code 都可以)。 +- 一个可能包含目标机器未安装字体的示例 DOCX 文件。 +就是这样。如果你已经具备这些基础,我们就可以开始深入探讨。 + +## 将 Word 保存为 PDF – 步骤概览 + +下面是完整的可运行程序。随意将其复制粘贴到控制台应用项目中并按 **F5** 运行。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **技巧提示:** 将 `YOUR_DIRECTORY` 替换为绝对路径,或使用 `Path.Combine(Environment.CurrentDirectory, "input.docx")` 以获得相对的、更安全的方式。 + +### 为什么使用警告回调 + +Aspose.Words 会悄悄地将缺失的字体替换为回退字体(通常是 Arial)。如果没有回调,你永远不会知道发生了替换,这可能导致生成的 PDF 出现布局错误。通过挂载 `IWarningCallback`,我们可以获得每个缺失字体事件的清晰、可编程列表——非常适合记录日志或通知终端用户。 + +### 检测缺失字体 – 需要关注的内容 + +运行程序时,任何缺失的字体都会在控制台输出类似以下的行: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +如果列表为空,恭喜——**save word as pdf** 已成功完成,且所有原始字体均完整保留。 + +## 将 Docx 转换为 PDF – 自定义输出 + +有时你需要特定的 PDF 版本、图像质量或合规级别。Aspose.Words 允许在调用 `Save` 之前调整 `PdfSaveOptions` 对象。 + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **为什么这很重要:** 如果你为法律档案生成 PDF,设置 `PdfA1b` 可确保文件符合严格标准。同样的转换仍然会遵循我们的警告回调,因此你仍然可以 **detect missing fonts**。 + +## Aspose Words 字体替换 – 处理边缘情况 + +### 场景 1:多个缺失字体 + +如果源文档使用了多个自定义字体,警告收集器将为每个字体包含一条记录。你可以将它们聚合: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### 场景 2:提供回退字体目录 + +Aspose.Words 可以搜索额外的文件夹以查找字体。加载文档之前,设置 `FontSettings` 的 `FontsFolder` 属性: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +现在库会首先尝试你的自定义文件夹,从而降低不必要的替换概率。 + +### 场景 3:忽略替换 + +如果你希望在缺少字体时转换失败(而不是悄悄替换),可以在回调中抛出异常: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +这会强制你在继续之前处理缺失的字体——在对静默失败不可接受的 CI 流水线中非常有用。 + +## 完整的端到端示例 + +将所有内容整合在一起,下面是一个简洁的版本,演示 **how to convert Word to PDF**,设置自定义 PDF 选项,并记录任何字体问题: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**预期的控制台输出**(如果缺少 Calibri): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +如果没有出现警告,你的 **save word as pdf** 操作使用了与源 DOCX 完全相同的字体。 + +## 可视化概览 + +![保存 Word 为 PDF 工作流图示](https://example.com/diagram.png "保存 Word 为 PDF 工作流") + +*图片说明:* **save word as pdf** 工作流展示了加载、警告收集和 PDF 输出。 + +## 常见问题与解答 + +| Question | Answer | +|----------|--------| +| **我需要 Aspose.Words 的许可证吗?** | 免费评估许可证可用于测试,但在生产环境中需要付费许可证以去除评估水印。 | +| **这在 .NET Core / .NET 6+ 上能工作吗?** | 当然可以——Aspose.Words 目标是 .NET Standard 2.0,因此任何近期的 .NET 运行时都兼容。 | +| **我可以在循环中转换多个 DOCX 文件吗?** | 可以,只需为每个文件实例化一个新的 `Document`,如果需要聚合结果,可复用同一个 `WarningInfoCollector`。 | +| **如果输出文件夹不存在怎么办?** | `Document.Save` 会抛出 `DirectoryNotFoundException`。请先创建文件夹,或使用 `Directory.CreateDirectory`。 | +| **有没有办法将缺失的字体嵌入到 PDF 中?** | 如果机器上有相应字体,Aspose.Words 可以自动嵌入;只需将 `PdfSaveOptions.EmbedFullFonts = true` 设置即可。 | + +## 结论 + +现在你已经拥有了一套稳固、可用于生产环境的模式,能够 **save Word as PDF**,同时 **detecting missing fonts** 并处理 **Aspose.Words font substitution** 场景。通过附加警告回调、定制字体文件夹,并可选地调整 `PdfSaveOptions`,你可以可靠地 **convert docx to pdf**,并让用户了解可能影响布局精度的任何字体问题。 + +准备好下一步了吗?尝试并行生成多个文档的 PDF,或探索添加水印和数字签名——这两者都是你刚掌握的代码的直接扩展。祝编码愉快,愿你的 PDF 始终如预期般完美呈现! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-loadoptions/_index.md b/words/chinese/net/programming-with-loadoptions/_index.md index 99d0724397..c6a529f4d9 100644 --- a/words/chinese/net/programming-with-loadoptions/_index.md +++ b/words/chinese/net/programming-with-loadoptions/_index.md @@ -34,7 +34,8 @@ Aspose.Words for .NET 教程为希望掌握使用 LoadOptions 进行文字处理 | [在 Word 文档中加载 Chm 文件](./load-chm/) 按照本分步教程,使用 Aspose.Words for .NET 轻松将 CHM 文件加载到 Word 文档中。非常适合整合您的技术文档。| | [如何使用 Aspose.Words 恢复 docx – 分步指南](./how-to-recover-docx-with-aspose-words-step-by-step/) 按照本分步指南,使用 Aspose.Words for .NET 恢复受损的 docx 文档。| | [Aspose Load Options – 使用自定义字体设置加载 DOCX](./aspose-load-options-load-docx-with-custom-font-settings/) 了解如何使用 Aspose.Words for .NET 的 LoadOptions 在加载 DOCX 时自定义字体设置,确保文档正确渲染。| -| [恢复损坏的 Word 文件 – 打开损坏的 DOCX 完整指南并获取页数](./recover-damaged-word-file-complete-guide-to-open-corrupted-d/) 了解如何使用 Aspose.Words for .NET 恢复损坏的 Word 文件,打开损坏的 DOCX 并获取页数。分步指南。| +| [恢复损坏的 Word 文件 – 打开损坏的 DOCX 完整指南并获取页数](./recover-damaged-word-file-complete-guide-to-open-corrupted-word-fi/) 了解如何使用 Aspose.Words for .NET 恢复损坏的 Word 文件,打开损坏的 DOCX 并获取页数。分步指南。| +| [恢复损坏的 docx – 加载受损 Word 文件的完整指南(C#)](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) 按照本完整指南,使用 Aspose.Words for .NET 在 C# 中加载并恢复受损的 docx 文件。| | [如何恢复 docx – C# 损坏 Word 文件指南](./how-to-recover-docx-c-guide-for-corrupted-word-files/) 了解如何使用 Aspose.Words for .NET 在 C# 中恢复受损的 docx 文件,步骤详尽,帮助您修复损坏的 Word 文档。| | [使用 Aspose.Words 在 C# 中恢复 Word 文档](./recover-word-document-with-aspose-words-in-c/) 了解如何使用 Aspose.Words for .NET 在 C# 中恢复受损的 Word 文档,分步指南帮助您快速修复文件。| | [如何恢复 docx – 设置恢复模式并打开受损的 Word 文件](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) 了解如何使用 Aspose.Words for .NET 设置恢复模式并打开受损的 Word 文档,确保文档完整性。| diff --git a/words/chinese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/chinese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..d857793825 --- /dev/null +++ b/words/chinese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 快速恢复损坏的 docx 文件。了解如何设置恢复模式、安全加载 docx,以及仅需几步即可读取受损的 Word + 文件。 +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: zh +og_description: 在 C# 中恢复损坏的 docx 文件。设置恢复模式,安全加载 docx,并使用 Aspose.Words 读取受损的 Word 文件。 +og_title: 恢复损坏的 docx – 快速 C# 指南 +tags: +- Aspose.Words +- C# +- Document Recovery +title: 恢复损坏的 docx – C# 中加载受损 Word 文件的完整指南 +url: /zh/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 恢复损坏的 docx – 快速 C# 指南 + +是否曾尝试打开一个根本无法加载的 Word 文件,并担心内容永远丢失?在许多实际项目中,您可以 **recover corrupted docx** 文件,而无需让用户重新发送附件。好消息是 Aspose.Words 让这变得轻而易举:只需设置恢复模式,让库来完成繁重的工作。 + +在本教程中,我们将逐步演示 **recover corrupted docx** 文件的具体操作,解释为何 `RecoveryMode.AutoRecover` 选项是最安全的选择,并展示如何 **how to load docx** 可能部分损坏的文件。完成后,您将能够读取损坏的 Word 文件,提取仍然存在的文本,甚至记录原始格式以供将来审计。无需外部工具,仅使用纯净的 C# 代码。 + +## 您需要的条件 + +- **Aspose.Words for .NET**(任何近期版本;我们使用的 API 兼容 23.5 及更高版本)。 +- 一个 .NET 开发环境(Visual Studio、VS Code 或 Rider)。 +- 您想要恢复的损坏或部分损坏的 `.docx`。 + +无需特殊权限、无需 COM 互操作,也不需要在服务器上安装 Microsoft Office。简单吧? + +## Step 1: Set Recovery Mode to Auto‑Recover + +当 Word 文件损坏时,默认的加载行为会抛出异常并中止。通过配置 `LoadOptions` 对象,您可以告诉 Aspose.Words **set recovery mode** 为 `AutoRecover`,它会扫描 zip 包,跳过不可读取的部分,并返回能够拼凑出的内容。 + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Why AutoRecover?** +> 它会尽可能多地读取内容,同时保持文档对象可用。如果选择 `RecoveryMode.NoRecovery`,加载将在第一次遇到损坏时失败,这就违背了 **recover corrupted docx** 场景的初衷。 + +## Step 2: Load the Document with the Configured Options + +现在恢复模式已经设置好,您可以安全地尝试打开文件。将 `"YOUR_DIRECTORY/input.docx"` 替换为实际的损坏文件路径。 + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +如果文件仅部分损坏,`Document` 实例仍会被创建。若需要额外验证,可以稍后检查 `document.IsStructureValid`。 + +## Step 3: Verify the Detected Format + +Aspose.Words 会自动检测原始格式(DOC、DOCX、ODT 等)。打印该值可以帮助您确认库正确识别了文件,这是一次 **recover corrupted docx** 操作后的快速 sanity check。 + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +典型输出: + +``` +Loaded with Docx format. +``` + +即使有些部分缺失,格式检测仍然成功——这又是 **recover corrupted docx** 工作流的一个胜利。 + +## Step 4: Extract What You Can + +文档加载后,您可以像处理任何健康的 Word 文件一样使用它。下面是一个紧凑示例,提取纯文本并写入控制台。这演示了您可以 **read damaged word file** 内容而不会崩溃。 + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +如果原文件中的表格或图片损坏,它们将直接从文本输出中省略。文档的其余部分保持完整。 + +## Step 5: Save a Clean Copy (Optional) + +通常在恢复后,您会想给用户一个全新的、干净的文件版本。使用相同的格式保存可确保与后续任何流程兼容。 + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +现在您拥有一个 **recover damaged docx** 文件,可以安全地作为附件发送邮件或传递给其他服务。 + +## Full Working Example + +把所有步骤组合起来,这就是完整的、可直接运行的程序。将其粘贴到新的控制台项目中,调整文件路径,然后按 F5 运行。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Expected output**(假设文件包含单段落 “Hello world!” 和一些损坏的 XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +请注意程序从未崩溃——即使源文件部分损坏。这正是使用 Aspose.Words **recover corrupted docx** 的精髓所在。 + +## Common Questions & Edge Cases + +### What if the file is completely unreadable? + +即使是 `AutoRecover` 也有其极限。如果 zip 容器本身损坏到无法修复,Aspose.Words 将抛出 `CorruptedFileException`。此时您可能需要先使用第三方 zip 修复工具,然后再尝试 **recover corrupted docx**。 + +### Can I recover other formats (e.g., `.doc`, `.odt`)? + +当然可以。相同的 `LoadOptions` 适用于 Aspose.Words 支持的任何格式。只需更改文件扩展名,库会自动检测原始格式。这意味着您同样可以使用相同代码 **recover damaged docx**‑like 文件,如 `.doc` 或 `.rtf`。 + +### How do I handle large documents without loading everything into memory? + +对于 GB 级别的文件,您可以启用 **load options**(如 `LoadOptions.LoadFormat`)或逐页流式读取文档。然而,恢复算法仍需读取整个包,因此在处理非常大的损坏文件时仍会占用较高内存。 + +### Is there a way to know which parts were lost? + +加载后,您可以检查 `document.GetChildNodes(NodeType.Any, true)` 并将节点数量与预期基准进行比较。缺失的表格、图片或页眉会直接从节点集合中消失。这让您能够准确记录哪些是 **recover damaged docx**,并通知用户。 + +## Pro Tips for Reliable Recovery + +- **Validate the input file size** 在加载前进行验证;零字节文件始终会失败。 +- **Log the `RecoveryMode` result** 通过捕获 `DocumentLoadingException` 并保存异常信息来记录;它通常包含哪些部分被跳过的线索。 +- **Run the recovery on a background thread** 如果您在 Web 服务中处理上传——这可以保持请求的响应性。 +- **Combine with a checksum**(例如 MD5)以检测恢复后的文件是否与原始文件不同;您可以据此决定是否保留两个版本。 + +## Conclusion + +我们已经展示了如何在 C# 中通过 **setting recovery mode** 为 `AutoRecover` 来 **recover corrupted docx** 文件,安全加载文档,提取仍然存在的文本,并可选地保存干净副本。这种方法让您能够 **how to load docx** 那些本会抛出异常的文件,并提供了一种可靠的方式来 **read damaged word file** 内容,而无需外部工具。 + +接下来可以尝试将 `RecoveryMode.AutoRecover` 替换为 `RecoveryMode.NoRecovery` 观察差异,或实验 `LoadOptions` 中控制密码处理和字体替换的属性。您甚至可以将恢复例程集成到接受上传并返回修复文件的 ASP.NET Core API 中——这对企业文档管理流水线非常理想。 + +还有关于 Word 文档恢复的其他问题,或想了解如何使用自定义回调 **recover damaged docx** 文件?在下方留言吧,祝编码愉快! + +![已恢复文档的示意图 – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-markdownsaveoptions/_index.md b/words/chinese/net/programming-with-markdownsaveoptions/_index.md index b59df0a2f7..8830ac9b45 100644 --- a/words/chinese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/chinese/net/programming-with-markdownsaveoptions/_index.md @@ -70,6 +70,10 @@ 使用 Aspose.Words for .NET 将 Word 文档转换为 Markdown,并提取嵌入的图像,提供完整的 C# 示例和详细步骤指南。 +### [将 docx 保存为 markdown – 使用 Aspose.Words 导出 Word 数学为 LaTeX](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) + +使用 Aspose.Words for .NET 将 docx 文档中的数学公式导出为 LaTeX,提供完整的 C# 示例和分步指南。 + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/chinese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..fc8548d28e --- /dev/null +++ b/words/chinese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 将 docx 保存为 markdown——学习将 Word 转换为 markdown,导出公式为 LaTeX,并在一个流畅的工作流中设置 + markdown 图像分辨率。 +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: zh +og_description: 使用 Aspose.Words 将 docx 保存为 markdown。本教程展示如何将 Word 转换为 markdown,导出公式为 + LaTeX,以及设置 markdown 图像分辨率。 +og_title: 将 docx 保存为 markdown – 完整指南:将 Word 数学公式导出为 LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: 将 docx 保存为 markdown – 使用 Aspose.Words 将 Word 数学导出为 LaTeX +url: /zh/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 docx 保存为 markdown – 使用 Aspose.Words 将 Word 数学公式导出为 LaTeX + +是否曾经想要 **将 docx 保存为 markdown**,却苦于如何保持 Office Math 公式的清晰度?你并不孤单。大多数开发者在默认转换把公式降为模糊的图片后,往往需要手动改写为 LaTeX,进而卡住。 + +好消息:Aspose.Words 可以为你完成繁重的工作。在本教程中,我们将 **将 word 转换为 markdown**,告诉引擎 **导出公式为 latex**,并且 **设置 markdown 图片分辨率**,以处理文档中的其他内容。完成后,你只需一条命令即可生成带有 LaTeX 公式和高分辨率图片的干净 `.md` 文件。 + +## 你将学到 + +- 如何加载包含 Office Math 对象的 `.docx`。 +- 哪些 `MarkdownSaveOptions` 属性控制 **导出公式为 latex** 和 **设置 markdown 图片分辨率**。 +- 一个完整、可运行的 C# 代码片段,直接粘贴到任意 .NET 项目中。 +- 常见问题的排查技巧,例如缺少字体或不支持的公式特性。 + +**先决条件**:.NET 6+(或 .NET Framework 4.6+),拥有 Aspose.Words for .NET 的授权,以及对 C# 的基本了解。如果你能够创建一个控制台应用程序,就可以开始了。 + +--- + +## 第一步 – 将 docx 保存为 markdown:加载 Word 文件 + +首先需要一个指向源 `.docx` 的 `Document` 对象。把它想象成在开始复制章节前先打开一本书。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*为什么重要*:如果文档中不包含任何数学公式,**导出公式为 latex** 步骤将不会产生任何效果,但其余转换仍会执行。此检查可以避免你疑惑为何输出的 Markdown 缺少 LaTeX 块。 + +--- + +## 第二步 – 配置导出公式为 LaTeX + +Aspose.Words 允许你决定 Office Math 的渲染方式。默认情况下,它会把公式转换为 PNG 图片,这也是许多教程生成颗粒感 markdown 文件的原因。将 `OfficeMathExportMode` 设置为 `LaTeX`,即可得到干净、可直接复制的公式。 + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*为什么使用 `OfficeMathExportMode.LaTeX`?* LaTeX 是科学出版的通用语言。当你随后使用静态站点生成器或 Jupyter Notebook 渲染 markdown 时,公式将在任何缩放级别下保持清晰。 + +--- + +## 第三步 – 设置 Markdown 图片分辨率(针对非数学内容) + +虽然我们主要关注数学公式,但大多数 Word 文档还包含图片、图表或嵌入的 SVG。`ImageResolution` 属性决定 Aspose.Words 对这些资源的光栅化方式。**300 DPI** 是屏幕和打印的折中选择。 + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*小技巧*:如果你的 markdown 只会在网页上展示,可以将分辨率降至 150 DPI,以减小文件体积。相反,若需生成可打印的 PDF,则可提升至 600 DPI。 + +--- + +## 第四步 – 执行转换 – 将 Word Math 导出为 LaTeX + +所有配置完成后,实际的转换只需一行代码。Aspose.Words 会在后台完成繁重工作。 + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**预期输出**:打开生成的 `.md` 文件,你会看到类似下面的内容: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +注意 LaTeX 块(`$...$` 与 `$$...$$`)已经取代了之前的 PNG 片段。文档底部的图片仍然是 PNG,分辨率为我们在步骤 3 中设定的 300 DPI。 + +--- + +## 第五步 – 常见边缘情况及处理办法 + +| 情况 | 会发生什么 | 解决方案 | +|-----------|--------------|------------| +| **缺少字体**(例如未安装 Cambria Math) | LaTeX 输出可能出现未知符号。 | 在服务器上安装缺失的字体,或在转换前将其嵌入文档。 | +| **复杂公式**(带自定义分隔符的矩阵) | 即使使用 `LaTeX` 模式,Aspose.Words 仍可能回退为图片。 | 升级到最新的 Aspose.Words 版本;库会持续改进公式支持范围。 | +| **大型文档**(> 50 MB) | 内存压力可能导致 `OutOfMemoryException`。 | 使用 `LoadOptions` 并指定 `LoadFormat.Docx`,以流方式加载文件,或在转换前将文档拆分为多个章节。 | +| **图片尺寸过大** | Markdown 文件体积膨胀,导致静态站点构建变慢。 | 对仅用于网页的场景,将 `ImageResolution` 降至 150 DPI(参见第 3 步)。 | + +--- + +## 第六步 – 完整示例:把所有代码整合在一起 + +下面是可以直接复制到 `Program.cs` 的 *完整* 控制台应用程序示例。它包含了前面讨论的所有要点,并加入了一点错误处理。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +运行程序(`dotnet run`),即可得到一个 **将 docx 保存为 markdown** 的文件,所有公式均以 LaTeX 形式保留。无需手动复制,也不再出现丑陋的数学图片。 + +--- + +## 结论 + +我们已经完整演示了如何使用 Aspose.Words **将 docx 保存为 markdown**,从加载 Word 文件到配置 **导出公式为 latex** 与 **设置 markdown 图片分辨率**。最终代码片段已具备生产级别,可直接嵌入任何需要 **将 word 转换为 markdown** 的 .NET 项目中。 + +接下来可以尝试将生成的 `.md` 文件喂给 Hugo、Jekyll 等静态站点生成器,欣赏公式的优雅渲染。如果你还需要 **将 word math latex** 转换为其他格式(PDF、HTML),只需将 `MarkdownSaveOptions` 替换为 `PdfSaveOptions` 或 `HtmlSaveOptions`——同样的 `OfficeMathExportMode` 标志在这些格式中同样适用。 + +如果你的工作流涉及从 Azure Blob 存储读取 Word 文件或通过 API 流式传输,只需将文件系统的 `Document` 构造函数换成基于流的版本,模式保持不变。 + +尽情实验吧,并在评论区分享此方法如何解决了你的转换难题。祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-pdfsaveoptions/_index.md b/words/chinese/net/programming-with-pdfsaveoptions/_index.md index c6462664a4..d4b05ce788 100644 --- a/words/chinese/net/programming-with-pdfsaveoptions/_index.md +++ b/words/chinese/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ Aspose.Words for .NET 教程“使用 PdfSaveOptions 进行文字处理”将引 | [在 C# 中创建可访问的 PDF – PDF 可访问性教程](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) 通过本分步指南了解如何使用 Aspose.Words for .NET 在 C# 中生成符合可访问性标准的 PDF 文档。| | [从 Word 创建可访问的 PDF – 完整指南](./create-accessible-pdf-from-word-complete-guide/) | 了解如何使用 Aspose.Words for .NET 将 Word 文档转换为符合可访问性标准的 PDF,包括标签、替代文本和文档结构等。| | [创建可访问的 PDF – PDF/UA 合规的分步指南](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) 通过本分步指南了解如何使用 Aspose.Words for .NET 创建符合 PDF/UA 标准的可访问 PDF 文档。| +| [使用 Aspose.Words 将文档保存为 PDF – 完整 C# 指南](./save-document-as-pdf-with-aspose-words-complete-c-guide/) 通过本完整的 C# 指南,学习使用 Aspose.Words 将文档转换并保存为 PDF。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/chinese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..cc1146f7e2 --- /dev/null +++ b/words/chinese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,252 @@ +--- +category: general +date: 2026-05-01 +description: 学习如何使用 Aspose.Words 在 C# 中将文档保存为 PDF。本教程还涵盖将 Word 转换为 PDF、导出数学 LaTeX,以及处理缺失字体。 +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: zh +og_description: 使用 Aspose.Words 轻松将文档保存为 PDF。本指南还展示了如何将 Word 转换为 PDF、导出数学 LaTeX,以及处理缺失字体。 +og_title: 使用 Aspose.Words 将文档保存为 PDF – 完整 C# 指南 +tags: +- Aspose.Words +- C# +- PDF generation +title: 使用 Aspose.Words 将文档保存为 PDF – 完整 C# 指南 +url: /zh/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.Words 将文档保存为 PDF – 完整 C# 指南 + +是否曾经想过 **如何将文档直接保存为 pdf**,从 Word 文件中而不丢失可访问性特性?你并非唯一——开发者们一直在寻找一种可靠的方法,将 Word 转换为 PDF,同时保留数学公式并优雅地处理缺失的字体。 + +在本教程中,我们将逐步演示一个不仅能 **save document as pdf**,还能展示 **convert word to pdf**、**export math latex** 与 **handle missing fonts** 的完整解决方案,使用最新的 Aspose.Words for .NET。完成后,你将拥有一个可直接运行的 C# 程序,生成符合 PDF/UA‑2 标准的文件,完美用于可访问性审计。 + +## 您需要的环境 + +- .NET 6 或更高(代码同样适用于 .NET Core 和 .NET Framework) +- Aspose.Words for .NET 25.10 或更高版本 – 可从 Aspose 官网获取免费试用 +- 一个普通的 Word 文档(`input.docx`),其中至少包含一个浮动形状和一个数学公式(用于演示 export‑math‑latex 功能) +- Visual Studio 2022(或您喜欢的任何 IDE) + +> **专业提示:** 如果您在 CI/CD 流水线中,向项目文件添加 Aspose.Words NuGet 包: + +```xml + +``` + +现在让我们深入代码。 + +## 第一步:使用自动恢复加载源文档 + +在处理真实的 Word 文件时,你可能会遇到损坏的章节或缺失的资源。启用自动恢复可确保加载过程永不抛出异常。 + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**为什么重要:** +`RecoveryMode.AutoRecover` 可防止管道在遇到格式错误的输入时崩溃,这在批量 **convert word to pdf** 时尤为实用。 + +## 第二步:为完整可访问性设置 PDF 保存选项 + +PDF/UA‑2 是可访问 PDF 的 ISO 标准。通过配置少量标志,我们即可得到屏幕阅读器可以导航的文件,并确保数学公式以隐藏的 LaTeX 形式导出。 + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**关键点:** + +- **ExportFloatingShapesAsInlineTag** – 确保生成的 PDF 保持原始布局,同时在语义上保持正确。 +- **OfficeMathExportMode.LaTeX** – 满足 **export math latex** 的需求,让下游工具能够提取公式。 + +## 第三步:捕获警告(例如缺失的字体) + +缺失字体是转换文档时常见的头疼问题。Aspose.Words 可以通过 `WarningCallback` 报告这些问题。我们将收集它们,以便后续记录或处理。 + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**你需要关注的原因:** +如果源文档使用的字体未在服务器上安装,PDF 将回退到默认字体,可能导致布局错乱。通过 **handle missing fonts** 我们可以提醒用户或嵌入替代字体。 + +## 第四步:将文档保存为可访问的 PDF + +真正的关键时刻——执行转换。 + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +如果一切顺利,你将得到一个符合 PDF/UA‑2 的文件,包含每个公式的隐藏 LaTeX 以及对浮动形状的正确标记。 + +## 第五步:审查捕获的警告(可选但推荐) + +保存操作完成后,你可以遍历收集到的警告并记录它们。 + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +典型输出可能如下: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +提前看到这些信息有助于在影响终端用户之前 **handle missing fonts**。 + +## 完整可运行示例 + +将所有内容组合在一起,这就是完整的、可直接运行的程序。请将占位路径替换为你自己的路径。 + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**预期结果:** +- `output.pdf` 符合 PDF/UA‑2。 +- 所有浮动形状被标记为内联图形。 +- 每个 Office Math 对象以隐藏 LaTeX 形式出现(在检查 PDF 结构时可见)。 +- 任何与字体相关的问题都会打印到控制台,让你有机会在发布文件前 **handle missing fonts**。 + +![展示从 Word → Aspose.Words → 可访问 PDF(save document as pdf)流程的图示](conversion-diagram.png "保存文档为 pdf 的流程图") + +*图片替代文字:* **使用 Aspose.Words 将文档保存为 pdf 的流程图** + +## 常见问题与边缘情况 + +### 如果我使用的是旧版本的 Aspose.Words,怎么办? + +`OfficeMathExportMode.LaTeX` 标志是在 25.10 版本中引入的。对于旧版本,你仍然可以 **convert word to pdf**,但公式会被栅格化而不是导出为 LaTeX。建议升级以获得最佳可访问性。 + +### 能否嵌入自定义字体以避免回退? + +可以。在调用 `Save` 之前设置 `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll`。这同样有助于通过 **handle missing fonts** 强制 PDF 包含所需字形。 + +### 如何验证 PDF/UA‑2 合规性? + +在 Adobe Acrobat Pro 中打开文件 → “Print Production” → “Preflight”。选择 “PDF/A‑2b” 或 “PDF/UA‑2” 配置文件;Acrobat 将报告任何违规项。 + +### 密码保护的 Word 文件怎么办? + +使用包含 `Password` 的 `LoadOptions` 加载文档。例如: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +其余流程保持不变。 + +## 结论 + +我们已经覆盖了使用 Aspose.Words 在 C# 中 **save document as pdf** 所需的全部内容。教程还演示了如何 **convert word to pdf**、**export math latex** 与 **handle missing fonts**——全部生成符合 PDF/UA‑2 标准的可访问 PDF。 + +尝试运行代码,实验不同的 `PdfSaveOptions`(例如图像压缩、PDF/A‑2b),并将其集成到你的文档处理服务中。如果需要更进一步的功能,可考虑使用 Aspose 的 PDF 专用库进行后处理或数字签名。 + +还有其他场景想要实现吗?欢迎留言或查看我们关于 **PDF 操作**、**图像提取** 与 **批量转换** 的其他指南。祝编码愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-shapes/_index.md b/words/chinese/net/programming-with-shapes/_index.md index 47ba271840..ea99649827 100644 --- a/words/chinese/net/programming-with-shapes/_index.md +++ b/words/chinese/net/programming-with-shapes/_index.md @@ -38,6 +38,7 @@ Aspose.Words for .NET 教程“使用形状进行文字处理”提供了在 Wor | [使用 C# 在 Word 中创建矩形形状](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) 通过本分步指南学习如何使用 Aspose.Words for .NET 在 Word 文档中插入矩形形状。| | [Aspose.Words 形状阴影教程 – 在 C# 中为 Word 形状添加阴影](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) 通过本分步指南学习如何使用 Aspose.Words for .NET 在 Word 文档的形状上添加阴影效果。| | [使用阴影矩形形状创建空白 Word 文档](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) 通过本分步指南学习如何使用 Aspose.Words for .NET 在 Word 文档中创建带阴影的矩形形状。| +| [如何在 Aspose.Words 中移动阴影 – 完整 C# 指南](./how-to-move-shadow-in-aspose-words-complete-c-guide/) 通过本分步指南学习如何在 Aspose.Words for .NET 中移动形状阴影,实现更灵活的视觉效果。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/chinese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..c821ae299f --- /dev/null +++ b/words/chinese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-01 +description: 如何使用 C# 在 Aspose.Words 中移动形状的阴影。学习在几分钟内为形状添加阴影、更改模糊度、设置透明度以及旋转阴影。 +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: zh +og_description: 如何使用 C# 在 Aspose.Words 中移动形状的阴影。本教程展示了如何为形状添加阴影、更改模糊程度、设置透明度以及旋转阴影。 +og_title: 如何在 Aspose.Words 中移动阴影 – 完整 C# 指南 +tags: +- Aspose.Words +- C# +- Document Automation +title: 如何在 Aspose.Words 中移动阴影 – 完整 C# 指南 +url: /zh/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Aspose.Words 中移动阴影 – 完整 C# 指南 + +是否曾经想过 **如何移动阴影** 在 Word 文档中的形状上,而不需要手动打开 Word?在我的日常工作中,我经常需要以编程方式微调形状的阴影——无论是为了打造精致的报告还是动态模板。好消息是?使用 Aspose.Words 只需几行代码,你还将学习 **向形状添加阴影**、**如何更改模糊程度**、**如何设置透明度**以及**如何旋转阴影**,一次搞定。 + +在本教程中,我们将通过一个真实场景演示:加载已有的包含形状的 DOCX,调整阴影的位置、柔软度、不透明度和方向,最后保存结果。完成后,你将拥有一段可在任何 .NET 项目中直接使用的代码片段,并且了解每个属性背后的意义。 + +## 前置条件 – 开始之前你需要准备的东西 + +- **Aspose.Words for .NET**(版本 23.12 或更高)。可通过 NuGet 使用 `Install-Package Aspose.Words` 获取。 +- .NET 6+ 开发环境(Visual Studio、VS Code、Rider——任选其一)。 +- 一个输入的 Word 文件(`input.docx`),其中已包含至少一个形状(矩形、圆形或图片均可)。 +- 对 C# 语法有基本了解——不需要高级技巧。 + +如果缺少上述任意项,请先暂停并安装相应库;后续示例默认已引用该包。 + +## 第一步:加载文档并获取目标形状 – **如何移动阴影** 从这里开始 + +首先我们加载源文档并定位要修改的形状。Aspose.Words 将每个对象(段落、表格、形状)视为树中的节点,因而可以直接查询。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **为什么这很重要:** 只加载一次文档并复用同一个 `Document` 实例可以提升效率。`GetChild` 调用是安全的,因为若索引超出范围会返回 `null`,从而让我们能够优雅地处理缺失的形状。 + +## 第二步:调整模糊半径 – 掌握 **如何更改模糊程度** + +柔和的阴影看起来更专业,而硬边的阴影则显得廉价。`BlurRadius` 属性以点(pt)为单位控制柔软度(1 pt ≈ 1/72 英寸)。我们把它提升到 8 pt。 + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **小技巧:** 默认模糊值为 0.5 pt。超过 5 pt 通常能明显感受到,但若设置过大,形状会显得与页面脱离。 + +## 第三步:设置透明度 – 解答 **如何设置透明度** + +透明度决定阴影的透视程度。`0` 表示完全不透明,`1` 表示完全透明。为了获得细腻效果,我们使用 `0.3`(30 % 透明)。 + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **你可能关心的原因:** 如果形状本身颜色较深,完全不透明的阴影会淹没底层文字。调低透明度既能保持可读性,又能增加层次感。 + +## 第四步:移动阴影 – **如何移动阴影** 的核心 + +`Distance` 属性定义阴影相对于形状的偏移距离,单位为点。距离越大,阴影越远,视觉冲击力越强。 + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **如果只需要微小偏移怎么办?** 将 `Distance` 设为 `0`,阴影会直接贴在形状后面,适用于压纹效果。 + +## 第五步:旋转光源 – 解决 **如何旋转阴影** + +阴影并非只能垂直向下,它会随光源角度变化。`Angle` 属性(单位为度)围绕形状旋转阴影。这里我们将其倾斜 45°。 + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **快速实验:** 试试 `90` 会得到右侧阴影,`-30` 则产生左倾阴影。视觉变化立刻可见。 + +## 第六步:保存文档 – 查看 **向形状添加阴影** 的结果 + +完成阴影调整后,我们将文档写回磁盘。可以覆盖原文件,也可以生成新文件;示例使用新输出文件。 + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **预期输出:** 打开 `output.docx`,形状的阴影将更柔和、略微偏移、半透明且倾斜 45°。若将其与 `input.docx` 并排对比,差异一目了然。 + +### 完整可运行示例(复制粘贴即用) + +下面是一整段程序代码。粘贴到新的控制台项目中,将 `YOUR_DIRECTORY` 替换为实际文件夹路径,然后运行。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## 常见问题与边缘情况 + +### 文档中有多个形状怎么办? + +可以遍历所有形状: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### 能给当前没有阴影的形状添加阴影吗? + +当然可以。`ShadowFormat` 对象始终存在,只需将其启用: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### 这对图片和 SmartArt 有效吗? + +有效。任何继承自 `Shape` 的节点——包括图片、图表和 SmartArt——都暴露 `ShadowFormat`,属性使用方式相同。 + +### 如何控制阴影颜色? + +使用 `Color` 属性: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 兼容性问题? + +Aspose.Words 23.12+ 支持 .NET 6、.NET Core 3.1 和 .NET Framework 4.6.2+。本文展示的 API 在这些版本间保持稳定。 + +## 结论 + +我们已经完整演示了 **如何在形状上移动阴影**,并顺带展示了 **向形状添加阴影**、**如何更改模糊程度**、**如何设置透明度**以及**如何旋转阴影**。完整的可运行示例让你在几秒钟内即可微调任意形状的阴影,为文档增添专业感,而无需打开 Word。 + +准备好下一步了吗?尝试将这些阴影调整与 **条件格式** 结合——例如,仅对标题或超过特定尺寸的图表应用更深的阴影。亦或探索 **渐变填充** 为形状本身增色,打造真正抢眼的设计。 + +如果遇到任何问题,欢迎在下方留言。祝编码愉快,愿你的阴影总是恰到好处! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/basic-conversions/_index.md b/words/czech/net/basic-conversions/_index.md index c609068d97..3aec65e4c2 100644 --- a/words/czech/net/basic-conversions/_index.md +++ b/words/czech/net/basic-conversions/_index.md @@ -16,7 +16,7 @@ # Základní konverze -Základní konverze vás provede základními konverzemi dokumentů pomocí knihovny Aspose.Words pro .NET. Návody poskytují podrobné vysvětlení, podrobný zdrojový kód a praktické příklady pro převod dokumentů Word do různých formátů, jako jsou PDF, HTML, EPUB, obrázky a další. Naučíte se také, jak nastavit možnosti převodu, spravovat fonty, obrázky a rozvržení. Tento zdroj je nezbytný pro vývojáře, kteří chtějí automatizovat konverze dokumentů pomocí knihovny Aspose.Words pro .NET, a poskytuje jim plnou flexibilitu a kontrolu nad procesem konverze. +Základní konverze vás provede základními konveremi dokumentů pomocí knihovny Aspose.Words pro .NET. Návody poskytují podrobné vysvětlení, podrobný zdrojový kód a praktické příklady pro převod dokumentů Word do různých formátů, jako jsou PDF, HTML, EPUB, obrázky a další. Naučíte se také, jak nastavit možnosti převodu, spravovat fonty, obrázky a rozvržení. Tento zdroj je nezbytný pro vývojáře, kteří chtějí automatizovat konverze dokumentů pomocí knihovny Aspose.Words pro .NET, a poskytuje jim plnou flexibilitu a kontrolu nad procesem konverze. ## Návody | Název | Popis | @@ -36,6 +36,7 @@ Základní konverze vás provede základními konverzemi dokumentů pomocí knih | [Převod Wordu do PDF v C# pomocí Aspose.Words – Průvodce](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Naučte se, jak převést dokument Word do PDF pomocí Aspose.Words v C#. Praktický návod s ukázkovým kódem. | | [Uložit Word jako PDF pomocí Aspose.Words – Kompletní průvodce C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Naučte se, jak pomocí Aspose.Words převést dokument Word do PDF v C# s podrobným návodem a ukázkovým kódem. | | [Uložit DOCX jako PDF pomocí Aspose.Words – Kompletní průvodce C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Naučte se, jak převést DOCX do PDF pomocí Aspose.Words v C# s podrobným návodem a ukázkovým kódem. | +| [Uložit Word jako PDF pomocí Aspose.Words – Kompletní průvodce](./save-word-as-pdf-with-aspose-words-complete-guide/) | Naučte se, jak převést dokument Word do PDF pomocí Aspose.Words s podrobným návodem a ukázkovým kódem. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/czech/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index d4e69b77ce..1a23fe93f6 100644 --- a/words/czech/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/czech/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,24 @@ --- category: general -date: 2025-12-29 -description: Jak exportovat LaTeX z Wordu pomocí Aspose.Words – naučte se převádět - Word na LaTeX, uložit docx jako txt a pracovat s rovnicemi v prostém textu. +date: 2026-05-01 +description: Naučte se, jak exportovat LaTeX z Word souboru, převést Word na txt a + zachovat tabulky pomocí Aspose.Words v C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: cs -og_description: Jak exportovat LaTeX z Wordu pomocí Aspose.Words. Tento průvodce vám - ukáže, jak převést Word na LaTeX, uložit docx jako txt a zachovat rovnice neporušené. -og_title: Jak exportovat LaTeX z Wordu – rychlý C# tutoriál +og_description: Objevte, jak exportovat LaTeX z Wordu, převést Word na prostý text + a zachovat rozložení tabulky beze změny s Aspose.Words. +og_title: Jak exportovat LaTeX z Wordu – kompletní C# tutoriál tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: Jak exportovat LaTeX z Wordu – krok za krokem +title: Jak exportovat LaTeX z Wordu – krok za krokem průvodce url: /cs/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -27,160 +26,215 @@ url: /cs/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Jak exportovat LaTeX z Wordu – krok za krokem prů se někdy zamýšleli **jak exportovat LaTeX z Wordu** bez ztráty těch obtížných rovnic Office Math? Nejste v tom sami. Mnoho vývojářů narazí na problém, když se snaží *převést Word do LaTeXu* pro akademické práce, vědecké zprávy nebo automatizované publikační řetězce. +# Jak exportovat LaTeX z Wordu – kompletní C# tutoriál -V tomto tutoriálu projdeme kompletním, připraveným k spuštění příkladem v C#, který ukazuje **jak exportovat LaTeX** pomocí Aspose.Words, vysvětluje **jak uložit txt** soubory s LaTeX značkami a dokonce se zabývá nuancemi **convert word equations latex**, aby se nic neztratilo při převodu. +Už jste se někdy zamýšleli **jak exportovat LaTeX** z dokumentu Word, aniž byste přišli o žádné matematické rovnice? Nejste v tom sami. Mnoho vývojářů potřebuje převést .docx, který obsahuje Office Math, na čistý LaTeX a zároveň **convert Word to txt** pro další zpracování. V tomto průvodci vás provedeme praktickým, připraveným řešením, které **zachovává tabulky**, poskytuje soubor prostého textu a udržuje LaTeX značky přesně tam, kde je potřebujete. -> **Tip:** Stejný přístup funguje pro jakýkoli .docx, který máte—stačí nasměrovat kód na jinou cestu k souboru. - ---- +Probereme vše od načtení zdrojového souboru až po doladění `TxtSaveOptions`, aby výstup byl jak čitelný pro člověka, tak i pro stroj. Na konci budete umět **save docx as txt**, **convert Word to plain text** a budete vědět **how to preserve tables** během exportu. Žádné externí skripty, žádné ruční kopírování‑vkládání — jen čistý C# kód, který můžete vložit do libovolného .NET projektu. ## Co budete potřebovat -Než se pustíme dál, ujistěte se, že máte následující předpoklady: - -| Požadavek | Proč je důležitý | -|--------------|----------------| -| **.NET 6.0+** (nebo .NET Framework 4.6+) | Aspose.Words cílí na moderní .NET runtime. | -| **Aspose.Words for .NET** NuGet balíček (`Aspose.Words`) | Knihovna provádí těžkou práci při parsování Wordu a generování LaTeXu. | -| **Ukázkový .docx** obsahující alespoň jednu rovnicu Office Math | Pro zobrazení převodu LaTeX v praxi. | -| **Visual Studio 2022** (nebo jakékoli IDE, které máte rádi) | Umožňuje snadné ladění a spuštění ukázky. | - -Pokud jste ještě nenainstalovali NuGet balíček, spusťte: - -```bash -dotnet add package Aspose.Words -``` - -A to je vše—žádné extra DLL, žádný COM interop, jen čistá spravovaná knihovna. +- **Aspose.Words for .NET** (nejnovější verze, 2024.x nebo novější). NuGet balíček je `Aspose.Words`. +- Vývojové prostředí .NET (Visual Studio, VS Code, Rider — kterékoli vám vyhovuje). +- Word soubor (`.docx`) obsahující Office Math rovnice a alespoň jednu tabulku (abychom mohli vidět magii zachování tabulek). -## Přehled exportu LaTeXu z Wordu +To je vše. Pokud už máte vše připravené, pokračujte ve čtení; jinak si stáhněte NuGet balíček a ukázkový DOCX, než se ponoříme hlouběji. -Níže je velký obrázek toho, co dosáhneme: +--- -1. **Načíst** zdrojový Word dokument (`.docx`). -2. **Nastavit** `TxtSaveOptions` tak, aby všechny objekty Office Math byly vypsány jako LaTeX kód. -3. **Uložit** dokument jako plain‑text (`.txt`) soubor, který můžete přímo předat libovolnému LaTeX kompilátoru. +## Jak exportovat LaTeX z Word dokumentu -![Příklad exportu LaTeXu z Wordu](image.png "Jak exportovat LaTeX z Wordu") +Níže je jádro tutoriálu — tři stručné kroky, které odpovídají na otázku **how to export latex** a zároveň řeší sekundární cíle **convert word to txt**, **convert word to plain text**, **save docx as txt** a **how to preserve tables**. -## Krok 1: Načtení Word dokumentu +### Krok 1: Načtěte soubor DOCX -Nejprve—otevřete .docx, který chcete převést. Třída `Document` abstrahuje veškeré podkladové XML a poskytuje vám přátelský objektový model. +Nejprve musíme načíst Word dokument do objektu `Aspose.Words.Document`. Tento krok je stejný, ať už později **convert word to txt** nebo **save docx as txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Proč je to důležité:** -Načtení souboru brzy nám umožní prozkoumat jeho obsah (např. spočítat rovnice) před tím, než se rozhodneme, jak jej serializovat. Pokud je soubor poškozený, `Document` vyhodí jasnou výjimku, čímž vás ochrání před tajemným výstupem později. +> **Proč je to důležité:** Načtení souboru vytvoří v‑paměti reprezentaci všech Word elementů — odstavců, tabulek a Office Math objektů. Bez tohoto objektu nemůžete manipulovat s možnostmi exportu. + +### Krok 2: Nakonfigurujte `TxtSaveOptions` pro LaTeX a rozvržení tabulky -## Krok 2: Nastavení TxtSaveOptions pro export LaTeXu +Třída `TxtSaveOptions` vám umožní přesně řídit, jak se generuje soubor prostého textu. Dvě vlastnosti jsou klíčové pro náš scénář: -Magie se odehrává v `TxtSaveOptions`. Nastavením `OfficeMathExportMode` na `LaTeX` se každý objekt Office Math přemění na odpovídající LaTeX reprezentaci. +| Vlastnost | Co dělá | Proč to potřebujete | +|-----------|---------|----------------------| +| `OfficeMathExportMode` | Určuje, jak se renderuje Office Math. Nastavením na `LaTeX` se rovnice převedou do LaTeX syntaxe. | To je jádro **how to export latex**. | +| `PreserveTableLayout` | Když je `true`, Aspose přidá mezery, aby tabulky zachovaly mřížkový vzhled. | To splňuje **how to preserve tables** při **convert word to txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Proč volíme tato nastavení:** +> **Tip:** Pokud potřebujete jen čistý LaTeX bez formátování tabulek, nastavte `PreserveTableLayout` na `false`. Soubor bude menší, ale ztratíte vizuální vodítko tabulky. -- `OfficeMathExportMode.LaTeX` je jediný režim, který zaručuje věrný matematický převod. -- `PreserveTableLayout` zachovává vzhled tabulek tak, jak jsou ve Wordu, což je užitečné, když později vložíte výstup do LaTeX prostředí `tabular`. -- UTF‑8 zajišťuje, že znaky jako “α”, “β” nebo “∑” přežijí celý proces. +### Krok 3: Uložte dokument jako prostý text -Pokud někdy potřebujete **convert word to latex** bez obalu plain‑text, můžete místo toho přepnout na `SaveFormat.LaTeX`—rychlý tip pro pokročilé scénáře. +Nyní zapíšeme dokument do souboru `.txt` pomocí právě definovaných možností. Tento jediný řádek provede **convert word to plain text**, **save docx as txt** a samozřejmě **how to export latex** najednou. -## Krok 3: Uložení dokumentu jako textový soubor +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -Nyní zapíšeme LaTeX‑bohatý text na disk. Výsledný `.txt` můžete později přejmenovat na `.tex` nebo ho přímo předat LaTeX kompilátoru. +doc.Save(outputPath, saveOptions); +``` -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +Po dokončení volání otevřete `output.txt`. Uvidíte: -// Save using the configured options -doc.Save(outputPath, txtOptions); +- LaTeX úryvky jako `\frac{a}{b}` pro každou Office Math rovnici. +- Tabulky vykreslené pomocí znaků `|` a `-`, zachovávající zarovnání sloupců. +- Běžné odstavce jako prostý text, připravené pro jakýkoli downstream parser. -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +### Kompletní funkční příklad + +Spojením všeho dohromady získáte samostatný program, který můžete dnes zkompilovat a spustit: + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Co uvidíte v `output.txt`:** +**Očekávaný výstup** (úryvek): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Všechny ostatní odstavce se zobrazí jako prostý text, zatímco každá rovnice Office Math je zabalena do LaTeX prostředí `equation` (nebo `inline`, pokud byla vkládána inline ve Wordu). To dokonale splňuje požadavek **convert word equations latex**. +Všimněte si, že tabulka si zachovává mřížku a rovnice se objevují jako čistý LaTeX. To je ideální kombinace, když **convert word to txt** a zároveň potřebujete věrnou reprezentaci struktury i matematiky. -## Okrajové případy a časté otázky +--- -| Situace | Co dělat | -|-----------|------------| -| **Žádné rovnice ve zdroji** | Převod stále funguje; získáte jen prostý text. Žádný extra LaTeX kód není přidán. | -| **Velmi velké dokumenty (>100 MB)** | Zvažte streamování výstupu pomocí `MemoryStream`, abyste se vyhnuli vysoké spotřebě paměti. | -| **Nepodporované matematické konstrukce** | Aspose.Words pokrývá 99 % Office Math. Pro vzácné okrajové případy může být nutné LaTeX ručně post‑processovat. | -| **Potřebujete .tex soubor místo .txt** | Změňte `outputPath` tak, aby končil na `.tex` a případně nastavte `txtOptions.Encoding` na `Encoding.UTF8`. | -| **Běh na Linux/macOS** | Stejný kóduje—jen zajistěte, aby cesty k souborům používaly dopředná lomítka nebo `Path.Combine`. | +## Tipy pro převod Wordu do TXT a zachování tabulek -## Jak uložit TXT s LaTeX rovnicemi – rychlý přehled +Ačkoliv tříkrokový přístup funguje ve většině případů, reálné projekty často přinášejí nečekané komplikace. Níže najdete praktické návrhy, jak udělat váš **convert word to plain text** pipeline robustní. -1. **Načíst** .docx (`Document`). -2. **Nastavit** `OfficeMathExportMode = LaTeX` v `TxtSaveOptions`. -3. **Uložit** soubor (`doc.Save`) s těmito možnostmi. +### Používejte konzistentní kódování -To je celý postup, jak **how to save txt** soubory, které obsahují LaTeX‑formátované rovnice. +`TxtSaveOptions` ve výchozím nastavení používá UTF‑8, který zvládne většinu znaků. Pokud potřebujete jinou znakovou sadu (např. starší systémy očekávající Windows‑1252), nastavte vlastnost `Encoding`: -## Bonus: Automatizace převodu pro více souborů +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -Pokud máte složku plnou Word dokumentů, zabalte výše uvedenou logiku do jednoduché smyčky: +### Odstraňte nadbytečné mezery + +Tabulky s mnoha sloupci mohou generovat dlouhé řádky. Po uložení můžete soubor post‑processovat a sloučit více mezer do jednoho tabulátoru: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Zpracování vnořených tabulek + +Pokud váš DOCX obsahuje tabulky uvnitř tabulek, `PreserveTableLayout` stále zachová vizuální hierarchii, ale odsazení může vypadat podivně. Rychlé řešení je nahradit úvodní mezery vlastním značkou (např. `>>`), aby downstream parser dokázal rozpoznat úrovně vnoření. - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +### Hromadné zpracování více souborů + +Když potřebujete **convert word to txt** pro desítky dokumentů, zabalte logiku do smyčky: + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Nyní můžete **convert word to latex** hromadně—ideální pro výzkumné skupiny, které denně dostávají desítky rukopisů. +Tímto způsobem můžete **save docx as txt** hromadně bez ruční intervence. + +--- + +## Časté úskalí a jak se jim vyhnout + +1. **Chybějící LaTeX exportní režim** — pokud zapomenete nastavit `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, rovnice se vrátí na prostý text (např. „Equation 1“). Vždy zkontrolujte blok možností. +2. **Ztráta rozvržení tabulky** — výchozí hodnota `PreserveTableLayout` je `false`. Pokud váš výstup vypadá jako blok textu, pravděpodobně jste příznak nepřepnuli. +3. **Cesty k souborům s mezerami** — použití raw stringu (`@"C:\My Folder\input.docx"`) eliminuje problémy s escapováním. Jinak můžete narazit na `FileNotFoundException`. +4. **Nesoulad verzí** — starší verze Aspose.Words (< 21.9) nepodporují `OfficeMathExportMode`. Aktualizujte na nejnovější balíček, aby **how to export latex** fungovalo. +5. **Chyby kódování pro ne‑ASCII znaky** — pokud vidíte symboly �, explicitně nastavte `options.Encoding` na UTF‑8 nebo příslušnou znakovou sadu. + +--- + +## Rozšíření řešení: z TXT do Markdown nebo HTML + +Někdy potřebujete víc než prostý text — například Markdown soubor, který stále obsahuje LaTeX bloky. Stejný `TxtSaveOptions` můžete nahradit `HtmlSaveOptions` nebo `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Tato malá změna vám umožní **convert word to txt**‑styl výstup, zatímco zachováte markdown syntaxi, kterou milujete. + +--- ## Závěr -Probrali jsme **jak exportovat LaTeX z Wordu** krok za krokem, ukázali **jak uložit txt** soubory, které zachovají každou rovnicu Office Math a dokonce vám ukázali, jak **convert word equations latex** bez ztráty věrnosti. +Prošli jsme kompletním, připraveným řešením na otázku **how to export latex** z Word dokumentu, a zároveň jsme vám ukázali, jak **convert word to txt**, **convert word to plain text**, **save docx as txt** a **how to preserve tables**. Klíčové body jsou: + +- Načtěte DOCX pomocí `Aspose.Words.Document`. +- Nastavte `TxtSaveOptions.OfficeMathExportMode = LaTeX` a `PreserveTableLayout = true`. +- Zavolejte `doc.Save(outputPath, options)` a získáte čistý LaTeX‑bohatý soubor prostého textu. -S několika řádky C# a výkonnou knihovnou Aspose.Words můžete převést jakýkoli .docx na LaTeX‑připravený text, připravený k zařazení do vědeckých prací, učebnic nebo automatizovaných publikačních řetězců. +Vyzkoušejte to na vlastních souborech, pohrávejte si s nastavením kódování a klidně hromadně zpracovávejte celé složky. Pokud narazíte na okrajové případy — vnořené tabulky, exotické znaky nebo starší verze Aspose — vrátíte se k sekcím „Tipy“ a „Úskalí“ pro rychlé opravy. -**Další kroky?** Zkuste předat vygenerovaný `.txt` (nebo jej přejmenovat na `.tex`) do `pdflatex` nebo `xelatex`, abyste vytvořili PDF, nebo prozkoumejte možnost `SaveFormat.LaTeX` pro přímý `.tex` soubor. Pokud potřebujete **save docx as txt** při zachování formátování, experimentujte s `PreserveTableLayout` a vlastním zpracováním zalomení řádků. +Připravený na další krok? Zkuste převést stejný DOCX do Markdownu, nebo nasajte vygenerovaný `.txt` do static‑site generátoru, který renderuje LaTeX na webu. Možnosti jsou neomezené a nyní máte pevný základ pro jakýkoli **convert word to txt** workflow. -Máte otázky ohledně okrajových případů, licencování nebo optimalizací výkonu? Zanechte komentář níže—šťastné kódování! +Šťastné kódování a ať se vám LaTeX kompiluje na první pokus! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/czech/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/czech/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..4b2304b3f9 --- /dev/null +++ b/words/czech/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-01 +description: Uložte Word jako PDF pomocí Aspose.Words v C#. Naučte se převádět docx + na PDF, detekovat chybějící písma a efektivně řešit varování o náhradě písma. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: cs +og_description: Uložte Word jako PDF pomocí Aspose.Words. Tento krok‑za‑krokem návod + ukazuje, jak převést docx na PDF a detekovat chybějící písma. +og_title: Uložte Word jako PDF pomocí Aspose.Words – Kompletní průvodce +tags: +- Aspose.Words +- C# +- PDF conversion +title: Uložte Word jako PDF pomocí Aspose.Words – Kompletní průvodce +url: /cs/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Uložení Wordu jako PDF pomocí Aspose.Words – Kompletní průvodce + +Už jste někdy potřebovali **save Word as PDF** za běhu a přemýšleli, jestli vám někde chybí písmo? Nejste sami — vývojáři se neustále potýkají s problémy chybějících fontů při konverzi dokumentů. V tomto průvodci projdeme praktickým řešením, které nejen **convert docx to pdf**, ale také **detect missing fonts** pomocí varování o substituci fontů v Aspose.Words. + +Probereme vše od nastavení sběrače varování po interpretaci výstupu, takže na konci přesně vědět, jak **save Word as PDF** bez překvapení. Žádné externí nástroje, žádná nejasná nastavení — jen čistý C# kód, který můžete vložit do libovolného .NET projektu. + +## Co budete potřebovat + +- **Aspose.Words for .NET** (nejnovější verze, např. 24.10) – můžete jej získat přes NuGet (`Install-Package Aspose.Words`). +- Vývojové prostředí .NET (Visual Studio, Rider nebo VS Code funguje dobře). +- Vzorek souboru DOCX, který může obsahovat písma neinstalovaná na cílovém počítači. +To je vše. Pokud máte tyto základy, jsme připraveni ponořit se dál. + +## Uložení Wordu jako PDF – Přehled krok za krokem + +Níže je kompletní spustitelný program. Klidně jej zkopírujte a vložte do projektu konzolové aplikace a stiskněte **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Tip:** Nahraďte `YOUR_DIRECTORY` absolutní cestou nebo použijte `Path.Combine(Environment.CurrentDirectory, "input.docx")` pro relativní, bezpečnější přístup. + +### Proč používáme zpětné volání varování + +Aspose.Words tiše nahrazuje chybějící písma náhradním (obvykle Arial). Bez zpětného volání byste nikdy nezjistili, že k substituci došlo, což může vést k poruchám rozvržení v výsledném PDF. Připojením `IWarningCallback` získáme jasný, programový seznam každé události chybějícího písma — ideální pro logování nebo upozorňování koncových uživatelů. + +### Detekce chybějících fontů – Co sledovat + +Když spustíte program, každé chybějící písmo vygeneruje řádek v konzoli podobný: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Pokud je seznam prázdný, gratulujeme — **save word as pdf** se podařilo se všemi původními fonty nedotčeny. + +## Konverze Docx do PDF – Přizpůsobení výstupu + +Někdy potřebujete konkrétní verzi PDF, kvalitu obrázků nebo úroveň souladu. Aspose.Words vám umožní upravit objekt `PdfSaveOptions` před voláním `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Proč je to důležité:** Pokud generujete PDF pro právní archivy, nastavení `PdfA1b` zajišťuje, že soubor splňuje přísné normy. Stejná konverze stále respektuje naše zpětné volání varování, takže stále **detect missing fonts**. + +## Substituce fontů v Aspose Words – Řešení okrajových případů + +### Scénář 1: Více chybějících fontů + +Pokud váš zdrojový dokument používá několik vlastních fontů, sběrač varování bude obsahovat jednu položku na každý font. Můžete je agregovat: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scénář 2: Poskytnutí adresáře s náhradními fonty + +Aspose.Words může prohledávat další složky pro fonty. Nastavte vlastnost `FontsFolder` na `FontSettings` před načtením dokumentu: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Nyní knihovna nejprve zkusí vaši vlastní složku, čímž sníží pravděpodobnost nechtěné substituce. + +### Scénář 3: Ignorování substitucí + +Pokud dáváte přednost, aby konverze selhala, když chybí font (namísto tichého nahrazení), vyhoďte výjimku uvnitř zpětného volání: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Tím vás donutí vyřešit chybějící font před pokračováním — užitečné v CI pipelinech, kde jsou tiché selhání nepřijatelná. + +## Kompletní příklad od začátku do konce + +Spojením všeho dohromady, zde je kompaktní verze, která ukazuje **how to convert Word to PDF**, nastavuje vlastní PDF možnosti a zaznamenává jakékoli problémy s fonty: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Očekávaný výstup v konzoli** (pokud chybí Calibri): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Pokud se neobjeví žádná varování, vaše operace **save word as pdf** použila přesně stejná písma jako zdrojový DOCX. + +## Vizuální shrnutí + +![Diagram pracovního postupu Uložení Wordu jako PDF](https://example.com/diagram.png "Uložení Wordu jako PDF workflow") + +*Text obrázku:* **save word as pdf** workflow zobrazující načítání, sběr varování a výstup PDF. + +## Často kladené otázky a odpovědi + +| Question | Answer | +|----------|--------| +| **Potřebuji licenci pro Aspose.Words?** | Bezplatná evaluační licence funguje pro testování, ale pro produkční použití je potřeba placená licence k odstranění evaluačního vodoznaku. | +| **Bude to fungovat na .NET Core / .NET 6+?** | Rozhodně — Aspose.Words cílí na .NET Standard 2.0, takže jakékoli moderní .NET runtime je kompatibilní. | +| **Mohu konvertovat více souborů DOCX ve smyčce?** | Ano, stačí pro každý soubor vytvořit nový `Document` a pokud chcete agregované výsledky, znovu použít stejný `WarningInfoCollector`. | +| **Co když výstupní složka neexistuje?** | `Document.Save` vyhodí `DirectoryNotFoundException`. Nejprve vytvořte složku nebo použijte `Directory.CreateDirectory`. | +| **Existuje způsob, jak vložit chybějící fonty do PDF?** | Aspose.Words může fonty automaticky vložit, pokud jsou dostupné na počítači; nastavte `PdfSaveOptions.EmbedFullFonts = true`. | + +## Závěr + +Nyní máte robustní, připravený vzor pro **save Word as PDF**, který **detect missing fonts** a řeší scénáře **Aspose.Words font substitution**. Připojením zpětného volání varování, přizpůsobením složek s fonty a volitelným úpravám `PdfSaveOptions` můžete spolehlivě **convert docx to pdf** a udržet své uživatele informované o jakýchkoli problémech s fonty, které by mohly ovlivnit věrnost rozvržení. + +Jste připraveni na další krok? Zkuste generovat PDF z více dokumentů paralelně, nebo prozkoumejte přidávání vodoznaků a digitálních podpisů — obojí jsou jednoduché rozšíření kódu, který jste právě zvládli. Šťastné programování a ať vaše PDF vždy vypadají přesně tak, jak mají! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-loadoptions/_index.md b/words/czech/net/programming-with-loadoptions/_index.md index 917220ae6a..3136cf7737 100644 --- a/words/czech/net/programming-with-loadoptions/_index.md +++ b/words/czech/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ V těchto tutoriálech se naučíte, jak používat LoadOptions k načítání d | [Obnovit dokument Word pomocí Aspose.Words v C#](./recover-word-document-with-aspose-words-in-c/) | Naučte se, jak obnovit poškozený dokument Word pomocí Aspose.Words v jazyce C#. | | [Jak používat LoadOptions v Aspose.Words – Kompletní průvodce](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Kompletní průvodce používáním LoadOptions v Aspose.Words pro .NET – nastavení, optimalizace a praktické ukázky. | | [Obnovit poškozený dokument v C# – nastavit režim obnovy a vyzvat uživatele](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Naučte se, jak obnovit poškozené dokumenty v C# pomocí Aspose.Words nastavením režimu obnovy a výzvou uživateli. | +| [Obnovit poškozený docx – Kompletní průvodce načítáním poškozených souborů Word v C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Kompletní návod, jak načíst a opravit poškozené soubory DOCX v C# pomocí Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/czech/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..8fbb8b7683 --- /dev/null +++ b/words/czech/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Rychle obnovte poškozené soubory docx pomocí Aspose.Words. Naučte se, + jak nastavit režim obnovy, bezpečně načíst docx a číst poškozené soubory Word během + několika kroků. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: cs +og_description: Obnovte poškozené soubory docx v C#. Nastavte režim obnovy, bezpečně + načtěte docx a čtěte poškozené soubory Word pomocí Aspose.Words. +og_title: Obnovit poškozený docx – Rychlý průvodce C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Obnova poškozených docx – Kompletní průvodce načítáním poškozených souborů + Word v C# +url: /cs/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Obnovení poškozených docx – Rychlý průvodce C# + +Už jste někdy zkusili otevřít soubor Word, který se prostě nenačetl, a přemýšleli, jestli je obsah navždy ztracen? V mnoha reálných projektech **recover corrupted docx** soubory obnovíte, aniž byste uživatele žádali o opětovné odeslání přílohy. Dobrou zprávou je, že Aspose.Words to dělá hračkou: jednoduše nastavíte režim obnovy a necháte knihovnu udělat těžkou práci. + +V tomto tutoriálu projdeme přesné kroky k **recover corrupted docx** souborům, vysvětlíme, proč je volba `RecoveryMode.AutoRecover` nejbezpečnější, a ukážeme vám, jak **how to load docx** soubory, které mohou být částečně poškozené. Na konci budete schopni přečíst poškozený Word soubor, extrahovat jakýkoli zachovalý text a dokonce zaznamenat původní formát pro budoucí audity. Žádné externí nástroje, jen čistý C# kód. + +## Co budete potřebovat + +- **Aspose.Words for .NET** (jakákoli recent verze; API, které používáme, funguje s 23.5 a novějšími). +- Vývojové prostředí .NET (Visual Studio, VS Code nebo Rider). +- Poškozený nebo částečně poškozený `.docx`, který chcete zachránit. + +Žádná speciální oprávnění, žádný COM interop a není nutné instalovat Microsoft Office na server. Jednoduché, že? + +## Krok 1: Nastavte režim obnovy na Auto‑Recover + +Když je soubor Word poškozený, výchozí chování načítání vyhodí výjimku a ukončí se. Konfigurací objektu `LoadOptions` řeknete Aspose.Words, aby **set recovery mode** na `AutoRecover`, což prohledá zip balíček, přeskočí nečitelné části a vrátí, co může poskládat. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Proč AutoRecover?** +> Snaží se přečíst co nejvíce, přičemž zachovává objekt dokumentu použitelný. Pokud zvolíte `RecoveryMode.NoRecovery`, načtení selže při první korupci, což podkopává smysl scénářů **recover corrupted docx**. + +## Krok 2: Načtěte dokument s nakonfigurovanými možnostmi + +Nyní, když je nastaven režim obnovy, můžete bezpečně zkusit otevřít soubor. Nahraďte `"YOUR_DIRECTORY/input.docx"` skutečnou cestou k vašemu poškozenému souboru. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Pokud je soubor jen částečně poškozený, instance `Document` bude stále vytvořena. Později můžete zkontrolovat `document.IsStructureValid`, pokud potřebujete další validaci. + +## Krok 3: Ověřte detekovaný formát + +Aspose.Words automaticky detekuje původní formát (DOC, DOCX, ODT atd.). Vytištění této hodnoty vám pomůže potvrdit, že knihovna soubor správně rozpoznala, což je rychlá kontrola po operaci **recover corrupted docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typický výstup: + +``` +Loaded with Docx format. +``` + +I když některé části chyběly, detekce formátu stále uspěje — další výhra pro workflow **recover corrupted docx**. + +## Krok 4: Extrahujte, co můžete + +Jakmile je dokument načten, můžete s ním zacházet jako s jakýmkoli zdravým Word souborem. Níže je stručný příklad, který extrahuje prostý text a vypíše jej do konzole. To ukazuje, že můžete **read damaged word file** obsah bez pádů. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Pokud původní soubor obsahoval tabulky nebo obrázky, které byly poškozené, budou jednoduše vynechány z textového výstupu. Zbytek dokumentu zůstane neporušen. + +## Krok 5: Uložte čistou kopii (volitelné) + +Často budete chtít uživateli po obnově poskytnout novou, čistou verzi souboru. Uložení ve stejném formátu zajišťuje kompatibilitu s jakýmikoli následnými procesy. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Nyní máte **recover damaged docx** soubor, který můžete bezpečně připojit k e‑mailu nebo předat jiné službě. + +## Kompletní funkční příklad + +Spojením všech částí získáte kompletní, připravený program. Vložte jej do nového konzolového projektu, upravte cesty k souborům a stiskněte F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Očekávaný výstup** (předpokládáme, že soubor obsahuje jediný odstavec „Hello world!“ a nějaký poškozený XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Všimněte si, že program nikdy nepadne — i když byl zdrojový soubor částečně poškozený. To je podstata **recover corrupted docx** pomocí Aspose.Words. + +## Časté otázky a okrajové případy + +### Co když je soubor zcela nečitelný? + +I `AutoRecover` má také limity. Pokud je zip kontejner sám poškozený natolik, že jej nelze opravit, Aspose.Words vyhodí `CorruptedFileException`. V takovém případě můžete potřebovat třetí stranu nástroj na opravu zipu, než se pokusíte znovu **recover corrupted docx**. + +### Můžu obnovit jiné formáty (např. `.doc`, `.odt`)? + +Rozhodně. Stejné `LoadOptions` funguje pro jakýkoli formát, který Aspose.Words podporuje. Stačí změnit příponu souboru a knihovna automaticky detekuje původní formát. To znamená, že můžete také **recover damaged docx**‑like soubory jako `.doc` nebo `.rtf` stejným kódem. + +### Jak zacházet s velkými dokumenty, aniž bych načítal vše do paměti? + +U souborů o velikosti gigabajtů můžete povolit **load options** jako `LoadOptions.LoadFormat` nebo streamovat dokument stránku po stránce. Nicméně algoritmus obnovy stále potřebuje přečíst celý balíček, takže očekávejte vyšší využití paměti u velmi velkých poškozených souborů. + +### Existuje způsob, jak zjistit, které části chyběly? + +Po načtení můžete prozkoumat `document.GetChildNodes(NodeType.Any, true)` a porovnat počet s očekávaným základem. Chybějící tabulky, obrázky nebo záhlaví budou jednoduše chybět ve sbírce uzlů. To vám umožní zaznamenat přesně, co bylo **recover damaged docx**, a informovat uživatele. + +## Profesionální tipy pro spolehlivou obnovu + +- **Ověřte velikost vstupního souboru** před načtením; soubor o velikosti nula bajtů vždy selže. +- **Log the `RecoveryMode` result** zachycením `DocumentLoadingException` a uložením zprávy výjimky; často obsahuje vodítka o tom, které části byly přeskočeny. +- **Run the recovery on a background thread** pokud zpracováváte nahrávání v webové službě — toto udržuje požadavek responzivní. +- **Combine with a checksum** (např. MD5) k detekci, zda se obnovený soubor liší od originálu; můžete pak rozhodnout, zda zachovat obě verze. + +## Závěr + +Právě jsme ukázali, jak **recover corrupted docx** soubory v C# nastavením **setting recovery mode** na `AutoRecover`, bezpečným načtením dokumentu, extrakcí jakéhokoli zachovaného textu a volitelným uložením čisté kopie. Tento přístup vám umožní **how to load docx** soubory, které by jinak vyvolaly výjimky, a poskytuje spolehlivý způsob, jak **read damaged word file** obsah bez externích nástrojů. + +Další kroky? Zkuste vyměnit `RecoveryMode.AutoRecover` za `RecoveryMode.NoRecovery` a podívejte se na rozdíl, nebo experimentujte s vlastnostmi `LoadOptions`, které řídí zpracování hesel a substituci fontů. Můžete také integrovat rutinu obnovy do ASP.NET Core API, které přijímá nahrané soubory a vrací opravený soubor — ideální pro podnikové pipeline pro správu dokumentů. + +Máte další otázky ohledně obnovy Word dokumentů, nebo chcete vidět, jak **recover damaged docx** soubory s vlastními zpětnými voláními? Zanechte komentář níže a šťastné kódování! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-markdownsaveoptions/_index.md b/words/czech/net/programming-with-markdownsaveoptions/_index.md index 315442e3d0..cd2d07d468 100644 --- a/words/czech/net/programming-with-markdownsaveoptions/_index.md +++ b/words/czech/net/programming-with-markdownsaveoptions/_index.md @@ -34,6 +34,7 @@ Zpracování textu pomocí MarkdownSaveOptions je podrobný návod, který vás | [Jak uložit Markdown z DOCX – krok za krokem průvodce](./how-to-save-markdown-from-docx-step-by-step-guide/) | Naučte se krok za krokem ukládat soubory DOCX jako Markdown pomocí Aspose.Words pro .NET. | | [Jak exportovat Markdown z DOCX – Kompletní průvodce](./how-to-export-markdown-from-docx-complete-guide/) | Naučte se, jak exportovat Markdown z DOCX pomocí kompletního průvodce. | | [Jak exportovat LaTeX z Wordu: převod DOCX do Markdownu pomocí Aspose](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) | Naučte se převádět soubory DOCX do Markdownu a zachovat LaTeX rovnice pomocí Aspose.Words pro .NET. | +| [Uložení docx jako markdown – Export matematických rovnic z Wordu do LaTeXu pomocí Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Naučte se převádět soubory DOCX do Markdownu a exportovat rovnice Wordu do LaTeXu pomocí Aspose.Words pro .NET. | | [Převod Wordu do Markdownu – Vložit obrázky jako Base64](./convert-word-to-markdown-embed-images-as-base64/) | Naučte se, jak při konverzi Wordu do Markdownu vložit obrázky přímo jako Base64 kód, aby byly soubory samostatné. | | [Jak uložit Markdown z Wordu – Kompletní průvodce v C#](./how-to-save-markdown-from-word-complete-c-guide/) | Kompletní průvodce v C# pro uložení dokumentu Word jako Markdown pomocí Aspose.Words. | | [Jak uložit Markdown z Wordu – Kompletní průvodce](./how-to-save-markdown-from-word-complete-guide/) | Kompletní průvodce pro uložení dokumentu Word jako Markdown pomocí Aspose.Words. | diff --git a/words/czech/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/czech/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..1197f110db --- /dev/null +++ b/words/czech/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Uložte docx jako markdown pomocí Aspose.Words – naučte se převádět Word + do markdownu, exportovat rovnice do LaTeXu a nastavit rozlišení obrázků v markdownu + v jednom plynulém workflow. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: cs +og_description: Uložte docx jako markdown pomocí Aspose.Words. Tento tutoriál ukazuje, + jak převést Word na markdown, exportovat rovnice do LaTeXu a nastavit rozlišení + obrázků v markdownu. +og_title: Uložte docx jako markdown – Kompletní průvodce exportem matematiky z Wordu + do LaTeXu +tags: +- Aspose.Words +- C# +- Document Conversion +title: Uložit docx jako markdown – Exportovat Word Math do LaTeXu pomocí Aspose.Words +url: /cs/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# uložit docx jako markdown – Export Word Math do LaTeXu s Aspose.Words + +Už jste někdy potřebovali **save docx as markdown**, ale uvízli jste v tom, jak zachovat rovnice Office Math ostré? Nejste v tom sami. Většina vývojářů narazí na problém, když výchozí konverze převádí rovnice na rozmazané obrázky, což nutí je ručně přepsat do LaTeXu. + +Dobrá zpráva: Aspose.Words může udělat těžkou práci za vás. V tomto tutoriálu **convert word to markdown**, řekneme enginu **export equations to latex** a dokonce **set markdown image resolution** pro zbytek dokumentu. Na konci budete mít jediný příkaz, který vytvoří čistý soubor `.md` s matematikou připravenou pro LaTeX a obrázky ve vysokém rozlišení. + +## Co se naučíte + +- Jak načíst `.docx`, který obsahuje objekty Office Math. +- Které vlastnosti `MarkdownSaveOptions` řídí **export equations to latex** a **set markdown image resolution**. +- Kompletní, spustitelný úryvek C# kódu, který můžete vložit do libovolného .NET projektu. +- Tipy pro řešení běžných problémů, jako chybějící fonty nebo nepodporované funkce rovnic. + +**Prerequisites**: .NET 6+ (nebo .NET Framework 4.6+), licence na Aspose.Words pro .NET a základní znalost C#. Pokud vám nevadí vytvořit konzolovou aplikaci, jste připraveni začít. + +--- + +## Krok 1 – Uložit docx jako markdown: Načtěte svůj Word soubor + +První věc, kterou potřebujeme, je objekt `Document`, který ukazuje na zdrojový `.docx`. Představte si to jako otevření knihy, než začnete kopírovat kapitoly. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Why this matters*: Pokud dokument neobsahuje žádnou matematiku, krok **export equations to latex** nebude mít žádný efekt, ale zbytek konverze se stále provede. Tento kontrolní krok vás ochrání před otázkou, proč ve výstupním Markdownu chybí LaTeX bloky. + +--- + +## Krok 2 – Nastavit Export rovnic do LaTeXu + +Aspose.Words vám umožňuje rozhodnout, jak má být Office Math vykreslen. Ve výchozím nastavení je převádí na PNG obrázky, což je důvod, proč mnoho tutoriálů končí s hrubým markdown souborem. Přepnutím `OfficeMathExportMode` na `LaTeX` získáte čisté rovnice připravené ke kopírování a vložení. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Why `OfficeMathExportMode.LaTeX`?* LaTeX je lingua franca vědeckého publikování. Když později vykreslíte markdown pomocí static‑site generátoru nebo Jupyter notebooku, rovnice budou ostré při jakémkoli zvětšení. + +--- + +## Krok 3 – Nastavit rozlišení obrázků v Markdownu (pro obsah bez rovnic) + +I když se zaměřujeme na matematiku, většina Word dokumentů také obsahuje obrázky, grafy nebo vložené SVG. Vlastnost `ImageResolution` určuje, jak Aspose.Words rasterizuje tyto assety. Hodnota **300 DPI** je ideální pro obrazovku i tisk. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: Pokud bude váš markdown zobrazován jen na webu, můžete snížit rozlišení na 150 DPI, aby se zmenšila velikost souboru. Naopak pro tiskové PDF zvyšte na 600 DPI. + +--- + +## Krok 4 – Spustit konverzi – Převést Word Math do LaTeXu + +Nyní, když je vše nastaveno, samotná konverze je jediný řádek kódu. Aspose.Words provádí těžkou práci v pozadí. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: Otevřete vygenerovaný soubor `.md` a měli byste vidět něco jako: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Všimněte si LaTeX bloků (`$...$` a `$$...$$`), které nahrazují předchozí PNG úryvky. Obrázek na konci je stále PNG, vykreslený s 300 DPI, jak jsme požadovali. + +--- + +## Krok 5 – Běžné okrajové případy a jak je řešit + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (e.g., Cambria Math not installed) | LaTeX output may contain unknown symbols. | Install the missing font on the server or embed it in the document before conversion. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words may fall back to an image despite `LaTeX` mode. | Upgrade to the latest Aspose.Words version; the library continuously improves equation coverage. | +| **Large documents** ( > 50 MB ) | Memory pressure can cause `OutOfMemoryException`. | Use `LoadOptions` with `LoadFormat.Docx` and stream the file, or split the document into sections before conversion. | +| **Image size too big** | Markdown file becomes huge, slowing down static‑site builds. | Reduce `ImageResolution` to 150 DPI for web‑only scenarios (see Step 3). | + +--- + +## Krok 6 – Sestavit vše dohromady: Kompletní funkční příklad + +Níže je *complete* console‑app program, který můžete zkopírovat a vložit do `Program.cs`. Obsahuje všechny části, o kterých jsme mluvili, plus trochu extra ošetření chyb. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Spusťte program (`dotnet run`) a získáte markdown soubor, který **save docx as markdown** a zachovává každou rovnici jako LaTeX. Žádné ruční kopírování, žádné ošklivé rastrové obrázky pro matematiku. + +--- + +## Závěr + +Prošli jsme celý proces **saving docx as markdown** s Aspose.Words, od načtení Word souboru po nastavení **export equations to latex** a **set markdown image resolution**. Výsledný úryvek je připravený pro produkci a můžete jej vložit do libovolného .NET projektu, který potřebuje **convert word to markdown** za běhu. + +Co dál? Zkuste vložit vygenerovaný `.md` do static‑site generátoru jako Hugo nebo Jekyll a sledujte, jak se vaše rovnice krásně vykreslí. Pokud potřebujete **convert word math latex** do jiných formátů (PDF, HTML), stačí vyměnit `MarkdownSaveOptions` za `PdfSaveOptions` nebo `HtmlSaveOptions` — stejný příznak `OfficeMathExportMode` funguje i v nich. + +Máte v pracovním postupu nějaký twist, například načítání Word souborů z Azure Blob storage nebo streamování z API? Stejný vzor platí; jen nahraďte konstruktor `Document` pracující se souborovým systémem verzí založenou na streamu. + +Klidně experimentujte a dejte nám vědět v komentářích, jak vám tento přístup pomohl vyřešit problémy s konverzí. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-pdfsaveoptions/_index.md b/words/czech/net/programming-with-pdfsaveoptions/_index.md index 27f978a289..538f693428 100644 --- a/words/czech/net/programming-with-pdfsaveoptions/_index.md +++ b/words/czech/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ Ať už chcete převést dokumenty Wordu do PDF pro online distribuci, archivaci | [Renderování 3D DML 3DEfektů v PDF dokumentu](./dml-3deffects-rendering/) | Naučte se, jak vykreslit úžasné 3D DML efekty v PDF dokumentech pomocí Aspose.Words pro .NET s tímto komplexním podrobným návodem. | | [Interpolace obrázků v dokumentu PDF](./interpolate-images/) | Naučte se, jak interpolovat obrázky v PDF dokumentu pomocí Aspose.Words pro .NET s naším podrobným návodem. Snadno vylepšete kvalitu obrázků ve vašem PDF. | | [Uložte docx jako pdf pomocí Aspose.Words – Kompletní průvodce C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Kompletní průvodce převodem souborů DOCX do PDF v C# pomocí Aspose.Words. | +| [Uložte dokument jako PDF pomocí Aspose.Words – Kompletní průvodce C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Kompletní průvodce převodem dokumentů do PDF v C# pomocí Aspose.Words. | | [Vytvořte přístupný PDF z Wordu pomocí C# – krok za krokem průvodce](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Naučte se, jak pomocí Aspose.Words pro .NET vytvořit PDF s přístupností z dokumentu Word v C#. | | [Vytvoření přístupného PDF v C# – PDF přístupnost](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Naučte se, jak v C# vytvořit PDF soubor splňující požadavky přístupnosti, včetně značek a struktury pro čtečky obrazovky. | | [Vytvořte přístupný PDF z Wordu – Kompletní průvodce](./create-accessible-pdf-from-word-complete-guide/) | Naučte se, jak pomocí Aspose.Words pro .NET vytvořit přístupný PDF soubor z dokumentu Word s kompletním návodem. | diff --git a/words/czech/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/czech/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..11ecac7661 --- /dev/null +++ b/words/czech/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-01 +description: Naučte se, jak uložit dokument jako PDF pomocí Aspose.Words v C#. Tutoriál + také zahrnuje převod Wordu do PDF, export matematického LaTeXu a řešení chybějících + fontů. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: cs +og_description: Uložte dokument jako PDF snadno s Aspose.Words. Tento průvodce také + ukazuje, jak převést Word do PDF, exportovat matematiku do LaTeXu a řešit chybějící + písma. +og_title: Uložte dokument jako PDF pomocí Aspose.Words – Kompletní průvodce C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Uložení dokumentu jako PDF s Aspose.Words – Kompletní průvodce C# +url: /cs/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Uložení dokumentu jako PDF pomocí Aspose.Words – Kompletní průvodce v C# + +Už jste se někdy zamysleli **jak uložit dokument jako pdf** přímo ze souboru Word, aniž byste ztratili funkce přístupnosti? Nejste v tom sami – vývojáři neustále požadují spolehlivý způsob, jak převést Word na PDF při zachování matematických rovnic a elegantním zacházení s chybějícími fonty. + +V tomto tutoriálu vás provedeme krok za krokem řešením, které nejen **save document as pdf**, ale také ukazuje **convert word to pdf**, **export math latex** a **handle missing fonts** pomocí nejnovější verze Aspose.Words pro .NET. Na konci budete mít připravený program v C#, který vytváří soubory splňující PDF/UA‑2, ideální pro audity přístupnosti. + +## Co budete potřebovat + +- .NET 6 nebo novější (kód funguje také s .NET Core a .NET Framework) +- Aspose.Words pro .NET 25.10 nebo novější – můžete si stáhnout bezplatnou zkušební verzi na webu Aspose +- Jednoduchý dokument Word (`input.docx`), který obsahuje alespoň jeden plovoucí tvar a matematickou rovnici (abyste viděli funkci export‑math‑latex v akci) +- Visual Studio 2022 (nebo jakékoli IDE, které preferujete) + +> **Tip:** Pokud používáte CI/CD pipeline, přidejte balíček Aspose.Words NuGet do souboru projektu: + +```xml + +``` + +Pojďme se ponořit do kódu. + +## Krok 1: Načtení zdrojového dokumentu s automatickým zotavením + +Při práci se skutečnými soubory Word můžete narazit na poškozené sekce nebo chybějící zdroje. Povolení automatického zotavení zajišťuje, že proces načítání nikdy nevyhodí výjimku. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Proč je to důležité:** +`RecoveryMode.AutoRecover` chrání váš pipeline před zhroucením při poškozených vstupech, což je obzvláště užitečné, když **convert word to pdf** hromadně. + +## Krok 2: Nastavení možností uložení PDF pro plnou přístupnost + +PDF/UA‑2 je standard ISO pro přístupná PDF. Nastavením několika příznaků získáme soubor, který mohou čtečky obrazovky procházet, a také zajistíme, aby matematické rovnice byly exportovány jako skrytý LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Klíčové body:** + +- **ExportFloatingShapesAsInlineTag** – zajišťuje, že výsledné PDF respektuje původní rozvržení a zároveň je sémanticky správné. +- **OfficeMathExportMode.LaTeX** – splňuje požadavek **export math latex**, což umožňuje následným nástrojům extrahovat rovnice, pokud je to potřeba. + +## Krok 3: Zachycení varování (např. chybějící fonty) + +Chybějící fonty jsou častou bolestí hlavy při převodu dokumentů. Aspose.Words může tyto problémy hlásit pomocí `WarningCallback`. Shromáždíme je, abyste je mohli později zaznamenat nebo na ně reagovat. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Proč vám to může být důležité:** +Pokud zdroj používá font, který není na serveru nainstalován, PDF přejde na výchozí font, což může rozbít rozvržení. Pomocí **handle missing fonts** můžeme uživatele upozornit nebo vložit náhradní font. + +## Krok 4: Uložení dokumentu jako přístupného PDF + +Nyní nastává okamžik pravdy – samotná konverze. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Pokud vše proběhne hladce, získáte soubor PDF/UA‑2, který obsahuje skrytý LaTeX pro každou rovnici a správné označení pro plovoucí tvary. + +## Krok 5: Přezkoumání zachycených varování (volitelné, ale doporučené) + +Po operaci uložení můžete projít shromážděná varování a zaznamenat je. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typický výstup může vypadat takto: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Včasné zobrazení těchto zpráv vám pomůže **handle missing fonts**, než ovlivní koncové uživatele. + +## Kompletní funkční příklad + +Spojením všeho dohromady zde máte kompletní, připravený program. Nahraďte zástupné cesty svými vlastními. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Očekávaný výsledek:** + +- `output.pdf` splňuje PDF/UA‑2. +- Všechny plovoucí tvary jsou označeny jako inline obrázky. +- Každý objekt Office Math se zobrazí jako skrytý LaTeX (viditelný při inspekci struktury PDF). +- Jakékoli problémy související s fonty jsou vytištěny do konzole, což vám dává šanci **handle missing fonts** před odesláním souboru. + +![Diagram ukazující tok od Word → Aspose.Words → Přístupné PDF (save document as pdf)](conversion-diagram.png "Diagram toku pro uložení dokumentu jako pdf") + +*Text obrázku:* **Diagram, jak uložit dokument jako pdf pomocí Aspose.Words** + +## Časté otázky a okrajové případy + +### Co když používám starší verzi Aspose.Words? + +`OfficeMathExportMode.LaTeX` příznak byl zaveden ve verzi 25.10. Pro starší verze můžete stále **convert word to pdf**, ale matematika bude rasterizována místo exportu jako LaTeX. Pro nejlepší přístupnost proveďte upgrade. + +### Mohu vložit vlastní fonty, aby se zabránilo náhradě? + +Ano. Nastavte `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` před voláním `Save`. To také pomáhá **handle missing fonts**, protože PDF bude obsahovat požadované glyfy. + +### Jak ověřím soulad s PDF/UA‑2? + +Otevřete soubor v Adobe Acrobat Pro → “Print Production” → “Preflight”. Vyberte profil “PDF/A‑2b” nebo “PDF/UA‑2”; Acrobat nahlásí případné porušení. + +### Co s Word soubory chráněnými heslem? + +Načtěte dokument s `LoadOptions`, který obsahuje `Password`. Příklad: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Zbytek pipeline zůstává beze změny. + +## Závěr + +Probrali jsme vše, co potřebujete k **save document as pdf** pomocí Aspose.Words v C#. Tutoriál také ukázal, jak **convert word to pdf**, **export math latex** a **handle missing fonts** – vše při tvorbě přístupného souboru PDF/UA‑2. + +Vyzkoušejte kód, experimentujte s různými `PdfSaveOptions` (např. komprese obrázků, PDF/A‑2b) a integrujte jej do své služby pro zpracování dokumentů. Pokud potřebujete jít dál, zvažte prozkoumání PDF‑specifické knihovny Aspose pro post‑processing nebo digitální podpisy. + +Máte další scénáře, které byste chtěli řešit? Neváhejte zanechat komentář nebo si prohlédnout naše další průvodce o **PDF manipulation**, **image extraction** a **batch conversion**. Šťastné programování! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-shapes/_index.md b/words/czech/net/programming-with-shapes/_index.md index f1362b81b6..935b370547 100644 --- a/words/czech/net/programming-with-shapes/_index.md +++ b/words/czech/net/programming-with-shapes/_index.md @@ -35,9 +35,9 @@ Používáním Aspose.Words pro .NET a podle těchto tutoriálů zvládnete mani | [Aktualizace kresby Smart Art](./update-smart-art-drawing/) | Naučte se, jak aktualizovat kresby Smart Art v dokumentech Wordu pomocí Aspose.Words pro .NET s tímto podrobným návodem. Zajistěte, aby vaše vizuální prvky byly vždy přesné. | | [Vytvořit obdélníkový tvar ve Wordu s Aspose.Words – krok za krokem](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Naučte se, jak pomocí Aspose.Words vytvořit obdélníkový tvar ve Wordu krok za krokem. | | [Vytvořit obdélníkový tvar ve Wordu pomocí C# – krok za krokem](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Naučte se, jak vytvořit obdélníkový tvar ve Wordu pomocí C# s podrobným krok za krokem návodem. | - | [Aspose.Words – Stín tvaru – Přidání stínu do tvaru Wordu v C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Naučte se, jak přidat stín k tvaru ve Wordu pomocí Aspose.Words pro .NET v jazyce C#. | | [Vytvořit prázdný dokument Word se stínovaným obdélníkovým tvarem – krok za krokem](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Naučte se, jak vytvořit prázdný dokument Word a přidat do něj stínovaný obdélníkový tvar pomocí Aspose.Words pro .NET. | +| [Jak přesunout stín v Aspose.Words – kompletní průvodce C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Naučte se, jak přesunout stín tvaru v dokumentech Word pomocí Aspose.Words pro .NET v jazyce C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/czech/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..a5d90d5f62 --- /dev/null +++ b/words/czech/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Jak přesunout stín na tvaru v Aspose.Words pomocí C#. Naučte se přidat + stín k tvaru, změnit rozostření, nastavit průhlednost a otočit stín během několika + minut. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: cs +og_description: Jak přesunout stín na tvaru v Aspose.Words pomocí C#. Tento tutoriál + vám ukáže, jak přidat stín k tvaru, změnit rozostření, nastavit průhlednost a otáčet + stín. +og_title: Jak přesunout stín v Aspose.Words – Kompletní průvodce C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Jak přesunout stín v Aspose.Words – kompletní průvodce C# +url: /cs/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak přesunout stín v Aspose.Words – Kompletní průvodce v C# + +Už jste se někdy zamysleli, **jak přesunout stín** na tvar uvnitř dokumentu Word, aniž byste Word otevírali ručně? V mé každodenní práci jsem často potřeboval programově upravit stín tvaru — ať už pro vylepšenou zprávu nebo dynamickou šablonu. Dobrá zpráva? S Aspose.Words to zvládnete během několika řádků a zároveň se naučíte **přidat stín k tvaru**, **jak změnit rozostření**, **jak nastavit průhlednost** a **jak otočit stín** najednou. + +V tomto tutoriálu projdeme reálný scénář: načteme existující DOCX, který už obsahuje tvar, upravíme pozici, měkkost, neprůhlednost a směr stínu a nakonec výsledek uložíme. Na konci budete mít znovupoužitelný úryvek, který můžete vložit do libovolného .NET projektu, a pochopíte, proč je každá vlastnost důležitá. + +## Požadavky – Co potřebujete před začátkem + +- **Aspose.Words for .NET** (verze 23.12 nebo novější). Můžete jej získat z NuGet pomocí `Install-Package Aspose.Words`. +- Vývojové prostředí .NET 6+ (Visual Studio, VS Code, Rider — co vám vyhovuje). +- Vstupní soubor Word (`input.docx`), který již obsahuje alespoň jeden tvar (obdélník, kruh nebo obrázek stačí). +- Základní znalost syntaxe C# — nic složitého. + +Pokud vám něco chybí, na chvíli zastavte a nainstalujte knihovnu; zbytek průvodce předpokládá, že balíček je již referencován. + +## Krok 1: Načtení dokumentu a získání cílového tvaru – **Jak přesunout stín** začíná zde + +Prvním krokem je načíst zdrojový dokument a najít tvar, který chceme upravit. Aspose.Words zachází s každým objektem (odstavci, tabulkami, tvary) jako s uzlem ve stromu, takže jej můžeme dotazovat přímo. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Proč je to důležité:** Načíst dokument jen jednou a znovu použít stejnou instanci `Document` je efektivní. Volání `GetChild` je bezpečné, protože vrátí `null`, pokud je index mimo rozsah, což nám umožní elegantně ošetřit chybějící tvary. + +## Krok 2: Úprava poloměru rozostření – Ovládněte **Jak změnit rozostření** + +Měkký stín vypadá profesionálně, zatímco tvrdý okraj může působit levně. Vlastnost `BlurRadius` řídí měkkost v bodech (1 pt ≈ 1/72 palce). Zvýšíme ji na 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Tip:** Výchozí rozostření je 0,5 pt. Hodnota nad 5 pt je obvykle patrná, ale dejte pozor, aby nebyla příliš velká — může způsobit, že se tvar bude jevit odtržený od stránky. + +## Krok 3: Nastavení průhlednosti – Odpověď na **Jak nastavit průhlednost** + +Průhlednost určuje, jak moc je stín průhledný. Hodnota `0` znamená plně neprůhledný; `1` znamená zcela neviditelný. Pro decentní efekt použijeme `0.3` (30 % průhlednosti). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Proč by vás to mohlo zajímat:** Pokud je tvar tmavý, plně neprůhledný stín může zahltit podkladový text. Úprava průhlednosti zachová čitelnost dokumentu a zároveň přidá hloubku. + +## Krok 4: Posunutí stínu – Jádro **Jak přesunout stín** + +Vlastnost `Distance` určuje, jak daleko je stín odsazen od tvaru, měřeno v bodech. Větší vzdálenost posune stín dál, čímž vytvoří dramatický efekt. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Co když potřebujete jen malý posun?** Nastavením `Distance` na `0` získáte stín přímo za tvarem, což se hodí pro efekty embosování. + +## Krok 5: Otočení světelného zdroje – Řešení **Jak otočit stín** + +Stíny nejsou jen přímo dolů; následují úhel světelného zdroje. Vlastnost `Angle` (ve stupních) otáčí stín kolem tvaru. Nakloníme ho o 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Rychlý experiment:** Zkuste `90` pro pravostranný stín nebo `-30` pro levostranný. Změna je okamžitá. + +## Krok 6: Uložení dokumentu – Výsledek **Přidat stín k tvaru** + +Po úpravě stínu dokument zapíšeme zpět na disk. Můžete přepsat originál nebo vytvořit nový soubor; příklad používá nový výstupní soubor. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Očekávaný výstup:** Otevřete `output.docx`. Stín tvaru bude měkčí, mírně odsazený, poloprůhledný a natočený o 45°. Pokud jej porovnáte vedle `input.docx`, rozdíl bude nepopiratelný. + +### Kompletní funkční příklad (připravený ke zkopírování) + +Níže je celý program v jednom bloku. Vložte jej do nového konzolového projektu, nahraďte `YOUR_DIRECTORY` skutečnou cestou ke složce a spusťte. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Často kladené otázky a okrajové případy + +### Co když dokument obsahuje více tvarů? + +Můžete projít všechny tvary ve smyčce: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Mohu přidat stín k tvaru, který jej zatím nemá? + +Ano. Objekt `ShadowFormat` je vždy přítomen; stačí jej povolit: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Funguje to i s obrázky a SmartArt? + +Ano. Každý uzel, který dědí z `Shape` — včetně obrázků, grafů a SmartArt — exponuje `ShadowFormat`. Stejné vlastnosti platí. + +### Jak ovládat barvu stínu? + +Použijte vlastnost `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Problémy s kompatibilitou? + +Aspose.Words 23.12+ podporuje .NET 6, .NET Core 3.1 a .NET Framework 4.6.2+. Ukázané API je stabilní napříč těmito verzemi. + +## Závěr + +Právě jsme prošli **jak přesunout stín** na tvar pomocí Aspose.Words a zároveň jsme ukázali **přidat stín k tvaru**, **jak změnit rozostření**, **jak nastavit průhlednost** a **jak otočit stín**. Kompletní, spustitelný příklad vám umožní během několika sekund upravit stín libovolného tvaru a dodat dokumentům profesionální vzhled, aniž byste kdykoli otevírali Word. + +Jste připraveni na další krok? Zkuste kombinovat tyto úpravy stínu s **podmíněným formátováním** — například aplikovat výraznější stín jen na nadpisy nebo na grafy, které překročí určitou velikost. Nebo prozkoumejte **gradientní výplně** samotného tvaru pro opravdu poutavý design. + +Pokud narazíte na potíže, zanechte komentář níže. Šťastné programování a ať vaše stíny vždy dopadnou tam, kde chcete! + +![Diagram ukazující efekt přesunu stínu na tvar – příklad jak přesunout stín](https://example.com/images/shadow-demo.png "příklad jak přesunout stín") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/basic-conversions/_index.md b/words/dutch/net/basic-conversions/_index.md index c69db7f2a6..211f2d289a 100644 --- a/words/dutch/net/basic-conversions/_index.md +++ b/words/dutch/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Basisconversies begeleidt u door basisdocumentconversies met behulp van de Aspos | [PDF opslaan in Word-formaat (Docx)](./pdf-to-docx/) | Leer hoe u een PDF naar een Word-document (Docx) converteert met Aspose.Words voor .NET in deze gedetailleerde, stapsgewijze handleiding. Perfect voor ontwikkelaars. | | [Hoe LaTeX vanuit Word exporteren – Stapsgewijze handleiding](./how-to-export-latex-from-word-step-by-step-guide/) | Leer hoe u LaTeX vanuit Word kunt exporteren met Aspose.Words voor .NET in een stapsgewijze handleiding. | | [Word opslaan als PDF met Aspose.Words – Complete C#-gids](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Leer hoe u Word-documenten naar PDF converteert met Aspose.Words in C# met een volledige stap‑voor‑stap gids. | +| [Word opslaan als PDF met Aspose.Words – Complete gids](./save-word-as-pdf-with-aspose-words-complete-guide/) | Leer hoe u Word-documenten naar PDF converteert met Aspose.Words in een volledige stap‑voor‑stap gids. | | [Docx opslaan als PDF met Aspose.Words – Complete C#-gids](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Leer hoe u een DOCX-bestand opslaat als PDF met Aspose.Words in C#, stap‑voor‑stap met voorbeeldcode. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/dutch/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 780df93849..182c79219d 100644 --- a/words/dutch/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/dutch/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,26 +1,24 @@ --- category: general -date: 2025-12-29 -description: Hoe LaTeX exporteren vanuit Word met Aspose.Words – leer Word naar LaTeX - converteren, docx opslaan als txt, en vergelijkingen in platte tekst verwerken. +date: 2026-05-01 +description: Leer hoe u LaTeX uit een Word‑bestand kunt exporteren, Word naar txt + kunt converteren en tabellen kunt behouden met Aspose.Words in C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: nl -og_description: Hoe LaTeX exporteren vanuit Word met Aspose.Words. Deze gids laat - zien hoe je Word naar LaTeX converteert, docx opslaat als txt, en formules intact - houdt. -og_title: Hoe LaTeX vanuit Word exporteren – Snelle C#‑tutorial +og_description: Ontdek hoe u LaTeX vanuit Word kunt exporteren, Word naar platte tekst + kunt converteren en de tabelindeling intact houdt met Aspose.Words. +og_title: Hoe LaTeX vanuit Word exporteren – Complete C#-tutorial tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: Hoe LaTeX vanuit Word te exporteren – Stapsgewijze handleiding +title: Hoe LaTeX uit Word te exporteren – Stapsgewijze handleiding url: /nl/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -28,178 +26,213 @@ url: /nl/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Hoe LaTeX exporteren vanuit Word – Stapsgewijze handleiding +# Hoe LaTeX exporteren vanuit Word – Complete C# Tutorial -Heb je je ooit afgevraagd **hoe je LaTeX kunt exporteren vanuit Word** zonder die lastige Office‑Math‑vergelijkingen te verliezen? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur aan wanneer ze *Word naar LaTeX converteren* voor academische papers, wetenschappelijke rapporten of geautomatiseerde publicatie‑pipelines. +Heb je je ooit afgevraagd **how to export LaTeX** vanuit een Word‑document zonder een van de wiskundige vergelijkingen te verliezen? Je bent niet de enige. Veel ontwikkelaars moeten een .docx die Office Math bevat omzetten naar schone LaTeX terwijl ze ook **convert Word to txt** voor downstream verwerking. In deze gids lopen we een praktische, kant‑klaar oplossing door die **preserves tables**, je een platte‑tekst‑bestand geeft, en de LaTeX‑opmaak precies behoudt waar je die nodig hebt. -In deze tutorial lopen we een compleet, kant‑klaar C#‑voorbeeld door dat **laat zien hoe je LaTeX exporteert** met Aspose.Words, uitlegt **hoe je txt‑bestanden opslaat** met LaTeX‑opmaak, en behandelt zelfs de nuances van **convert word equations latex** zodat er niets verloren gaat in de vertaling. - -> **Pro tip:** dezelfde aanpak werkt voor elk .docx‑bestand dat je hebt—wijs de code gewoon naar een ander pad. - ---- +We zullen alles behandelen, van het laden van het bronbestand tot het aanpassen van `TxtSaveOptions` zodat de output zowel mens‑leesbaar als machine‑vriendelijk is. Aan het einde kun je **save docx as txt**, **convert Word to plain text**, en weet je **how to preserve tables** tijdens de export. Geen externe scripts, geen handmatig kopiëren‑plakken—alleen pure C#‑code die je in elk .NET‑project kunt plaatsen. ## Wat je nodig hebt -Voordat we beginnen, zorg dat je de volgende vereisten hebt: - -| Vereiste | Waarom het belangrijk is | -|--------------|----------------| -| **.NET 6.0+** (of .NET Framework 4.6+) | Aspose.Words richt zich op moderne .NET‑runtimes. | -| **Aspose.Words for .NET** NuGet‑package (`Aspose.Words`) | De bibliotheek doet het zware werk van het parsen van Word en het genereren van LaTeX. | -| **Een voorbeeld‑.docx** met minstens één Office‑Math‑vergelijking | Om de LaTeX‑conversie in actie te zien. | -| **Visual Studio 2022** (of een IDE naar keuze) | Maakt debuggen en uitvoeren van het voorbeeld eenvoudig. | - -Als je het NuGet‑package nog niet hebt geïnstalleerd, voer dan uit: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (latest version, 2024.x or newer). De NuGet‑package is `Aspose.Words`. +- Een .NET‑ontwikkelomgeving (Visual Studio, VS Code, Rider—elk is geschikt). +- Een Word‑bestand (`.docx`) dat Office Math‑vergelijkingen bevat en minstens één tabel (zodat we de tabel‑preserving magie kunnen zien). -Dat is alles—geen extra DLL’s, geen COM‑interop, alleen een schone managed library. +Dat is alles. Als je die al hebt, lees dan verder; anders haal je de NuGet‑package en een voorbeeld‑DOCX voordat we dieper ingaan. --- -## Hoe LaTeX exporteren vanuit Word – Overzicht +## Hoe LaTeX exporteren vanuit een Word‑document -Hieronder zie je het grote plaatje van wat we gaan bereiken: +Hieronder staat het hart van de tutorial—drie beknopte stappen die de vraag **how to export latex** beantwoorden, terwijl ze ook de secundaire doelen van **convert word to txt**, **convert word to plain text**, **save docx as txt**, en **how to preserve tables** behandelen. -1. **Laad** het bron‑Word‑document (`.docx`). -2. **Configureer** `TxtSaveOptions` zodat alle Office‑Math‑objecten worden uitgegeven als LaTeX‑code. -3. **Sla** het document op als een platte‑tekst (`.txt`)‑bestand dat je direct kunt voeren aan elke LaTeX‑compiler. +### Stap 1: Laad het DOCX‑bestand -![Voorbeeld van LaTeX exporteren vanuit Word](image.png "Voorbeeld van LaTeX exporteren vanuit Word") - ---- - -## Stap 1: Het Word‑document laden - -Allereerst—open de .docx die je wilt converteren. De `Document`‑klasse abstraheert alle onderliggende XML en biedt je een gebruiksvriendelijk objectmodel. +Eerst moeten we het Word‑document lezen in een `Aspose.Words.Document`‑object. Deze stap is hetzelfde, of je later **convert word to txt** of **save docx as txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Waarom dit belangrijk is:** -Het vroegtijdig laden van het bestand stelt ons in staat de inhoud te inspecteren (bijv. het aantal vergelijkingen) voordat we beslissen hoe we het gaan serialiseren. Als het bestand corrupt is, gooit `Document` een duidelijke uitzondering, waardoor je later geen mysterieus resultaat krijgt. +> **Why this matters:** Het laden van het bestand creëert een in‑memory representatie van alle Word‑elementen—paragrafen, tabellen en Office Math‑objecten. Zonder dit object kun je exportopties niet manipuleren. ---- +### Stap 2: Configure `TxtSaveOptions` voor LaTeX en Tabelindeling -## Stap 2: TxtSaveOptions configureren voor LaTeX‑export +De `TxtSaveOptions`‑klasse laat je precies bepalen hoe het platte‑tekst‑bestand wordt gegenereerd. Twee eigenschappen zijn cruciaal voor ons scenario: -De magie gebeurt in `TxtSaveOptions`. Door `OfficeMathExportMode` op `LaTeX` te zetten, wordt elk Office‑Math‑object omgezet naar de bijbehorende LaTeX‑representatie. +| Eigenschap | Wat het doet | Waarom je het nodig hebt | +|------------|--------------|--------------------------| +| `OfficeMathExportMode` | Bepaalt hoe Office Math wordt gerenderd. Instellen op `LaTeX` zet vergelijkingen om naar LaTeX‑syntaxis. | Dit is de kern van **how to export latex**. | +| `PreserveTableLayout` | Wanneer `true`, voegt Aspose witruimte toe zodat tabellen een raster‑achtige weergave behouden. | Dit voldoet aan **how to preserve tables** terwijl je **convert word to txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Waarom we deze instellingen kiezen:** +> **Pro tip:** Als je alleen de ruwe LaTeX nodig hebt zonder tabelopmaak, stel `PreserveTableLayout` in op `false`. Het bestand wordt kleiner, maar je verliest de visuele tabelindicatie. -- `OfficeMathExportMode.LaTeX` is de enige modus die een getrouwe wiskundige vertaling garandeert. -- `PreserveTableLayout` behoudt tabellen zoals ze in Word verschijnen, wat handig is wanneer je de output later in een LaTeX `tabular`‑omgeving embedt. -- UTF‑8 zorgt ervoor dat tekens zoals “α”, “β” of “∑” de round‑trip overleven. +### Stap 3: Sla het document op als platte tekst -Als je ooit **convert word to latex** wilt uitvoeren zonder de platte‑tekst‑wrapper, kun je overschakelen naar `SaveFormat.LaTeX`—een snelle tip voor gevorderde scenario’s. +Nu schrijven we het document naar een `.txt`‑bestand met de opties die we zojuist hebben gedefinieerd. Deze ene regel voert **convert word to plain text**, **save docx as txt**, en uiteraard **how to export latex** in één keer uit. ---- +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` -## Stap 3: Het document opslaan als tekstbestand +Na het voltooien van de aanroep, open `output.txt`. Je ziet: -Nu schrijven we de LaTeX‑rijke tekst naar schijf. Het resulterende `.txt`‑bestand kan later worden hernoemd naar `.tex`, of direct worden gepiped naar een LaTeX‑compiler. +- LaTeX‑fragmenten zoals `\frac{a}{b}` voor elke Office Math‑vergelijking. +- Tabellen weergegeven met `|` en `-` tekens, waarbij kolomuitlijning behouden blijft. +- Reguliere paragrafen als platte tekst, klaar voor elke downstream parser. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Volledig werkend voorbeeld + +Alles bij elkaar genomen, hier is een zelfstandige programma dat je vandaag kunt compileren en uitvoeren: -// Save using the configured options -doc.Save(outputPath, txtOptions); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Wat je zult zien in `output.txt`:** +**Verwachte output** (fragment): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Alle andere alinea’s verschijnen als platte tekst, terwijl elke Office‑Math‑vergelijking wordt omgeven door een LaTeX `equation`‑omgeving (of `inline` als het inline in Word stond). Dit voldoet perfect aan de **convert word equations latex**‑vereiste. +Merk op hoe de tabel zijn raster behoudt en de vergelijking verschijnt als schone LaTeX. Dat is de ideale situatie wanneer je **convert word to txt** en toch een getrouwe weergave van zowel structuur als wiskunde nodig hebt. --- -## Randgevallen & Veelgestelde vragen +## Tips voor het converteren van Word naar TXT en het behouden van tabellen -| Situatie | Wat te doen | -|-----------|------------| -| **Geen vergelijkingen in de bron** | De conversie werkt nog steeds; je krijgt alleen platte tekst. Er wordt geen extra LaTeX‑code toegevoegd. | -| **Zeer grote documenten (>100 MB)** | Overweeg de output te streamen met `MemoryStream` om hoog geheugenverbruik te vermijden. | -| **Niet‑ondersteunde wiskundige constructies** | Aspose.Words dekt 99 % van Office Math. Voor het zeldzame randgeval moet je de LaTeX handmatig post‑processen. | -| **Een .tex‑bestand nodig in plaats van .txt** | Verander `outputPath` zodat het eindigt op `.tex` en stel eventueel `txtOptions.Encoding` in op `Encoding.UTF8`. | -| **Uitvoeren op Linux/macOS** | Dezelfde code werkt—zorg er alleen voor dat de bestandspaden schuine strepen gebruiken of `Path.Combine`. | +Hoewel de drie‑stappen‑aanpak voor de meeste gevallen werkt, gooien real‑world projecten vaak onverwachte situaties. Hieronder staan praktische suggesties die je **convert word to plain text**‑pipeline robuust maken. ---- +### Gebruik een consistente codering -## Hoe TXT opslaan met LaTeX‑vergelijkingen – Snelle samenvatting +`TxtSaveOptions` standaard op UTF‑8, wat de meeste tekens aankan. Als je een andere code‑pagina nodig hebt (bijv. legacy‑systemen die Windows‑1252 verwachten), stel je de `Encoding`‑eigenschap in: -1. **Laad** de .docx (`Document`). -2. **Stel** `OfficeMathExportMode = LaTeX` in `TxtSaveOptions`. -3. **Sla** het bestand op (`doc.Save`) met die opties. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -Dat is de volledige workflow om **how to save txt**‑bestanden te maken die LaTeX‑geformatteerde vergelijkingen bevatten. +### Verwijder overtollige witruimte ---- +Tabellen met veel kolommen kunnen lange regels genereren. Na het opslaan wil je misschien het bestand post‑processen om meerdere spaties samen te voegen tot één tab. -## Bonus: De conversie automatiseren voor meerdere bestanden +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -Heb je een map vol Word‑docs, verpak dan de bovenstaande logica in een eenvoudige lus: +### Omgaan met geneste tabellen -```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +Als je DOCX tabellen binnen tabellen bevat, zal `PreserveTableLayout` nog steeds de visuele hiërarchie behouden, maar de inspringing kan er vreemd uitzien. Een snelle oplossing is om leidende spaties te vervangen door een aangepast marker (bijv. `>>`) zodat downstream‑parsers nestingsniveaus kunnen detecteren. -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Batchverwerking van meerdere bestanden + +Wanneer je **convert word to txt** moet uitvoeren voor tientallen documenten, wikkel je de logica in een lus: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Nu kun je **convert word to latex** in bulk—perfect voor onderzoeksgroepen die dagelijks tientallen manuscripten ontvangen. +Zo kun je **save docx as txt** in massa uitvoeren zonder handmatige tussenkomst. + +--- + +## Veelvoorkomende valkuilen en hoe ze te vermijden + +1. **Missing LaTeX Export Mode** – Als je vergeet `OfficeMathExportMode = OfficeMathExportMode.LaTeX` in te stellen, vallen vergelijkingen terug naar platte tekst (bijv. “Equation 1”). Controleer altijd de opties‑blok. +2. **Table Layout Gets Lost** – Het instellen van `PreserveTableLayout` op `false` is de standaard. Als je output eruitziet als een muur van tekst, heb je de vlag waarschijnlijk niet omgezet. +3. **File Paths with Spaces** – Het gebruik van ruwe strings (`@"C:\My Folder\input.docx"`) voorkomt escape‑problemen. Anders krijg je een `FileNotFoundException`. +4. **Version Mismatch** – Oudere Aspose.Words‑versies (< 21.9) ondersteunen `OfficeMathExportMode` niet. Upgrade naar de nieuwste package om ervoor te zorgen dat **how to export latex** werkt. +5. **Encoding Errors for Non‑ASCII Characters** – Als je �‑symbolen ziet, stel dan expliciet `options.Encoding` in op UTF‑8 of de juiste code‑pagina. + +## De oplossing uitbreiden: van TXT naar Markdown of HTML + +Soms heb je meer nodig dan platte tekst—misschien een Markdown‑bestand dat nog steeds LaTeX‑blokken bevat. Dezelfde `TxtSaveOptions` kan worden vervangen door `HtmlSaveOptions` of `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Die kleine wijziging laat je **convert word to txt**‑stijl output krijgen terwijl je de markdown‑syntaxis behoudt die je liefhebt. --- ## Conclusie -We hebben stap‑voor‑stap behandeld **hoe je LaTeX exporteert vanuit Word**, laten zien **hoe je txt‑bestanden opslaat** die elke Office‑Math‑vergelijking behouden, en zelfs laten zien hoe je **convert word equations latex** uitvoert zonder verlies van nauwkeurigheid. +We hebben een volledige, productie‑klare oplossing voor **how to export latex** vanuit een Word‑document doorgenomen, terwijl we je tegelijkertijd laten zien hoe je **convert word to txt**, **convert word to plain text**, **save docx as txt**, en **how to preserve tables** kunt uitvoeren. De belangrijkste punten zijn: + +- Laad de DOCX met `Aspose.Words.Document`. +- Stel `TxtSaveOptions.OfficeMathExportMode = LaTeX` en `PreserveTableLayout = true` in. +- Roep `doc.Save(outputPath, options)` aan om een schoon LaTeX‑rijk platte‑tekst‑bestand te krijgen. -Met slechts een paar regels C# en de krachtige Aspose.Words‑bibliotheek kun je elk .docx omzetten naar LaTeX‑gereed tekst, klaar voor opname in wetenschappelijke papers, leerboeken of geautomatiseerde publicatie‑pipelines. +Probeer het op je eigen bestanden, experimenteer met codering‑aanpassingen, en voel je vrij om volledige mappen in batch te verwerken. Als je tegen randgevallen aanloopt—geneste tabellen, exotische tekens, of oudere Aspose‑versies—raadpleeg dan de secties “Tips” en “Valkuilen” voor snelle oplossingen. -**Volgende stappen?** Probeer het gegenereerde `.txt` (of hernoem het naar `.tex`) te voeren aan `pdflatex` of `xelatex` om een PDF te produceren, of verken de `SaveFormat.LaTeX`‑optie voor een direct `.tex`‑bestand. Als je **save docx as txt** wilt doen terwijl je opmaak behoudt, experimenteer dan met `PreserveTableLayout` en aangepaste regel‑breek‑afhandeling. +Klaar voor de volgende stap? Probeer dezelfde DOCX naar Markdown te converteren, of voer het gegenereerde `.txt` in een static‑site‑generator die LaTeX op het web rendert. De mogelijkheden zijn eindeloos, en nu heb je een solide basis voor elke **convert word to txt**‑workflow. -Vragen over randgevallen, licenties of prestatie‑tweaks? Laat een reactie achter—happy coding! +Veel plezier met coderen, en moge je LaTeX altijd bij de eerste poging compileren! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/dutch/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/dutch/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..7dead6439d --- /dev/null +++ b/words/dutch/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Sla Word op als PDF met Aspose.Words in C#. Leer hoe je docx naar PDF + converteert, ontbrekende lettertypen detecteert en waarschuwingen voor lettertypevervanging + efficiënt afhandelt. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: nl +og_description: Sla Word op als PDF met Aspose.Words. Deze stapsgewijze tutorial laat + zien hoe je docx naar PDF converteert en ontbrekende lettertypen detecteert. +og_title: Word opslaan als PDF met Aspose.Words – Complete gids +tags: +- Aspose.Words +- C# +- PDF conversion +title: Word opslaan als PDF met Aspose.Words – Complete gids +url: /nl/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word opslaan als PDF met Aspose.Words – Complete gids + +Heb je ooit **Word opslaan als PDF** on-the-fly nodig gehad en je afgevraagd of je een lettertype mist onderweg? Je bent niet de enige—ontwikkelaars worstelen voortdurend met missende‑lettertype hoofdpijn bij het converteren van documenten. In deze gids lopen we stap voor stap door een praktische oplossing die niet alleen **docx naar pdf converteren** mogelijk maakt, maar ook **missende lettertypen detecteert** met behulp van de font‑substitutie waarschuwingen van Aspose.Words. + +We behandelen alles, van het instellen van de waarschuwingverzamelaar tot het interpreteren van de output, zodat je aan het einde precies weet hoe je **Word opslaan als PDF** kunt doen zonder verrassingen. Geen externe tools, geen obscure instellingen—alleen nette C#-code die je in elk .NET-project kunt gebruiken. + +## Wat je nodig hebt + +- **Aspose.Words for .NET** (nieuwste versie, bijv. 24.10) – je kunt het ophalen via NuGet (`Install-Package Aspose.Words`). +- Een .NET-ontwikkelomgeving (Visual Studio, Rider, of VS Code werkt prima). +- Een voorbeeld DOCX‑bestand dat mogelijk lettertypen bevat die niet op de doelmachine geïnstalleerd zijn. +Dat is alles. Als je die basis hebt, kunnen we meteen beginnen. + +## Word opslaan als PDF – Stapsgewijze overzicht + +Hieronder staat het volledige, uitvoerbare programma. Voel je vrij om het te kopiëren en plakken in een console‑app‑project en op **F5** te drukken. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** Vervang `YOUR_DIRECTORY` door een absoluut pad of gebruik `Path.Combine(Environment.CurrentDirectory, "input.docx")` voor een relatief, veiliger pad. + +### Waarom we een waarschuwing‑callback gebruiken + +Aspose.Words vervangt stilzwijgend missende lettertypen door een fallback (meestal Arial). Zonder een callback zou je nooit weten dat die substitutie heeft plaatsgevonden, wat kan leiden tot lay‑out glitches in de resulterende PDF. Door `IWarningCallback` aan te haken, krijgen we een duidelijke, programmeerbare lijst van elk missend‑lettertype‑event—perfect voor logging of het informeren van eindgebruikers. + +### Missende lettertypen detecteren – Waar je op moet letten + +Wanneer je het programma uitvoert, zal elk missend lettertype een console‑regel genereren die lijkt op: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Als de lijst leeg is, gefeliciteerd—**Word opslaan als PDF** is geslaagd met alle originele lettertypen behouden. + +## Docx naar PDF converteren – De output aanpassen + +Soms heb je een specifieke PDF‑versie, beeldkwaliteit of conformiteitsniveau nodig. Aspose.Words laat je het `PdfSaveOptions`‑object aanpassen voordat je `Save` aanroept. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Waarom dit belangrijk is:** Als je PDF's genereert voor juridische archieven, zorgt het instellen van `PdfA1b` ervoor dat het bestand aan strenge normen voldoet. Dezelfde conversie respecteert nog steeds onze waarschuwing‑callback, zodat je nog steeds **missende lettertypen detecteert**. + +## Aspose Words Font Substitutie – Randgevallen afhandelen + +### Scenario 1: Meerdere missende lettertypen + +Als je brondocument meerdere aangepaste lettertypen gebruikt, zal de waarschuwingverzamelaar één vermelding per lettertype bevatten. Je kunt ze aggregeren: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenario 2: Een fallback lettertype‑map opgeven + +Aspose.Words kan extra mappen doorzoeken op lettertypen. Stel de `FontsFolder`‑eigenschap in op `FontSettings` voordat je het document laadt: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Nu zal de bibliotheek eerst je aangepaste map proberen, waardoor de kans op ongewenste substitutie afneemt. + +### Scenario 3: Substituties negeren + +Als je liever wilt dat de conversie faalt wanneer een lettertype ontbreekt (in plaats van stilzwijgend te substitueren), gooi dan een uitzondering in de callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Dit dwingt je om het missende lettertype op te lossen voordat je verdergaat—handig in CI‑pipelines waar stille fouten onaanvaardbaar zijn. + +## Volledig end‑to‑end voorbeeld + +Alles samenvoegend, hier is een compacte versie die **laat zien hoe je Word naar PDF converteert**, aangepaste PDF‑opties instelt, en eventuele lettertype‑problemen logt: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Verwachte console‑output** (als Calibri ontbreekt): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Als er geen waarschuwingen verschijnen, heeft je **Word opslaan als PDF**‑operatie exact dezelfde lettertypen gebruikt als de bron‑DOCX. + +## Visuele samenvatting + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Afbeeldings‑alt‑tekst:* **Word opslaan als PDF** workflow die laden, waarschuwingverzameling en PDF‑output toont. + +## Veelgestelde vragen & antwoorden + +| Vraag | Antwoord | +|----------|--------| +| **Heb ik een licentie nodig voor Aspose.Words?** | Een gratis evaluatielicentie werkt voor testen, maar productiegebruik vereist een betaalde licentie om het evaluatiewatermerk te verwijderen. | +| **Werkt dit op .NET Core / .NET 6+?** | Absoluut—Aspose.Words richt zich op .NET Standard 2.0, dus elke recente .NET-runtime is compatibel. | +| **Kan ik meerdere DOCX‑bestanden in een lus converteren?** | Ja, maak gewoon een nieuw `Document` aan voor elk bestand en hergebruik dezelfde `WarningInfoCollector` als je geaggregeerde resultaten wilt. | +| **Wat als de output‑map niet bestaat?** | `Document.Save` zal een `DirectoryNotFoundException` gooien. Maak de map eerst aan of gebruik `Directory.CreateDirectory`. | +| **Is er een manier om de missende lettertypen in de PDF in te sluiten?** | Aspose.Words kan lettertypen automatisch insluiten als ze beschikbaar zijn op de machine; stel `PdfSaveOptions.EmbedFullFonts = true` in. | + +## Conclusie + +Je hebt nu een solide, productie‑klaar patroon om **Word op te slaan als PDF** terwijl je **missende lettertypen detecteert** en **Aspose.Words font‑substitutie** scenario's afhandelt. Door een waarschuwing‑callback toe te voegen, lettertype‑mappen aan te passen en eventueel `PdfSaveOptions` te tweaken, kun je betrouwbaar **docx naar pdf converteren** en je gebruikers informeren over eventuele lettertype‑problemen die de lay‑out nauwkeurigheid kunnen beïnvloeden. + +Klaar voor de volgende stap? Probeer PDF's te genereren van meerdere documenten parallel, of verken het toevoegen van watermerken en digitale handtekeningen—beide zijn eenvoudige uitbreidingen van de code die je net onder de knie hebt. Veel plezier met coderen, en moge je PDF's er altijd precies uitzien zoals bedoeld! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-loadoptions/_index.md b/words/dutch/net/programming-with-loadoptions/_index.md index 9d75633c0c..3f390afbbe 100644 --- a/words/dutch/net/programming-with-loadoptions/_index.md +++ b/words/dutch/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ In deze tutorials leert u hoe u LoadOptions kunt gebruiken om Word-documenten me | [Hoe een DOCX te herstellen – herstelmodus instellen & corrupte Word‑bestanden openen](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Leer hoe u een beschadigd DOCX‑bestand kunt herstellen door de herstelmodus in te stellen en corrupte Word‑bestanden te openen met Aspose.Words voor .NET. | | [Hoe LoadOptions in Aspose.Words te gebruiken – Complete gids](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Leer stap voor stap hoe u LoadOptions gebruikt in Aspose.Words voor .NET met deze volledige gids. | | [Beschadigd document herstellen in C# – Herstelmodus instellen & gebruiker prompten](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Leer hoe u beschadigde documenten kunt herstellen in C# door de herstelmodus in te stellen en de gebruiker een prompt te tonen. | +| [Beschadigd docx herstellen – Volledige gids voor het laden van beschadigde Word-bestanden in C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Leer hoe u beschadigde docx-bestanden kunt laden en herstellen in C# met Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/dutch/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..23d1b98187 --- /dev/null +++ b/words/dutch/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Herstel snel corrupte docx‑bestanden met Aspose.Words. Leer hoe je de + herstelmodus instelt, docx veilig laadt en beschadigde Word‑bestanden in slechts + een paar stappen leest. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: nl +og_description: Herstel corrupte docx‑bestanden in C#. Stel herstelmodus in, laad + docx veilig en lees beschadigde Word‑bestanden met Aspose.Words. +og_title: Herstel corrupte docx – Snelle C#-gids +tags: +- Aspose.Words +- C# +- Document Recovery +title: Herstel beschadigde docx – Volledige gids voor het laden van beschadigde Word‑bestanden + in C# +url: /nl/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Herstel corrupte docx – Snelle C# Gids + +Heb je ooit geprobeerd een Word‑bestand te openen dat gewoonweg niet laadde en je afgevraagd of de inhoud voor altijd verloren was? In veel real‑world projecten zul je **recover corrupted docx** bestanden herstellen zonder de gebruiker te vragen de bijlage opnieuw te verzenden. Het goede nieuws is dat Aspose.Words het een fluitje van een cent maakt: je stelt simpelweg de recovery‑mode in en laat de bibliotheek het zware werk doen. + +In deze tutorial lopen we de exacte stappen door om **recover corrupted docx** bestanden te herstellen, leggen we uit waarom de `RecoveryMode.AutoRecover`‑optie de veiligste keuze is, en laten we je zien hoe je **how to load docx** bestanden kunt laden die mogelijk gedeeltelijk beschadigd zijn. Aan het einde kun je een beschadigd Word‑bestand lezen, de overgebleven tekst extraheren, en zelfs het oorspronkelijke formaat loggen voor toekomstige audits. Geen externe tools, alleen schone C#‑code. + +## Wat je nodig hebt + +- **Aspose.Words for .NET** (any recent version; the API we use works with 23.5 and newer). +- Een .NET‑ontwikkelomgeving (Visual Studio, VS Code, of Rider). +- Het corrupte of gedeeltelijk beschadigde `.docx` dat je wilt redden. + +Geen speciale permissies, geen COM‑interop, en geen noodzaak om Microsoft Office op de server te installeren. Simpel, toch? + +## Stap 1: Stel Recovery‑Mode in op Auto‑Recover + +Wanneer een Word‑bestand beschadigd is, gooit het standaard laadgedrag een uitzondering en stopt. Door een `LoadOptions`‑object te configureren vertel je Aspose.Words om **set recovery mode** in te stellen op `AutoRecover`, wat het zip‑pakket scant, onleesbare delen overslaat, en teruggeeft wat het kan samenstellen. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Waarom AutoRecover?** +> Het probeert zoveel mogelijk te lezen terwijl het documentobject bruikbaar blijft. Als je `RecoveryMode.NoRecovery` kiest, zal het laden falen bij de eerste corruptie, wat het doel van **recover corrupted docx**‑scenario's ondermijnt. + +## Stap 2: Laad het document met de geconfigureerde opties + +Nu de recovery‑mode is ingesteld, kun je veilig proberen het bestand te openen. Vervang `"YOUR_DIRECTORY/input.docx"` door het daadwerkelijke pad naar je beschadigde bestand. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Als het bestand slechts gedeeltelijk corrupt is, wordt de `Document`‑instantie nog steeds aangemaakt. Je kunt later `document.IsStructureValid` controleren als je extra validatie nodig hebt. + +## Stap 3: Controleer het gedetecteerde formaat + +Aspose.Words detecteert automatisch het oorspronkelijke formaat (DOC, DOCX, ODT, enz.). Het afdrukken van deze waarde helpt je bevestigen dat de bibliotheek het bestand correct heeft herkend, wat een snelle sanity‑check is na een **recover corrupted docx**‑operatie. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typische output: + +``` +Loaded with Docx format. +``` + +Zelfs als sommige delen ontbraken, slaagt de formaatdetectie nog steeds—een extra winst voor **recover corrupted docx**‑workflows. + +## Stap 4: Extraheer wat je kunt + +Zodra het document is geladen, kun je het behandelen als elk gezond Word‑bestand. Hieronder staat een compact voorbeeld dat platte tekst extraheert en naar de console schrijft. Dit toont aan dat je **read damaged word file**‑inhoud kunt lezen zonder crashes. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Als het oorspronkelijke bestand tabellen of afbeeldingen bevatte die corrupt waren, worden deze simpelweg weggelaten uit de tekstoutput. De rest van het document blijft intact. + +## Stap 5: Sla een schone kopie op (optioneel) + +Vaak wil je de gebruiker een nieuwe, schone versie van het bestand geven na herstel. Opslaan in hetzelfde formaat zorgt voor compatibiliteit met alle downstream‑processen. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Nu heb je een **recover damaged docx**‑bestand dat je veilig kunt bijvoegen aan een e‑mail of doorgeven aan een andere service. + +## Volledig werkend voorbeeld + +Alles bij elkaar, hier is het complete, kant‑klaar programma. Plak het in een nieuw console‑project, pas de bestandspaden aan, en druk op F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Verwachte output** (ervan uitgaande dat het bestand een enkele alinea “Hello world!” en wat corrupte XML bevat): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Merk op dat het programma nooit crasht—ondanks dat het bronbestand gedeeltelijk kapot was. Dat is de essentie van **recover corrupted docx** met Aspose.Words. + +## Veelgestelde vragen & randgevallen + +### Wat als het bestand volledig onleesbaar is? + +Zelfs `AutoRecover` heeft grenzen. Als de zip‑container zelf zodanig corrupt is dat herstel niet mogelijk is, zal Aspose.Words een `CorruptedFileException` gooien. In dat geval heb je mogelijk een derde‑partij zip‑reparatietool nodig voordat je opnieuw probeert **recover corrupted docx**. + +### Kan ik andere formaten herstellen (bijv. `.doc`, `.odt`)? + +Absoluut. Dezelfde `LoadOptions` werkt voor elk formaat dat Aspose.Words ondersteunt. Verander simpelweg de bestandsextensie en de bibliotheek detecteert automatisch het oorspronkelijke formaat. Dit betekent dat je ook **recover damaged docx**‑achtige bestanden zoals `.doc` of `.rtf` kunt herstellen met identieke code. + +### Hoe ga ik om met grote documenten zonder alles in het geheugen te laden? + +Voor bestanden van gigabyte‑grootte kun je **load options** inschakelen zoals `LoadOptions.LoadFormat` of het document pagina‑voor‑pagina streamen. Het herstelalgoritme moet echter nog steeds het volledige pakket lezen, dus verwacht een hoger geheugenverbruik voor zeer grote corrupte bestanden. + +### Is er een manier om te weten welke delen verloren zijn gegaan? + +Na het laden kun je `document.GetChildNodes(NodeType.Any, true)` inspecteren en het aantal vergelijken met een verwachte basislijn. Ontbrekende tabellen, afbeeldingen of headers zullen simpelweg ontbreken in de node‑collectie. Dit stelt je in staat precies te loggen wat er **recover damaged docx** is en de gebruiker te informeren. + +## Pro‑tips voor betrouwbaar herstel + +- **Validate the input file size** vóór het laden; een bestand van nul bytes zal altijd falen. +- **Log the `RecoveryMode` result** door `DocumentLoadingException` af te vangen en het exceptiebericht op te slaan; het bevat vaak aanwijzingen over welke delen zijn overgeslagen. +- **Run the recovery on a background thread** als je uploads verwerkt in een webservice—dit houdt de aanvraag responsief. +- **Combine with a checksum** (bijv. MD5) om te detecteren of het herstelde bestand verschilt van het origineel; je kunt dan beslissen of je beide versies wilt behouden. + +## Conclusie + +We hebben zojuist laten zien hoe je **recover corrupted docx**‑bestanden in C# kunt herstellen door **setting recovery mode** in te stellen op `AutoRecover`, het document veilig te laden, de overgebleven tekst te extraheren, en optioneel een schone kopie op te slaan. Deze aanpak stelt je in staat **how to load docx**‑bestanden te laden die anders uitzonderingen zouden gooien, en biedt je een betrouwbare manier om **read damaged word file**‑inhoud te lezen zonder externe tools. + +Volgende stappen? Probeer `RecoveryMode.AutoRecover` te vervangen door `RecoveryMode.NoRecovery` om het verschil te zien, of experimenteer met de `LoadOptions`‑eigenschappen die wachtwoordafhandeling en lettertype‑substitutie regelen. Je kunt de herstelroutine ook integreren in een ASP.NET Core API die uploads accepteert en een gerepareerd bestand teruggeeft—perfect voor enterprise document‑management pipelines. + +Heb je meer vragen over Word‑documentherstel, of wil je zien hoe je **recover damaged docx**‑bestanden kunt herstellen met aangepaste callbacks? Laat een reactie achter hieronder, en happy coding! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-markdownsaveoptions/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/_index.md index 968053bfaa..d4c833b706 100644 --- a/words/dutch/net/programming-with-markdownsaveoptions/_index.md +++ b/words/dutch/net/programming-with-markdownsaveoptions/_index.md @@ -41,11 +41,9 @@ Leer hoe u Markdown vanuit Word opslaat met een volledige stap‑voor‑stap C# ### [Docx opslaan als markdown – Complete C#-gids met LaTeX‑vergelijkingen](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) ### [Docx opslaan als markdown – Volledige C#-gids met afbeeldingsextractie](./save-docx-as-markdown-full-c-guide-with-image-extraction/) - Leer hoe u docx-bestanden opslaat als markdown en afbeeldingen extraheert met een volledige C#‑handleiding. ### [Word naar Markdown converteren in C# – Volledige gids met afbeeldingsextractie](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) - Leer hoe u Word-documenten naar Markdown converteert en afbeeldingen extraheert met een volledige C#-handleiding. ### [Hoe Markdown te exporteren vanuit Word – Complete C#-gids](./how-to-export-markdown-from-word-complete-c-guide/) @@ -72,6 +70,10 @@ Leer hoe u afbeeldingen een nieuwe naam geeft tijdens het converteren van DOCX n ### [Opslaan van Word-afbeeldingen – Converteer Word naar Markdown met Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) +### [Docx opslaan als markdown – Exporteer Word‑wiskunde naar LaTeX met Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) + +### [Afbeeldingen uploaden naar de cloud bij het converteren van Word naar Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..eda65357ae --- /dev/null +++ b/words/dutch/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: sla docx op als markdown met Aspose.Words – leer hoe je Word naar markdown + converteert, vergelijkingen exporteert naar LaTeX, en de markdown‑afbeeldingsresolutie + instelt in één soepele workflow. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: nl +og_description: sla docx op als markdown met Aspose.Words. Deze tutorial laat zien + hoe je Word naar markdown converteert, vergelijkingen exporteert naar LaTeX en de + resolutie van markdown‑afbeeldingen instelt. +og_title: docx opslaan als markdown – volledige gids voor het exporteren van Word‑wiskunde + naar LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx opslaan als markdown – Exporteer Word-wiskunde naar LaTeX met Aspose.Words +url: /nl/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx opslaan als markdown – Export Word Math naar LaTeX met Aspose.Words + +Heb je ooit **docx opslaan als markdown** moeten doen, maar zat je vast bij het behouden van die Office‑Math‑vergelijkingen in een scherpe weergave? Je bent niet de enige. De meeste ontwikkelaars lopen tegen een muur aan wanneer de standaardconversie vergelijkingen als wazige afbeeldingen oplevert, waardoor je ze handmatig moet herschrijven in LaTeX. + +Goed nieuws: Aspose.Words kan het zware werk voor je doen. In deze tutorial **converteren we Word naar markdown**, vertellen we de engine om **vergelijkingen te exporteren naar LaTeX**, en stellen we zelfs **de markdown‑afbeeldingsresolutie** in voor de rest van het document. Aan het einde heb je één enkele opdracht die een nette `.md`‑bestand oplevert met LaTeX‑gereed wiskunde en afbeeldingen met hoge resolutie. + +## Wat je gaat leren + +- Hoe je een `.docx` laadt die Office‑Math‑objecten bevat. +- Welke `MarkdownSaveOptions`‑eigenschappen **export equations to latex** en **set markdown image resolution** regelen. +- Een volledige, uitvoerbare C#‑codefragment dat je in elk .NET‑project kunt plakken. +- Tips voor het oplossen van veelvoorkomende valkuilen, zoals ontbrekende lettertypen of niet‑ondersteunde vergelijkingseigenschappen. + +**Prerequisites**: .NET 6+ (of .NET Framework 4.6+), een licentie voor Aspose.Words for .NET, en een basiskennis van C#. Als je comfortabel een console‑app kunt maken, ben je klaar om te starten. + +--- + +## Stap 1 – Docx opslaan als markdown: Laad je Word‑bestand + +Het eerste wat we nodig hebben is een `Document`‑object dat naar de bron‑`.docx` wijst. Beschouw het als het openen van het boek voordat je begint met het kopiëren van hoofdstukken. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Waarom dit belangrijk is*: Als het document geen wiskunde bevat, is de **export equations to latex**‑stap een no‑op, maar de rest van de conversie wordt wel uitgevoerd. Deze controle bespaart je de verwarring waarom je gegenereerde Markdown geen LaTeX‑blokken bevat. + +--- + +## Stap 2 – Configureren van Export Equations to LaTeX + +Aspose.Words laat je bepalen hoe Office Math moet worden gerenderd. Standaard zet het ze om in PNG‑afbeeldingen, waardoor veel tutorials eindigen met een korrelig markdown‑bestand. Door `OfficeMathExportMode` op `LaTeX` te zetten, krijg je nette, copy‑paste‑klare vergelijkingen. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Waarom `OfficeMathExportMode.LaTeX`?* LaTeX is de lingua franca van wetenschappelijke publicaties. Wanneer je later de markdown rendert met een static‑site generator of een Jupyter‑notebook, verschijnen de vergelijkingen scherp op elk zoom‑niveau. + +--- + +## Stap 3 – Instellen van Markdown Image Resolution (voor niet‑wiskundige inhoud) + +Hoewel we ons op wiskunde richten, bevatten de meeste Word‑documenten ook afbeeldingen, diagrammen of ingesloten SVG’s. De eigenschap `ImageResolution` bepaalt hoe Aspose.Words die assets rastert. Een waarde van **300 DPI** is een goed evenwicht voor scherm en afdruk. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: Als je markdown alleen op het web wordt weergegeven, kun je dit verlagen naar 150 DPI om de bestandsgrootte te beperken. Omgekeerd, voor print‑klare PDF’s, verhoog je het naar 600 DPI. + +--- + +## Stap 4 – Voer de conversie uit – Convert Word Math LaTeX + +Nu alles geconfigureerd is, bestaat de daadwerkelijke conversie uit één regel. Aspose.Words doet het zware werk op de achtergrond. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Verwachte output**: Open het gegenereerde `.md`‑bestand en je zou iets moeten zien als: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Let op de LaTeX‑blokken (`$...$` en `$$...$$`) die de eerdere PNG‑fragmenten vervangen. De afbeelding onderaan blijft een PNG, gerenderd op 300 DPI zoals gevraagd. + +--- + +## Stap 5 – Veelvoorkomende randgevallen & hoe ze op te lossen + +| Situatie | Wat gebeurt er | Hoe op te lossen | +|-----------|----------------|------------------| +| **Ontbrekende lettertypen** (bijv. Cambria Math niet geïnstalleerd) | LaTeX‑output kan onbekende symbolen bevatten. | Installeer het ontbrekende lettertype op de server of embed het in het document vóór conversie. | +| **Complexe vergelijkingen** (matrix met aangepaste delimiters) | Aspose.Words kan terugvallen op een afbeelding ondanks `LaTeX`‑modus. | Upgrade naar de nieuwste Aspose.Words‑versie; de bibliotheek verbetert continu de dekking van vergelijkingen. | +| **Grote documenten** ( > 50 MB ) | Geheugendruk kan een `OutOfMemoryException` veroorzaken. | Gebruik `LoadOptions` met `LoadFormat.Docx` en stream het bestand, of splits het document in secties vóór conversie. | +| **Afbeeldingsgrootte te groot** | Markdown‑bestand wordt enorm, waardoor static‑site builds trager worden. | Verlaag `ImageResolution` naar 150 DPI voor alleen‑webscenario’s (zie Stap 3). | + +--- + +## Stap 6 – Alles samenvoegen: Volledig werkend voorbeeld + +Hieronder staat het *complete* console‑app‑programma dat je kunt kopiëren‑plakken in `Program.cs`. Het bevat alle besproken onderdelen, plus een beetje extra foutafhandeling. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Voer het programma uit (`dotnet run`) en je krijgt een markdown‑bestand dat **docx opslaan als markdown** terwijl elke vergelijking wordt bewaard als LaTeX. Geen handmatig kopiëren‑plakken, geen lelijke raster‑afbeeldingen voor wiskunde. + +--- + +## Conclusie + +We hebben het volledige proces doorlopen om **docx opslaan als markdown** te realiseren met Aspose.Words, van het laden van het Word‑bestand tot het configureren van **export equations to latex** en **set markdown image resolution**. Het uiteindelijke fragment is productie‑klaar en je kunt het in elk .NET‑project gebruiken dat **word to markdown** on‑the‑fly moet converteren. + +Wat nu? Probeer het gegenereerde `.md`‑bestand in een static‑site generator zoals Hugo of Jekyll te voeren en zie hoe je vergelijkingen prachtig renderen. Als je **word math latex** naar andere formaten wilt converteren (PDF, HTML), vervang je simpelweg `MarkdownSaveOptions` door `PdfSaveOptions` of `HtmlSaveOptions`—dezelfde `OfficeMathExportMode`‑vlag werkt in al die scenario’s. + +Heb je een eigen twist in je workflow, bijvoorbeeld het ophalen van Word‑bestanden uit Azure Blob storage of het streamen ervan vanuit een API? Hetzelfde patroon is van toepassing; vervang alleen de bestands‑system `Document`‑constructor door een op stream gebaseerde versie. + +Experimenteer gerust, en laat ons in de reacties weten hoe deze aanpak jouw conversie‑problemen heeft opgelost. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..a912f29b91 --- /dev/null +++ b/words/dutch/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: Upload afbeeldingen naar de cloud terwijl je een Word‑document naar markdown + converteert. Leer hoe je afbeeldingen uit een docx kunt extraheren en opslaan in + Azure Blob‑opslag. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: nl +og_description: Upload afbeeldingen naar de cloud terwijl je een Word‑document naar + markdown converteert. Deze gids laat zien hoe je afbeeldingen uit een docx kunt + extraheren en opslaan in Azure Blob storage. +og_title: Upload afbeeldingen naar de cloud bij het converteren van Word naar Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Afbeeldingen uploaden naar de cloud bij het converteren van Word naar Markdown +url: /nl/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Afbeeldingen uploaden naar de cloud bij het converteren van Word naar Markdown + +Heb je ooit **afbeeldingen naar de cloud moeten uploaden** terwijl je een Word‑bestand naar markdown omzet? Je bent niet de enige—ontwikkelaars moeten constant documentconversie en asset‑beheer combineren, en beide in één vloeiende workflow uitvoeren kan voelen als het najagen van een bewegend doelwit. + +Het goede nieuws? Met Aspose.Words kun je elke foto, grafiek of diagram uit een .docx halen, direct naar Azure Blob Storage pushen, en de gegenereerde markdown laten verwijzen naar die cloud‑URL’s in plaats van lokale bestanden. In deze tutorial lopen we het volledige proces door, van het laden van het bron‑document tot het eindresultaat: een schone markdown‑file die naar jouw Azure‑container wijst. + +Aan het einde van deze gids kun je **docx naar markdown converteren**, **afbeeldingen uit docx extraheren**, en **afbeeldingen opslaan in Azure Blob**—allemaal met slechts een paar regels C#. Geen externe tools, geen handmatig kopiëren‑plakken, en zeker geen gebroken afbeeldingslinks. + +## Wat je nodig hebt + +- **.NET 6.0** of hoger (de code werkt ook op .NET Core en .NET Framework) +- **Aspose.Words for .NET** (NuGet‑package `Aspose.Words`) +- Een **Azure Storage‑account** met een container (bijv. `images`) en een gedeelde toegangssleutel – je hebt de connection string nodig om bestanden te uploaden. +- Een basiskennis van C# en async/await (optioneel maar handig). + +Als je deze onderdelen al hebt, prima—laten we direct naar de oplossing gaan. Zo niet, dan wijst de sectie “Prerequisites” onderaan je naar snelle installatie‑stappen. + +## Stap 1: Azure Blob‑helper opzetten (Waarom het belangrijk is) + +Voordat we het Word‑document aanraken, hebben we een kleine helper nodig die een byte‑array naar Azure Blob Storage kan pushen en een openbare URL teruggeeft. Deze abstractie houdt de conversielogica schoon en maakt het later eenvoudig om van opslagprovider te wisselen. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Waarom deze helper?** +1. **Separation of concerns** – de markdown‑conversiecode blijft gefocust op documentverwerking, niet op HTTP‑details. +2. **Reusability** – je kunt `UploadAsync` vanaf overal in je app aanroepen (bijv. voor door gebruikers geüploade afbeeldingen). +3. **Future‑proofing** – overschakelen naar Amazon S3 of Google Cloud Storage vereist alleen een nieuwe implementatie van dezelfde interface. + +> **Pro tip:** Stel het toegangs‑niveau van de container in op `Blob` (publiek) alleen als je het prima vindt dat iedereen de afbeeldingen kan lezen. Voor private scenario’s genereer je SAS‑tokens per upload en embed je die URL’s in plaats daarvan. + +## Stap 2: Een Resource‑Saving Callback definiëren (De kern van Upload‑While‑Convert) + +Aspose.Words laat je elke resource (afbeelding, grafiek, enz.) onderscheppen die normaal naar schijf zou worden geschreven wanneer je een document als markdown opslaat. Door een `ResourceSavingCallback` te leveren, kunnen we elke resource naar Azure Blob uploaden en de lokale bestandsnaam vervangen door de cloud‑URL. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Wat gebeurt er hier?** + +- **Extract** – Aspose.Words geeft ons een stream voor elke afbeelding. +- **Upload** – We geven die stream door aan `AzureBlobUploader`. +- **Replace** – De markdown‑writer ontvangt de openbare URL en schrijft die in de markdown‑afbeeldingssyntaxis (`![](https://…)`). + +Omdat we `args.AlreadyExists = true` instellen, blijven er geen tijdelijke bestanden achter op het bestandssysteem—a clean, stateless operation perfect voor serverless functions. + +## Stap 3: Markdown Save Options configureren (Alles aan elkaar knopen) + +Nu verweven we de callback met de Aspose.Words `MarkdownSaveOptions`. De cruciale vlaggen zijn `ExportImagesAsBase64 = false` (zodat we externe links krijgen) en `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Waarom we Base64 uitschakelen?** +Wanneer `ExportImagesAsBase64` true is, embedt Aspose elke afbeelding direct in de markdown als een data‑URI. Dat ondermijnt het doel van **upload images to cloud** omdat het markdown‑bestand enorm groeit en de afbeeldingen verborgen blijven voor de CDN. Door het uit te schakelen krijgen we schone, externe links die naar Azure Blob wijzen—precies wat een moderne static‑site generator verwacht. + +## Stap 4: Alles samenvoegen – Een minimale console‑app + +Hieronder vind je een compleet, kant‑klaar console‑programma. Vervang de placeholders door je eigen Azure‑connection string en containernaam. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma met `sample.docx` dat twee afbeeldingen bevat, levert: + +- `output.md` met markdown‑afbeeldingssyntaxis zoals: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-pdfsaveoptions/_index.md b/words/dutch/net/programming-with-pdfsaveoptions/_index.md index f0e3c4be15..96010d5a5e 100644 --- a/words/dutch/net/programming-with-pdfsaveoptions/_index.md +++ b/words/dutch/net/programming-with-pdfsaveoptions/_index.md @@ -46,10 +46,10 @@ Of u nu Word-documenten naar PDF wilt converteren voor online distributie, archi | [3D DML 3D-effecten renderen in een PDF-document](./dml-3deffects-rendering/) | Leer hoe u verbluffende 3D DML-effecten kunt maken in PDF-documenten met Aspose.Words voor .NET met deze uitgebreide stapsgewijze handleiding. | | [Afbeeldingen in een PDF-document interpoleren](./interpolate-images/) | Leer hoe u afbeeldingen in een PDF-document kunt interpoleren met Aspose.Words voor .NET met onze stapsgewijze handleiding. Verbeter eenvoudig de beeldkwaliteit van uw PDF. | | [Docx opslaan als pdf met Aspose.Words – Complete C#-gids](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Leer hoe u een DOCX-bestand naar PDF converteert met Aspose.Words in C# met deze volledige stap‑voor‑stap gids. | +| [Document opslaan als PDF met Aspose.Words – Complete C#-gids](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Leer hoe u een document naar PDF converteert met Aspose.Words in C# met deze volledige stap‑voor‑stap gids. | | [Maak toegankelijke PDF vanuit Word met C# – Stapsgewijze handleiding](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Leer hoe u met Aspose.Words voor .NET een toegankelijke PDF maakt vanuit een Word-document met C# in een stapsgewijze handleiding. | | [Toegankelijke PDF maken in C# – PDF-toegankelijkheidstutorial](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Leer hoe u met Aspose.Words voor .NET een PDF maakt die voldoet aan toegankelijkheidsnormen, inclusief tags, alternatieve tekst en navigatie. | | [Maak een toegankelijke PDF vanuit Word – Complete gids](./create-accessible-pdf-from-word-complete-guide/) | Leer hoe u met Aspose.Words voor .NET een toegankelijke PDF maakt vanuit een Word-document, inclusief tags en toegankelijkheidsopties. | - | [Maak toegankelijke PDF – Stapsgewijze handleiding voor PDF/UA-naleving](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Leer hoe u met Aspose.Words voor .NET een PDF maakt die voldoet aan PDF/UA-standaarden voor toegankelijkheid. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/dutch/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..8839e6f50b --- /dev/null +++ b/words/dutch/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Leer hoe je een document als PDF opslaat met Aspose.Words in C#. De tutorial + behandelt ook het converteren van Word naar PDF, het exporteren van wiskundige LaTeX + en het omgaan met ontbrekende lettertypen. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: nl +og_description: Sla een document moeiteloos op als pdf met Aspose.Words. Deze gids + laat ook zien hoe je Word naar pdf converteert, wiskundige LaTeX exporteert en ontbrekende + lettertypen afhandelt. +og_title: Document opslaan als PDF met Aspose.Words – Complete C#-gids +tags: +- Aspose.Words +- C# +- PDF generation +title: Document opslaan als PDF met Aspose.Words – Complete C#-gids +url: /nl/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Document opslaan als PDF met Aspose.Words – Complete C# Gids + +Heb je je ooit afgevraagd **hoe je een document als pdf kunt opslaan** direct vanuit een Word‑bestand zonder toegankelijkheidsfuncties te verliezen? Je bent niet de enige—ontwikkelaars vragen voortdurend om een betrouwbare manier om Word naar PDF te converteren terwijl wiskundige vergelijkingen behouden blijven en ontbrekende lettertypen op een nette manier worden afgehandeld. + +In deze tutorial lopen we stap voor stap door een oplossing die niet alleen **document opslaan als pdf** laat zien, maar ook **word naar pdf converteren**, **math latex exporteren**, en **ontbrekende lettertypen afhandelen** demonstreert met de nieuwste Aspose.Words voor .NET. Aan het einde heb je een kant‑klaar C#‑programma dat PDF/UA‑2‑conforme bestanden produceert, perfect voor toegankelijkheidscontroles. + +## Wat je nodig hebt + +- .NET 6 of later (de code werkt ook met .NET Core en .NET Framework) +- Aspose.Words voor .NET 25.10 of nieuwer – je kunt een gratis proefversie downloaden van de Aspose‑website +- Een bescheiden Word‑document (`input.docx`) dat minstens één zwevende vorm en een wiskundige vergelijking bevat (om de export‑math‑latex‑functie in actie te zien) +- Visual Studio 2022 (of elke IDE die je wilt) + +> **Pro tip:** Als je op een CI/CD‑pipeline werkt, voeg dan het Aspose.Words‑NuGet‑pakket toe aan je projectbestand: + +```xml + +``` + +Laten we nu in de code duiken. + +## Stap 1: Laad het bron‑document met automatische herstel + +Bij het werken met Word‑bestanden uit de praktijk kun je corrupte secties of ontbrekende bronnen tegenkomen. Het inschakelen van automatische herstel zorgt ervoor dat het laadproces nooit een uitzondering gooit. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Waarom dit belangrijk is:** +`RecoveryMode.AutoRecover` beschermt je pipeline tegen crashes bij misvormde invoer, wat vooral handig is wanneer je **word naar pdf converteert** in bulk. + +## Stap 2: Stel PDF‑opslaan‑opties in voor volledige toegankelijkheid + +PDF/UA‑2 is de ISO‑norm voor toegankelijke PDF’s. Door een paar vlaggen te configureren krijgen we een bestand dat schermlezers kunnen navigeren, en zorgen we er ook voor dat wiskundige vergelijkingen worden geëxporteerd als verborgen LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – zorgt ervoor dat de resulterende PDF de oorspronkelijke lay-out respecteert en toch semantisch correct blijft. +- **OfficeMathExportMode.LaTeX** – voldoet aan de **export math latex**‑vereiste, waardoor downstream‑tools de vergelijkingen kunnen extraheren indien nodig. + +## Stap 3: Waarschuwingen vastleggen (bijv. ontbrekende lettertypen) + +Ontbrekende lettertypen zijn een veelvoorkomend probleem bij het converteren van documenten. Aspose.Words kan deze problemen melden via een `WarningCallback`. We zullen ze verzamelen zodat je ze later kunt loggen of erop kunt reageren. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Waarom dit relevant is:** +Als de bron een lettertype gebruikt dat niet op de server is geïnstalleerd, zal de PDF terugvallen op een standaardlettertype, wat de lay-out kan breken. Door **ontbrekende lettertypen af te handelen** kunnen we de gebruiker waarschuwen of een vervanging insluiten. + +## Stap 4: Sla het document op als een toegankelijke PDF + +Nu het moment van de waarheid—de daadwerkelijke conversie uitvoeren. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Als alles soepel verloopt, krijg je een PDF/UA‑2‑bestand dat verborgen LaTeX bevat voor elke vergelijking en correcte tagging voor zwevende vormen. + +## Stap 5: Bekijk de vastgelegde waarschuwingen (optioneel maar aanbevolen) + +Na de opslaan‑operatie kun je over de verzamelde waarschuwingen itereren en ze loggen. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typische output kan er als volgt uitzien: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Het vroeg zien van deze berichten helpt je **ontbrekende lettertypen af te handelen** voordat ze eindgebruikers beïnvloeden. + +## Volledig werkend voorbeeld + +Alles samenvoegend, hier is het volledige, kant‑klaar programma. Vervang de tijdelijke paden door die van jou. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` voldoet aan PDF/UA‑2. +- Alle zwevende vormen worden getagd als inline‑figuren. +- Elk Office‑Math‑object verschijnt als verborgen LaTeX (zichtbaar wanneer je de structuur van de PDF inspecteert). +- Eventuele lettertype‑gerelateerde problemen worden naar de console geprint, waardoor je de kans krijgt om **ontbrekende lettertypen af te handelen** voordat je het bestand publiceert. + +![Diagram dat de stroom toont van Word → Aspose.Words → Toegankelijke PDF (document opslaan als pdf)](conversion-diagram.png "Stroomdiagram voor het opslaan van een document als pdf") + +*Afbeeldings‑alt‑tekst:* **Diagram van hoe je een document opslaat als pdf met Aspose.Words** + +## Veelgestelde vragen & randgevallen + +### Wat als ik een oudere Aspose.Words‑versie gebruik? + +De `OfficeMathExportMode.LaTeX`‑vlag werd geïntroduceerd in 25.10. Voor oudere releases kun je nog steeds **word naar pdf converteren**, maar de wiskunde wordt gerasterd in plaats van geëxporteerd als LaTeX. Upgrade voor optimale toegankelijkheid. + +### Kan ik aangepaste lettertypen insluiten om terugval te voorkomen? + +Ja. Stel `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` in vóór het aanroepen van `Save`. Dit helpt ook bij het **afhandelen van ontbrekende lettertypen** door de PDF te dwingen de benodigde glyphs te bevatten. + +### Hoe verifieer ik de PDF/UA‑2‑conformiteit? + +Open het bestand in Adobe Acrobat Pro → “Print Production” → “Preflight”. Kies het “PDF/A‑2b” of “PDF/UA‑2”‑profiel; Acrobat geeft eventuele overtredingen weer. + +### Hoe zit het met met wachtwoord‑beveiligde Word‑bestanden? + +Load the document with a `LoadOptions` that includes `Password`. Example: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +De rest van de pipeline blijft ongewijzigd. + +## Conclusie + +We hebben alles behandeld wat je nodig hebt om **document op te slaan als pdf** met Aspose.Words in C#. De tutorial toonde ook hoe je **word naar pdf kunt converteren**, **math latex kunt exporteren**, en **ontbrekende lettertypen kunt afhandelen**—alles terwijl je een toegankelijke PDF/UA‑2‑file produceert. + +Probeer de code uit, experimenteer met verschillende `PdfSaveOptions` (bijv. beeldcompressie, PDF/A‑2b), en integreer het in je document‑verwerkingsservice. Als je verder wilt gaan, overweeg dan om Aspose’s PDF‑specifieke bibliotheek te verkennen voor post‑processing of digitale handtekeningen. + +Heb je meer scenario's die je wilt aanpakken? Laat gerust een reactie achter of bekijk onze andere handleidingen over **PDF-manipulatie**, **beeld‑extractie**, en **batch‑conversie**. Veel plezier met coderen! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-shapes/_index.md b/words/dutch/net/programming-with-shapes/_index.md index 416ee07917..792b6b53e7 100644 --- a/words/dutch/net/programming-with-shapes/_index.md +++ b/words/dutch/net/programming-with-shapes/_index.md @@ -38,6 +38,7 @@ Door Aspose.Words voor .NET te gebruiken en deze tutorials te volgen, krijgt u d | [Smart Art-tekening bijwerken](./update-smart-art-drawing/) | Leer hoe u Smart Art-tekeningen in Word-documenten kunt bijwerken met Aspose.Words voor .NET met deze stapsgewijze handleiding. Zorg ervoor dat uw afbeeldingen altijd accuraat zijn. | | [Aspose.Words Vormschaduw Tutorial – Voeg een schaduw toe aan een Word-vorm in C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Leer hoe u een schaduw toevoegt aan vormen in Word-documenten met Aspose.Words voor .NET met deze stapsgewijze handleiding. | | [Leeg Word‑document maken met een schaduwrechthoek – Stapsgewijze handleiding](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Leer hoe u een leeg Word‑document maakt en een rechthoek met schaduw toevoegt met Aspose.Words voor .NET. | +| [Hoe schaduw te verplaatsen in Aspose.Words – Complete C#-gids](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Leer hoe u de schaduw van vormen in Word-documenten verplaatst met Aspose.Words en C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/dutch/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..30019de497 --- /dev/null +++ b/words/dutch/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Hoe schaduw op een vorm verplaatsen in Aspose.Words met C#. Leer hoe + je schaduw aan een vorm toevoegt, de vervaging aanpast, transparantie instelt en + de schaduw roteert in enkele minuten. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: nl +og_description: Hoe je een schaduw op een vorm verplaatst in Aspose.Words met C#. + Deze tutorial laat zien hoe je een schaduw aan een vorm toevoegt, de vervaging aanpast, + transparantie instelt en de schaduw roteert. +og_title: Hoe schaduw te verplaatsen in Aspose.Words – Complete C#-gids +tags: +- Aspose.Words +- C# +- Document Automation +title: Hoe de schaduw te verplaatsen in Aspose.Words – Complete C#-gids +url: /nl/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe Schaduw Verplaatsen in Aspose.Words – Complete C# Gids + +Heb je je ooit afgevraagd **hoe je schaduw verplaatst** op een vorm in een Word‑document zonder Word handmatig te openen? In mijn dagelijkse werk heb ik vaak een vorm‑schaduw programmatisch moeten aanpassen—of het nu gaat om een gepolijste rapportage of een dynamisch sjabloon. Het goede nieuws? Met Aspose.Words kun je dit in een handvol regels doen, en je leert ook **schaduw toevoegen aan vorm**, **hoe je vervaging wijzigt**, **hoe je transparantie instelt**, en **hoe je schaduw roteert** in één keer. + +In deze tutorial lopen we een real‑world scenario door: een bestaand DOCX‑bestand laden dat al een vorm bevat, de positie, zachtheid, opacity en richting van de schaduw aanpassen, en tenslotte het resultaat opslaan. Aan het einde heb je een herbruikbare snippet die je in elk .NET‑project kunt plakken, en begrijp je waarom elke eigenschap belangrijk is. + +## Voorvereisten – Wat je nodig hebt voordat je begint + +- **Aspose.Words for .NET** (versie 23.12 of later). Je kunt het via NuGet ophalen met `Install-Package Aspose.Words`. +- Een .NET 6+ ontwikkelomgeving (Visual Studio, VS Code, Rider—wat je maar prefereert). +- Een invoer‑Word‑bestand (`input.docx`) dat al minstens één vorm bevat (een rechthoek, cirkel of afbeelding volstaat). +- Basiskennis van C#‑syntaxis—niets ingewikkelds. + +Als je een van deze mist, pauzeer even en installeer de bibliotheek; de rest van de gids gaat ervan uit dat het pakket al is gerefereerd. + +## Stap 1: Het Document Laden en de Doelform Vinden – **Hoe je Schaduw Verplaatst** Begint Hier + +Het eerste wat we doen is het bron‑document laden en de vorm zoeken die we willen aanpassen. Aspose.Words behandelt elk object (alinea’s, tabellen, vormen) als een knoop in een boom, zodat we er direct op kunnen queryen. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Waarom dit belangrijk is:** Het document één keer laden en dezelfde `Document`‑instantie hergebruiken is efficiënt. De `GetChild`‑aanroep is veilig omdat hij `null` retourneert als de index buiten bereik ligt, waardoor we ontbrekende vormen netjes kunnen afhandelen. + +## Stap 2: De Vervagingsstraal Aanpassen – Master **Hoe je Vervaging Wijzigt** + +Een zachte schaduw oogt professioneel, terwijl een harde rand goedkoop kan lijken. De eigenschap `BlurRadius` regelt de zachtheid in punten (1 pt ≈ 1/72 inch). Laten we deze verhogen naar 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** De standaardvervaging is 0,5 pt. Alles boven 5 pt valt meestal op, maar pas op dat je het niet te groot maakt—dan kan de vorm loskomen van de pagina. + +## Stap 3: Transparantie Instellen – Het Antwoord op **Hoe je Transparantie Instelt** + +Transparantie bepaalt hoe doorschijnend de schaduw is. Een waarde van `0` betekent volledig ondoorzichtig; `1` betekent volledig onzichtbaar. Voor een subtiel effect gebruiken we `0.3` (30 % transparant). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Waarom je dit zou kunnen willen:** Als de vorm donker is, kan een volledig ondoorzichtige schaduw de onderliggende tekst verdrinken. Transparantie aanpassen houdt het document leesbaar terwijl je toch diepte toevoegt. + +## Stap 4: De Schaduw Verplaatsen – De Kern van **Hoe je Schaduw Verplaatst** + +De eigenschap `Distance` bepaalt hoe ver de schaduw van de vorm wordt verschoven, gemeten in punten. Een grotere afstand duwt de schaduw verder weg, wat een dramatischer effect geeft. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Wat als je een heel kleine offset nodig hebt?** Een `Distance` van `0` plaatst de schaduw direct achter de vorm, wat handig kan zijn voor reliëf‑effecten. + +## Stap 5: De Lichtbron Roteren – Oplossen **Hoe je Schaduw Roteert** + +Schaduwen vallen niet alleen recht naar beneden; ze volgen de hoek van de lichtbron. De eigenschap `Angle` (in graden) roteert de schaduw rond de vorm. Laten we hem 45° kantelen. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Snelle proef:** Probeer `90` voor een rechts‑vallende schaduw of `-30` voor een links‑hellende. De visuele verandering is direct merkbaar. + +## Stap 6: Het Document Opslaan – Het Resultaat Zien van **Schaduw Toevoegen aan Vorm** + +Nu we de schaduw hebben aangepast, schrijven we het document terug naar de schijf. Je kunt het origineel overschrijven of een nieuw bestand maken; het voorbeeld gebruikt een nieuw uitvoerbestand. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Verwacht resultaat:** Open `output.docx`. De schaduw van de vorm zal zachter, iets verschoven, halfdoorzichtig en onder een hoek van 45° verschijnen. Als je het naast `input.docx` zet, is het verschil onmiskenbaar. + +### Volledig Werkend Voorbeeld (Klaar om te Kopiëren‑Plakken) + +Hieronder staat het volledige programma in één blok. Plak het in een nieuw console‑project, vervang `YOUR_DIRECTORY` door een echte map‑pad, en voer uit. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Veelgestelde Vragen & Randgevallen + +### Wat als het document meerdere vormen bevat? + +Je kunt door alle vormen itereren: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Kan ik een schaduw toevoegen aan een vorm die er nog geen heeft? + +Absoluut. Het `ShadowFormat`‑object is altijd aanwezig; je hoeft het alleen maar in te schakelen: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Werkt dit met afbeeldingen en SmartArt? + +Ja. Elke knoop die afgeleid is van `Shape`—inclusief afbeeldingen, grafieken en SmartArt—heeft een `ShadowFormat`. Dezelfde eigenschappen zijn van toepassing. + +### Hoe regel ik de kleur van de schaduw? + +Gebruik de eigenschap `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Compatibiliteitszorgen? + +Aspose.Words 23.12+ ondersteunt .NET 6, .NET Core 3.1 en .NET Framework 4.6.2+. De getoonde API is stabiel over deze versies heen. + +## Conclusie + +We hebben zojuist **hoe je schaduw verplaatst** op een vorm met Aspose.Words behandeld, en onderweg ook **schaduw toevoegen aan vorm**, **hoe je vervaging wijzigt**, **hoe je transparantie instelt**, en **hoe je schaduw roteert** gedemonstreerd. Het complete, uitvoerbare voorbeeld laat je elke vorm‑schaduw in enkele seconden aanpassen, waardoor je documenten een gepolijste, professionele uitstraling krijgen zonder ooit Word te openen. + +Klaar voor de volgende stap? Probeer deze schaduw‑aanpassingen te combineren met **conditionele opmaak**—bijvoorbeeld alleen een diepere schaduw toepassen op koppen of op grafieken die een bepaalde grootte overschrijden. Of verken **gradient fills** voor de vorm zelf om een echt opvallend ontwerp te creëren. + +Als je ergens vastloopt, laat dan een reactie achter. Veel programmeerplezier, en moge je schaduwen altijd precies vallen waar jij ze wilt! + +![Diagram dat het effect van het verplaatsen van een schaduw op een vorm toont – voorbeeld hoe je schaduw verplaatst](https://example.com/images/shadow-demo.png "voorbeeld hoe je schaduw verplaatst") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/basic-conversions/_index.md b/words/english/net/basic-conversions/_index.md index 6ebbd57498..7aff85557f 100644 --- a/words/english/net/basic-conversions/_index.md +++ b/words/english/net/basic-conversions/_index.md @@ -37,6 +37,7 @@ Basic Conversions walks you through basic document conversions using the Aspose. | [convert word to pdf in C# using Aspose.Words – Guide](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Learn how to convert Word documents to PDF in C# using Aspose.Words. Step‑by‑step guide with code examples for developers. | | [Save Word as PDF with Aspose.Words – Complete C# Guide](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Learn how to save Word documents as PDF using Aspose.Words in C#. Detailed step‑by‑step guide with code examples. | | [save docx as pdf with Aspose.Words – Complete C# Guide](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Learn how to save DOCX as PDF using Aspose.Words in C#. Detailed step‑by‑step guide with code examples. | +| [Save Word as PDF with Aspose.Words – Complete Guide](./save-word-as-pdf-with-aspose-words-complete-guide/) | Learn how to save Word documents as PDF using Aspose.Words. Detailed step‑by‑step guide with code examples for developers. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/english/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/english/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 3060f5364d..ce63b3fffb 100644 --- a/words/english/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/english/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,22 @@ --- category: general -date: 2025-12-29 -description: How to export LaTeX from Word using Aspose.Words – learn to convert Word - to LaTeX, save docx as txt, and handle equations in plain‑text. +date: 2026-05-01 +description: Learn how to export LaTeX from a Word file, convert Word to txt, and + preserve tables using Aspose.Words in C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: en -og_description: How to export LaTeX from Word with Aspose.Words. This guide shows - you how to convert Word to LaTeX, save docx as txt, and keep equations intact. -og_title: How to Export LaTeX from Word – Quick C# Tutorial +og_description: Discover how to export LaTeX from Word, convert Word to plain text, + and keep table layout intact with Aspose.Words. +og_title: How to Export LaTeX from Word – Complete C# Tutorial tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: How to Export LaTeX from Word – Step‑by‑Step Guide url: /net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,178 +26,219 @@ url: /net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# How to Export LaTeX from Word – Step‑by‑Step Guide +# How to Export LaTeX from Word – Complete C# Tutorial -Ever wondered **how to export LaTeX from Word** without losing any of those tricky Office Math equations? You're not the only one. Many developers hit a wall when they try to *convert Word to LaTeX* for academic papers, scientific reports, or automated publishing pipelines. +Ever wondered **how to export LaTeX** from a Word document without losing any of the math equations? You're not alone. Many developers need to turn a .docx that contains Office Math into clean LaTeX while also **convert Word to txt** for downstream processing. In this guide we’ll walk through a practical, ready‑to‑run solution that **preserves tables**, gives you a plain‑text file, and keeps the LaTeX markup exactly where you need it. -In this tutorial we’ll walk through a complete, ready‑to‑run C# example that shows **how to export LaTeX** using Aspose.Words, explains **how to save txt** files with LaTeX markup, and even covers the nuances of **convert word equations latex** so nothing gets lost in translation. +We’ll cover everything from loading the source file to tweaking `TxtSaveOptions` so the output is both human‑readable and machine‑friendly. By the end you’ll be able to **save docx as txt**, **convert Word to plain text**, and know **how to preserve tables** during the export. No external scripts, no manual copy‑pasting—just pure C# code that you can drop into any .NET project. -> **Pro tip:** The same approach works for any .docx you have—just point the code at a different file path. +## What You’ll Need + +- **Aspose.Words for .NET** (latest version, 2024.x or newer). The NuGet package is `Aspose.Words`. +- A .NET development environment (Visual Studio, VS Code, Rider—any will do). +- A Word file (`.docx`) that contains Office Math equations and at least one table (so we can see the table‑preserving magic). + +That’s it. If you already have those, keep reading; otherwise grab the NuGet package and a sample DOCX before we dive deeper. --- -## What You’ll Need +## How to Export LaTeX from a Word Document -Before we dive in, make sure you have the following prerequisites: +Below is the heart of the tutorial—three concise steps that answer the question **how to export latex** while also handling the secondary goals of **convert word to txt**, **convert word to plain text**, **save docx as txt**, and **how to preserve tables**. -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words targets modern .NET runtimes. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | The library does the heavy lifting of parsing Word and emitting LaTeX. | -| **A sample .docx** containing at least one Office Math equation | To see the LaTeX conversion in action. | -| **Visual Studio 2022** (or any IDE you like) | Makes debugging and running the sample trivial. | +### Step 1: Load the DOCX File -If you haven’t installed the NuGet package yet, run: +First we need to read the Word document into an `Aspose.Words.Document` object. This step is the same whether you later **convert word to txt** or **save docx as txt**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -That’s it—no extra DLLs, no COM interop, just a clean managed library. +> **Why this matters:** Loading the file creates an in‑memory representation of all Word elements—paragraphs, tables, and Office Math objects. Without this object you can’t manipulate export options. ---- +### Step 2: Configure `TxtSaveOptions` for LaTeX and Table Layout -## How to Export LaTeX from Word – Overview +The `TxtSaveOptions` class lets you control exactly how the plain‑text file is generated. Two properties are key for our scenario: -Below is the big picture of what we’ll accomplish: +| Property | What it does | Why you need it | +|----------|--------------|-----------------| +| `OfficeMathExportMode` | Determines how Office Math is rendered. Setting it to `LaTeX` converts equations to LaTeX syntax. | This is the core of **how to export latex**. | +| `PreserveTableLayout` | When `true`, Aspose adds whitespace so tables keep a grid‑like appearance. | This satisfies **how to preserve tables** while you **convert word to txt**. | -1. **Load** the source Word document (`.docx`). -2. **Configure** `TxtSaveOptions` so that any Office Math objects are emitted as LaTeX code. -3. **Save** the document as a plain‑text (`.txt`) file that you can feed directly into any LaTeX compiler. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro tip:** If you only need the raw LaTeX without any table formatting, set `PreserveTableLayout` to `false`. The file becomes smaller, but you lose the visual table cue. -## Step 1: Load the Word Document +### Step 3: Save the Document as Plain Text -First things first—open the .docx you want to convert. The `Document` class abstracts away all the underlying XML, giving you a friendly object model. +Now we write the document to a `.txt` file using the options we just defined. This single line accomplishes **convert word to plain text**, **save docx as txt**, and, of course, **how to export latex** all at once. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Why this matters:** -Loading the file early lets us inspect its contents (e.g., count equations) before we decide how to serialize it. If the file is corrupted, `Document` will throw a clear exception, saving you from mysterious output later. +After the call finishes, open `output.txt`. You’ll see: ---- +- LaTeX snippets like `\frac{a}{b}` for every Office Math equation. +- Tables rendered with `|` and `-` characters, preserving column alignment. +- Regular paragraphs as plain text, ready for any downstream parser. -## Step 2: Configure TxtSaveOptions for LaTeX Export +### Full Working Example -The magic happens in `TxtSaveOptions`. By setting `OfficeMathExportMode` to `LaTeX`, every Office Math object is transformed into its corresponding LaTeX representation. +Putting it all together, here’s a self‑contained program you can compile and run today: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Why we choose these settings:** +**Expected output** (excerpt): -- `OfficeMathExportMode.LaTeX` is the only mode that guarantees a faithful mathematical translation. -- `PreserveTableLayout` keeps tables looking like they do in Word, which is handy when you later embed the output in a LaTeX `tabular` environment. -- UTF‑8 ensures characters like “α”, “β”, or “∑” survive the round‑trip. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -If you ever need to **convert word to latex** without the plain‑text wrapper, you could switch to `SaveFormat.LaTeX` instead—just a quick tip for advanced scenarios. +Notice how the table keeps its grid and the equation appears as clean LaTeX. That’s the sweet spot when you **convert word to txt** and still need a faithful representation of both structure and math. --- -## Step 3: Save the Document as a Text File +## Tips for Converting Word to TXT and Preserving Tables -Now we write the LaTeX‑rich text to disk. The resulting `.txt` can be renamed to `.tex` later, or piped directly into a LaTeX compiler. +While the three‑step approach works for most cases, real‑world projects often throw curveballs. Below are practical suggestions that make your **convert word to plain text** pipeline robust. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Use a Consistent Encoding -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` defaults to UTF‑8, which handles most characters. If you need a different code page (e.g., legacy systems expecting Windows‑1252), set the `Encoding` property: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**What you’ll see in `output.txt`:** +### Trim Excess Whitespace + +Tables with many columns can generate long lines. After saving, you might want to post‑process the file to collapse multiple spaces into a single tab: +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -\begin{equation} -E = mc^{2} -\end{equation} + +### Handle Nested Tables + +If your DOCX contains tables inside tables, `PreserveTableLayout` will still keep the visual hierarchy, but the indentation may look odd. A quick fix is to replace leading spaces with a custom marker (e.g., `>>`) so downstream parsers can detect nesting levels. + +### Batch Processing Multiple Files + +When you need to **convert word to txt** for dozens of documents, wrap the logic in a loop: + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} ``` -All other paragraphs appear as plain text, while any Office Math equation is wrapped in a LaTeX `equation` environment (or `inline` if it was inline in Word). This satisfies the **convert word equations latex** requirement perfectly. +That way you can **save docx as txt** en masse without manual intervention. --- -## Edge Cases & Common Questions +## Common Pitfalls and How to Avoid Them -| Situation | What to do | -|-----------|------------| -| **No equations in the source** | The conversion still works; you’ll just get plain text. No extra LaTeX code is added. | -| **Very large documents (>100 MB)** | Consider streaming the output using `MemoryStream` to avoid high memory usage. | -| **Unsupported Math constructs** | Aspose.Words covers 99 % of Office Math. For the rare edge case, you may need to post‑process the LaTeX manually. | -| **Need a .tex file instead of .txt** | Change `outputPath` to end with `.tex` and optionally set `txtOptions.Encoding` to `Encoding.UTF8`. | -| **Running on Linux/macOS** | The same code works—just ensure the file paths use forward slashes or `Path.Combine`. | +1. **Missing LaTeX Export Mode** – If you forget to set `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, equations will fall back to plain text (e.g., “Equation 1”). Always double‑check the options block. ---- +2. **Table Layout Gets Lost** – Setting `PreserveTableLayout` to `false` is the default. If your output looks like a wall of text, you probably didn’t toggle the flag. -## How to Save TXT with LaTeX Equations – Quick Recap +3. **File Paths with Spaces** – Using raw strings (`@"C:\My Folder\input.docx"`) avoids escaping issues. Otherwise you’ll get a `FileNotFoundException`. -1. **Load** the .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` in `TxtSaveOptions`. -3. **Save** the file (`doc.Save`) with those options. +4. **Version Mismatch** – Older Aspose.Words versions (< 21.9) don’t support `OfficeMathExportMode`. Upgrade to the latest package to ensure **how to export latex** works. -That’s the entire workflow to **how to save txt** files that contain LaTeX‑formatted equations. +5. **Encoding Errors for Non‑ASCII Characters** – If you see � symbols, explicitly set `options.Encoding` to UTF‑8 or the appropriate code page. --- -## Bonus: Automating the Conversion for Multiple Files +## Extending the Solution: From TXT to Markdown or HTML -If you have a folder full of Word docs, wrap the above logic in a simple loop: +Sometimes you need more than plain text—maybe a Markdown file that still contains LaTeX blocks. The same `TxtSaveOptions` can be swapped for `HtmlSaveOptions` or `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Now you can **convert word to latex** in bulk—perfect for research groups that receive dozens of manuscripts daily. +That tiny change lets you **convert word to txt**‑style output while keeping the markdown syntax you love. --- ## Conclusion -We’ve covered **how to export LaTeX from Word** step‑by‑step, demonstrated **how to save txt** files that preserve every Office Math equation, and even showed you how to **convert word equations latex** without losing fidelity. +We’ve walked through a complete, production‑ready answer to **how to export latex** from a Word document, while simultaneously showing you how to **convert word to txt**, **convert word to plain text**, **save docx as txt**, and **how to preserve tables**. The key takeaways are: + +- Load the DOCX with `Aspose.Words.Document`. +- Set `TxtSaveOptions.OfficeMathExportMode = LaTeX` and `PreserveTableLayout = true`. +- Call `doc.Save(outputPath, options)` to get a clean LaTeX‑rich plain‑text file. -With just a few lines of C# and the powerful Aspose.Words library, you can turn any .docx into LaTeX‑ready text, ready for inclusion in scientific papers, textbooks, or automated publishing pipelines. +Give it a try on your own files, experiment with encoding tweaks, and feel free to batch‑process entire folders. If you run into edge cases—nested tables, exotic characters, or older Aspose versions—refer back to the “Tips” and “Pitfalls” sections for quick fixes. -**Next steps?** Try feeding the generated `.txt` (or rename it to `.tex`) into `pdflatex` or `xelatex` to produce a PDF, or explore the `SaveFormat.LaTeX` option for a direct `.tex` file. If you need to **save docx as txt** while preserving formatting, experiment with `PreserveTableLayout` and custom line‑break handling. +Ready for the next step? Try converting the same DOCX to Markdown, or feed the generated `.txt` into a static‑site generator that renders LaTeX on the web. The possibilities are endless, and now you have a solid foundation for any **convert word to txt** workflow. -Got questions about edge cases, licensing, or performance tweaks? Drop a comment below—happy coding! +Happy coding, and may your LaTeX always compile on the first try! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/english/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/english/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..535923be30 --- /dev/null +++ b/words/english/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-01 +description: Save Word as PDF using Aspose.Words in C#. Learn to convert docx to PDF, + detect missing fonts and handle font substitution warnings efficiently. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: en +og_description: Save Word as PDF using Aspose.Words. This step‑by‑step tutorial shows + how to convert docx to pdf and detect missing fonts. +og_title: Save Word as PDF with Aspose.Words – Complete Guide +tags: +- Aspose.Words +- C# +- PDF conversion +title: Save Word as PDF with Aspose.Words – Complete Guide +url: /net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save Word as PDF with Aspose.Words – Complete Guide + +Ever needed to **save Word as PDF** on the fly and wondered whether you’d miss a font along the way? You’re not alone—developers constantly grapple with missing‑font headaches when converting documents. In this guide we’ll walk through a hands‑on solution that not only **convert docx to pdf** but also **detect missing fonts** using Aspose.Words’ font‑substitution warnings. + +We’ll cover everything from setting up the warning collector to interpreting the output, so by the end you’ll know exactly how to **save Word as PDF** without surprises. No external tools, no obscure settings—just clean C# code you can drop into any .NET project. + +## What You’ll Need + +- **Aspose.Words for .NET** (latest version, e.g., 24.10) – you can grab it via NuGet (`Install-Package Aspose.Words`). +- A .NET development environment (Visual Studio, Rider, or VS Code works fine). +- A sample DOCX file that may contain fonts not installed on the target machine. +That’s it. If you’ve got those basics, we’re ready to dive in. + +## Save Word as PDF – Step‑by‑Step Overview + +Below is the full, runnable program. Feel free to copy‑paste it into a console app project and hit **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** Replace `YOUR_DIRECTORY` with an absolute path or use `Path.Combine(Environment.CurrentDirectory, "input.docx")` for a relative, safer approach. + +### Why We Use a Warning Callback + +Aspose.Words silently substitutes missing fonts with a fallback (usually Arial). Without a callback you’d never know that substitution happened, which can lead to layout glitches in the resulting PDF. By hooking `IWarningCallback`, we get a clear, programmatic list of every missing‑font event—perfect for logging or notifying end‑users. + +### Detect Missing Fonts – What to Look For + +When you run the program, any missing font will produce a console line similar to: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +If the list is empty, congratulations—**save word as pdf** succeeded with all original fonts intact. + +## Convert Docx to PDF – Customizing the Output + +Sometimes you need a specific PDF version, image quality, or compliance level. Aspose.Words lets you tweak the `PdfSaveOptions` object before calling `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Why this matters:** If you’re generating PDFs for legal archives, setting `PdfA1b` ensures the file meets strict standards. The same conversion still respects our warning callback, so you’ll still **detect missing fonts**. + +## Aspose Words Font Substitution – Handling Edge Cases + +### Scenario 1: Multiple Missing Fonts + +If your source document uses several custom fonts, the warning collector will contain one entry per font. You can aggregate them: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenario 2: Providing a Fallback Font Directory + +Aspose.Words can search additional folders for fonts. Set the `FontsFolder` property on `FontSettings` before loading the document: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Now the library will try your custom folder first, reducing the chance of unwanted substitution. + +### Scenario 3: Ignoring Substitutions + +If you prefer the conversion to fail when a font is missing (instead of silently substituting), throw an exception inside the callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +This forces you to address the missing font before proceeding—useful in CI pipelines where silent failures are unacceptable. + +## Full End‑to‑End Example + +Putting everything together, here’s a compact version that demonstrates **how to convert Word to PDF**, sets custom PDF options, and logs any font issues: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Expected console output** (if Calibri is missing): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +If no warnings appear, your **save word as pdf** operation used the exact same fonts as the source DOCX. + +## Visual Summary + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Image alt text:* **save word as pdf** workflow showing loading, warning collection, and PDF output. + +## Common Questions & Answers + +| Question | Answer | +|----------|--------| +| **Do I need a license for Aspose.Words?** | A free evaluation license works for testing, but production use requires a paid license to remove the evaluation watermark. | +| **Will this work on .NET Core / .NET 6+?** | Absolutely—Aspose.Words targets .NET Standard 2.0, so any recent .NET runtime is compatible. | +| **Can I convert multiple DOCX files in a loop?** | Yes, just instantiate a new `Document` for each file and reuse the same `WarningInfoCollector` if you want aggregated results. | +| **What if the output folder doesn’t exist?** | `Document.Save` will throw `DirectoryNotFoundException`. Create the folder first or use `Directory.CreateDirectory`. | +| **Is there a way to embed the missing fonts into the PDF?** | Aspose.Words can embed fonts automatically if they are available on the machine; set `PdfSaveOptions.EmbedFullFonts = true`. | + +## Conclusion + +You now have a solid, production‑ready pattern to **save Word as PDF** while **detecting missing fonts** and handling **Aspose.Words font substitution** scenarios. By attaching a warning callback, customizing font folders, and optionally tweaking `PdfSaveOptions`, you can reliably **convert docx to pdf** and keep your users informed about any font issues that might affect layout fidelity. + +Ready for the next step? Try generating PDFs from multiple documents in parallel, or explore adding watermarks and digital signatures—both are straightforward extensions of the code you just mastered. Happy coding, and may your PDFs always look exactly as intended! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-loadoptions/_index.md b/words/english/net/programming-with-loadoptions/_index.md index 8aaf0351f5..dcdf55b6a5 100644 --- a/words/english/net/programming-with-loadoptions/_index.md +++ b/words/english/net/programming-with-loadoptions/_index.md @@ -41,6 +41,7 @@ In these tutorials, you will learn how to use LoadOptions to load Word documents | [Recover Word Document with Aspose.Words in C#](./recover-word-document-with-aspose-words-in-c/) | Learn how to recover corrupted Word documents using Aspose.Words for .NET in C# with a step-by-step guide. | | [how to recover docx – set recovery mode & open corrupted Word files](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Learn how to set recovery mode and open corrupted Word files using Aspose.Words for .NET. | | [How to Use LoadOptions in Aspose.Words – Complete Guide](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | A comprehensive guide on using LoadOptions in Aspose.Words for .NET, covering all settings and best practices. | +| [Recover corrupted docx – Full Guide to Loading Damaged Word Files in C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Learn how to load and recover damaged DOCX files in C# using Aspose.Words, with step-by-step instructions and code examples. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/english/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/english/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..a04a8a6fa5 --- /dev/null +++ b/words/english/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: Recover corrupted docx files quickly using Aspose.Words. Learn how to + set recovery mode, load docx safely, and read damaged Word files in just a few steps. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: en +og_description: Recover corrupted docx files in C#. Set recovery mode, load docx safely, + and read damaged Word files with Aspose.Words. +og_title: Recover corrupted docx – Quick C# Guide +tags: +- Aspose.Words +- C# +- Document Recovery +title: Recover corrupted docx – Full Guide to Loading Damaged Word Files in C# +url: /net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Recover corrupted docx – Quick C# Guide + +Ever tried to open a Word file that just wouldn’t load and wondered if the content was lost forever? In many real‑world projects you’ll **recover corrupted docx** files without asking the user to resend the attachment. The good news is that Aspose.Words makes it a piece of cake: you simply set the recovery mode and let the library do the heavy lifting. + +In this tutorial we’ll walk through the exact steps to **recover corrupted docx** files, explain why the `RecoveryMode.AutoRecover` option is the safest choice, and show you how to **how to load docx** files that might be partially damaged. By the end you’ll be able to read a damaged Word file, extract whatever text survived, and even log the original format for future audits. No external tools, just clean C# code. + +## What You’ll Need + +- **Aspose.Words for .NET** (any recent version; the API we use works with 23.5 and newer). +- A .NET development environment (Visual Studio, VS Code, or Rider). +- The corrupted or partially damaged `.docx` you want to salvage. + +No special permissions, no COM interop, and no need to install Microsoft Office on the server. Simple, right? + +## Step 1: Set Recovery Mode to Auto‑Recover + +When a Word file is broken, the default loading behavior throws an exception and aborts. By configuring a `LoadOptions` object you tell Aspose.Words to **set recovery mode** to `AutoRecover`, which scans the zip package, skips unreadable parts, and returns whatever it can piece together. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Why AutoRecover?** +> It attempts to read as much as possible while keeping the document object usable. If you pick `RecoveryMode.NoRecovery`, the load will fail on the first corruption, which defeats the purpose of **recover corrupted docx** scenarios. + +## Step 2: Load the Document with the Configured Options + +Now that the recovery mode is set, you can safely attempt to open the file. Replace `"YOUR_DIRECTORY/input.docx"` with the actual path to your damaged file. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +If the file is only partially corrupted, the `Document` instance will still be created. You can check `document.IsStructureValid` later if you need extra validation. + +## Step 3: Verify the Detected Format + +Aspose.Words automatically detects the original format (DOC, DOCX, ODT, etc.). Printing this value helps you confirm that the library recognized the file correctly, which is a quick sanity check after a **recover corrupted docx** operation. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typical output: + +``` +Loaded with Docx format. +``` + +Even if some parts were missing, the format detection still succeeds—another win for **recover corrupted docx** workflows. + +## Step 4: Extract What You Can + +Once the document is loaded, you can treat it like any healthy Word file. Below is a compact example that extracts plain text and writes it to the console. This demonstrates that you can **read damaged word file** content without crashes. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +If the original file had tables or images that were corrupted, they’ll simply be omitted from the text output. The rest of the document remains intact. + +## Step 5: Save a Clean Copy (Optional) + +Often you’ll want to give the user a new, clean version of the file after recovery. Saving with the same format ensures compatibility with any downstream processes. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Now you have a **recover damaged docx** file that you can safely attach to an email or pass to another service. + +## Full Working Example + +Putting it all together, here’s the complete, ready‑to‑run program. Paste it into a new console project, adjust the file paths, and hit F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Expected output** (assuming the file contains a single paragraph “Hello world!” and some corrupted XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Notice how the program never crashes—even though the source file was partially broken. That’s the essence of **recover corrupted docx** using Aspose.Words. + +## Common Questions & Edge Cases + +### What if the file is completely unreadable? + +Even `AutoRecover` has limits. If the zip container itself is corrupted beyond repair, Aspose.Words will throw a `CorruptedFileException`. In that case you might need a third‑party zip repair tool before trying to **recover corrupted docx** again. + +### Can I recover other formats (e.g., `.doc`, `.odt`)? + +Absolutely. The same `LoadOptions` works for any format Aspose.Words supports. Just change the file extension and the library will detect the original format automatically. This means you can also **recover damaged docx**‑like files such as `.doc` or `.rtf` with identical code. + +### How do I handle large documents without loading everything into memory? + +For gigabyte‑size files you can enable **load options** like `LoadOptions.LoadFormat` or stream the document page‑by‑page. However, the recovery algorithm still needs to read the whole package, so expect higher memory usage for very large corrupted files. + +### Is there a way to know which parts were lost? + +After loading, you can inspect `document.GetChildNodes(NodeType.Any, true)` and compare the count with an expected baseline. Missing tables, images, or headers will simply be absent from the node collection. This lets you log exactly what was **recover damaged docx** and inform the user. + +## Pro Tips for Reliable Recovery + +- **Validate the input file size** before loading; a zero‑byte file will always fail. +- **Log the `RecoveryMode` result** by catching `DocumentLoadingException` and storing the exception message; it often contains clues about which parts were skipped. +- **Run the recovery on a background thread** if you’re processing uploads in a web service—this keeps the request responsive. +- **Combine with a checksum** (e.g., MD5) to detect if the recovered file differs from the original; you can then decide whether to keep both versions. + +## Conclusion + +We’ve just shown how to **recover corrupted docx** files in C# by **setting recovery mode** to `AutoRecover`, loading the document safely, extracting whatever text survives, and optionally saving a clean copy. This approach lets you **how to load docx** files that would otherwise throw exceptions, and it gives you a reliable way to **read damaged word file** content without external tools. + +Next steps? Try swapping `RecoveryMode.AutoRecover` with `RecoveryMode.NoRecovery` to see the difference, or experiment with the `LoadOptions` properties that control password handling and font substitution. You could also integrate the recovery routine into an ASP.NET Core API that accepts uploads and returns a repaired file—perfect for enterprise document‑management pipelines. + +Got more questions about Word document recovery, or want to see how to **recover damaged docx** files with custom callbacks? Drop a comment below, and happy coding! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-markdownsaveoptions/_index.md b/words/english/net/programming-with-markdownsaveoptions/_index.md index dd737d44f7..fc8bdd87e3 100644 --- a/words/english/net/programming-with-markdownsaveoptions/_index.md +++ b/words/english/net/programming-with-markdownsaveoptions/_index.md @@ -24,12 +24,14 @@ Words Processing with MarkdownSaveOptions is an in-depth resource that walks you | --- | --- | | [Export Into Markdown With Table Content Alignment](./export-into-markdown-with-table-content-alignment/) | Learn how to export Word documents into Markdown with aligned tables using Aspose.Words for .NET. Follow our step-by-step guide for perfect Markdown tables. | | [Set Images Folder](./set-images-folder/) | Convert Word documents to Markdown with proper table alignment using Aspose.Words for .NET. Follow our detailed guide for perfect results. | +| [Upload Images to Cloud When Converting Word to Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) | Learn how to upload images to cloud storage while converting Word documents to Markdown using Aspose.Words for .NET. | | [Save Word as PDF and Recover Corrupted Word – Convert Word to Markdown in C#](./save-word-as-pdf-and-recover-corrupted-word-convert-word-to/) | | | [Create Accessible PDF and Convert Word to Markdown – Full C# Guide](./create-accessible-pdf-and-convert-word-to-markdown-full-c-gu/) | Learn how to create accessible PDFs and convert Word documents to Markdown using Aspose.Words in C#. | | [How to Use Markdown: Convert DOCX to Markdown with LaTeX Equations](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | Learn how to convert DOCX files to Markdown while preserving LaTeX equations using Aspose.Words for .NET. | | [Save docx as markdown – Complete C# Guide with LaTeX Equations](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | Learn how to save DOCX as Markdown with LaTeX equations using Aspose.Words for .NET. | | [save docx as markdown – Full C# Guide with Image Extraction](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Learn how to save DOCX as Markdown with image extraction using Aspose.Words for .NET. | | [Save docx as markdown with Aspose.Words – Full C# Guide](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | | +| [save docx as markdown – Export Word Math to LaTeX with Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Export Word Math equations to LaTeX while saving DOCX as Markdown using Aspose.Words. | | [Convert Word to Markdown in C# – Full Guide with Image Extraction](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) | Learn how to convert Word documents to Markdown in C# with full image extraction using Aspose.Words for .NET. | | [Convert docx to markdown – Step‑by‑Step C# Guide](./convert-docx-to-markdown-step-by-step-c-guide/) | Learn how to convert DOCX files to Markdown in C# with a detailed step‑by‑step guide using Aspose.Words for .NET. | | [How to Export Markdown from Word – Complete C# Guide](./how-to-export-markdown-from-word-complete-c-guide/) | | diff --git a/words/english/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/english/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..1543ec2fee --- /dev/null +++ b/words/english/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-05-01 +description: save docx as markdown using Aspose.Words – learn to convert word to markdown, + export equations to latex, and set markdown image resolution in one smooth workflow. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: en +og_description: save docx as markdown with Aspose.Words. This tutorial shows how to + convert word to markdown, export equations to latex, and set markdown image resolution. +og_title: save docx as markdown – Full Guide to Export Word Math as LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: save docx as markdown – Export Word Math to LaTeX with Aspose.Words +url: /net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# save docx as markdown – Export Word Math to LaTeX with Aspose.Words + +Ever needed to **save docx as markdown** but got stuck on how to keep those Office Math equations looking sharp? You're not the only one. Most developers hit a wall when the default conversion drops equations as blurry images, forcing a manual rewrite in LaTeX. + +Good news: Aspose.Words can do the heavy lifting for you. In this tutorial we’ll **convert word to markdown**, tell the engine to **export equations to latex**, and even **set markdown image resolution** for the rest of the document. By the end you’ll have a single command that spits out a clean `.md` file with LaTeX‑ready math and high‑resolution images. + +## What You’ll Learn + +- How to load a `.docx` that contains Office Math objects. +- Which `MarkdownSaveOptions` properties control **export equations to latex** and **set markdown image resolution**. +- A complete, runnable C# snippet that you can paste into any .NET project. +- Tips for troubleshooting common pitfalls, like missing fonts or unsupported equation features. + +**Prerequisites**: .NET 6+ (or .NET Framework 4.6+), a license for Aspose.Words for .NET, and a basic familiarity with C#. If you’re comfortable creating a console app, you’re ready to roll. + +--- + +## Step 1 – Save docx as markdown: Load Your Word File + +The first thing we need is a `Document` object that points at the source `.docx`. Think of it as opening the book before you start copying chapters. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Why this matters*: If the document doesn’t contain any math, the **export equations to latex** step will be a no‑op, but the rest of the conversion still runs. The check saves you from wondering why your output Markdown is missing LaTeX blocks. + +--- + +## Step 2 – Configure Export Equations to LaTeX + +Aspose.Words lets you decide how Office Math should be rendered. By default it turns them into PNG images, which is why many tutorials end up with a grainy markdown file. Switching the `OfficeMathExportMode` to `LaTeX` gives you clean, copy‑paste‑ready equations. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Why `OfficeMathExportMode.LaTeX`?* LaTeX is the lingua franca of scientific publishing. When you later render the markdown with a static‑site generator or a Jupyter notebook, the equations will appear crisp at any zoom level. + +--- + +## Step 3 – Set Markdown Image Resolution (for Non‑Math Content) + +Even though we’re focusing on math, most Word documents also contain pictures, charts, or embedded SVGs. The `ImageResolution` property controls how Aspose.Words rasterizes those assets. A value of **300 DPI** is a sweet spot for screen and print. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: If your markdown will be displayed on the web only, you might drop this to 150 DPI to keep file size down. Conversely, for print‑ready PDFs, bump it up to 600 DPI. + +--- + +## Step 4 – Run the Conversion – Convert Word Math LaTeX + +Now that everything is configured, the actual conversion is a single line. Aspose.Words does the heavy lifting behind the scenes. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: Open the generated `.md` file and you should see something like: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Notice the LaTeX blocks (`$...$` and `$$...$$`) replacing the previous PNG snippets. The image at the bottom is still a PNG, rendered at 300 DPI as we requested. + +--- + +## Step 5 – Common Edge Cases & How to Handle Them + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (e.g., Cambria Math not installed) | LaTeX output may contain unknown symbols. | Install the missing font on the server or embed it in the document before conversion. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words may fall back to an image despite `LaTeX` mode. | Upgrade to the latest Aspose.Words version; the library continuously improves equation coverage. | +| **Large documents** ( > 50 MB ) | Memory pressure can cause `OutOfMemoryException`. | Use `LoadOptions` with `LoadFormat.Docx` and stream the file, or split the document into sections before conversion. | +| **Image size too big** | Markdown file becomes huge, slowing down static‑site builds. | Reduce `ImageResolution` to 150 DPI for web‑only scenarios (see Step 3). | + +--- + +## Step 6 – Put It All Together: Full Working Example + +Below is the *complete* console‑app program you can copy‑paste into `Program.cs`. It includes all the bits we discussed, plus a little extra error handling. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Run the program (`dotnet run`) and you’ll get a markdown file that **save docx as markdown** while preserving every equation as LaTeX. No manual copy‑pasting, no ugly raster images for math. + +--- + +## Conclusion + +We’ve walked through the entire process of **saving docx as markdown** with Aspose.Words, from loading the Word file to configuring **export equations to latex** and **set markdown image resolution**. The final snippet is production‑ready, and you can drop it into any .NET project that needs to **convert word to markdown** on the fly. + +What’s next? Try feeding the generated `.md` into a static‑site generator like Hugo or Jekyll and watch your equations render beautifully. If you need to **convert word math latex** into other formats (PDF, HTML), just swap `MarkdownSaveOptions` for `PdfSaveOptions` or `HtmlSaveOptions`—the same `OfficeMathExportMode` flag works across them. + +Got a twist in your workflow, like pulling Word files from Azure Blob storage or streaming them from an API? The same pattern applies; just replace the file‑system `Document` constructor with a stream‑based one. + +Feel free to experiment, and let us know in the comments how this approach solved your conversion headaches. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/english/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..0967c0f708 --- /dev/null +++ b/words/english/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-05-01 +description: Upload images to cloud while converting a Word document to markdown. + Learn how to extract images from docx and store them in Azure Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: en +og_description: Upload images to cloud while converting a Word document to markdown. + This guide shows how to extract images from docx and store them in Azure Blob storage. +og_title: Upload Images to Cloud When Converting Word to Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Upload Images to Cloud When Converting Word to Markdown +url: /net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Upload Images to Cloud When Converting Word to Markdown + +Ever needed to **upload images to cloud** while turning a Word file into markdown? You're not the only one—developers constantly juggle document conversion and asset management, and doing both in one smooth flow can feel like chasing a moving target. + +The good news? With Aspose.Words you can extract every picture, chart, or diagram from a .docx, push it straight to Azure Blob Storage, and let the generated markdown reference those cloud URLs instead of local files. In this tutorial we’ll walk through the whole process, from loading the source document to ending up with a clean markdown file that points at your Azure bucket. + +By the end of this guide you’ll be able to **convert docx to markdown**, **extract images from docx**, and **store images Azure Blob**—all with just a few lines of C#. No external tools, no manual copy‑pasting, and certainly no broken image links. + +## What You’ll Need + +- **.NET 6.0** or later (the code works on .NET Core and .NET Framework as well) +- **Aspose.Words for .NET** (NuGet package `Aspose.Words`) +- An **Azure Storage account** with a container (e.g., `images`) and a shared access key – you’ll need the connection string to upload files. +- A basic understanding of C# and async/await (optional but helpful). + +If you already have these pieces in place, great—let’s jump straight into the solution. If not, the “Prerequisites” section at the end will point you to quick setup steps. + +## Step 1: Set Up Azure Blob Helper (Why It Matters) + +Before we even touch the Word document, we need a tiny helper that knows how to push a byte array to Azure Blob Storage and return a public URL. This abstraction keeps the conversion logic clean and makes it easy to swap storage providers later. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Why this helper?** +1. **Separation of concerns** – the markdown conversion code stays focused on document handling, not on HTTP details. +2. **Reusability** – you can call `UploadAsync` from anywhere else in your app (e.g., for user‑uploaded pictures). +3. **Future‑proofing** – swapping to Amazon S3 or Google Cloud Storage only requires a new implementation of the same interface. + +> **Pro tip:** Set the container’s access level to `Blob` (public) only if you’re okay with anyone reading the images. For private scenarios, generate SAS tokens per upload and embed those URLs instead. + +## Step 2: Define a Resource‑Saving Callback (The Core of Upload‑While‑Convert) + +Aspose.Words lets you intercept every resource (image, chart, etc.) that would normally be written to disk when you save a document as markdown. By providing a `ResourceSavingCallback`, we can upload each resource to Azure Blob and replace the local filename with the cloud URL. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**What’s happening here?** + +- **Extract** – Aspose.Words gives us a stream for each image. +- **Upload** – We hand that stream to `AzureBlobUploader`. +- **Replace** – The markdown writer receives the public URL and writes it into the markdown image syntax (`![](https://…)`). + +Because we set `args.AlreadyExists = true`, no temporary files clutter the filesystem—a clean, stateless operation perfect for serverless functions. + +## Step 3: Configure Markdown Save Options (Tie Everything Together) + +Now we stitch the callback into the Aspose.Words `MarkdownSaveOptions`. The crucial flags are `ExportImagesAsBase64 = false` (so we get external links) and `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Why we disable Base64?** +When `ExportImagesAsBase64` is true, Aspose embeds every picture directly into the markdown as a data URI. That defeats the purpose of **upload images to cloud** because the markdown file balloons in size and the images stay hidden from the CDN. By turning it off we get clean, external links that point at Azure Blob—exactly what a modern static‑site generator expects. + +## Step 4: Put It All Together – A Minimal Console App + +Below is a complete, ready‑to‑run console program. Replace the placeholders with your actual Azure connection string and container name. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Expected Output + +Running the program with `sample.docx` that contains two pictures will produce: + +- `output.md` containing markdown image syntax like: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-pdfsaveoptions/_index.md b/words/english/net/programming-with-pdfsaveoptions/_index.md index e36f586bb2..a3422b95af 100644 --- a/words/english/net/programming-with-pdfsaveoptions/_index.md +++ b/words/english/net/programming-with-pdfsaveoptions/_index.md @@ -47,6 +47,7 @@ Whether you want to convert Word documents to PDF for online distribution, archi | [Render 3D DML 3DEffects in a PDF Document](./dml-3deffects-rendering/) | Learn how to render stunning 3D DML effects in PDF documents using Aspose.Words for .NET with this comprehensive step-by-step guide. | | [Interpolate Images in a PDF Document](./interpolate-images/) | Learn how to interpolate images in a PDF document using Aspose.Words for .NET with our step-by-step guide. Improve your PDF's image quality easily. | | [Save docx as pdf with Aspose.Words – Complete C# Guide](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Step-by-step guide to convert DOCX to PDF using Aspose.Words in C#, covering all essential settings. | +| [Save Document as PDF with Aspose.Words – Complete C# Guide](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Comprehensive C# guide to save any document as PDF using Aspose.Words, covering all key options and settings. | | [Create Accessible PDF from Word with C# – Step‑by‑Step Guide](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Learn how to create accessible PDFs from Word documents using Aspose.Words for .NET with C# in this step-by-step guide. | | [Create Accessible PDF in C# – PDF Accessibility Tutorial](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Learn how to generate accessible PDF files in C# using Aspose.Words, covering tags, alt text, and compliance with PDF/UA standards. | | [Create Accessible PDF from Word – Complete Guide](./create-accessible-pdf-from-word-complete-guide/) | Learn how to create accessible PDFs from Word documents using Aspose.Words for .NET in this comprehensive guide. | diff --git a/words/english/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/english/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..4b0a4c3379 --- /dev/null +++ b/words/english/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: Learn how to save document as pdf using Aspose.Words in C#. The tutorial + also covers convert word to pdf, export math latex, and handle missing fonts. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: en +og_description: Save document as pdf effortlessly with Aspose.Words. This guide also + shows how to convert word to pdf, export math latex, and handle missing fonts. +og_title: Save Document as PDF with Aspose.Words – Complete C# Guide +tags: +- Aspose.Words +- C# +- PDF generation +title: Save Document as PDF with Aspose.Words – Complete C# Guide +url: /net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save Document as PDF with Aspose.Words – Complete C# Guide + +Ever wondered **how to save document as pdf** directly from a Word file without losing accessibility features? You're not the only one—developers constantly ask for a reliable way to convert Word to PDF while preserving math equations and handling missing fonts gracefully. + +In this tutorial we’ll walk through a step‑by‑step solution that not only **save document as pdf** but also demonstrates **convert word to pdf**, **export math latex**, and **handle missing fonts** using the latest Aspose.Words for .NET. By the end you’ll have a ready‑to‑run C# program that produces PDF/UA‑2 compliant files, perfect for accessibility audits. + +## What You’ll Need + +- .NET 6 or later (the code works with .NET Core and .NET Framework as well) +- Aspose.Words for .NET 25.10 or newer – you can grab a free trial from the Aspose website +- A modest Word document (`input.docx`) that contains at least one floating shape and a math equation (to see the export‑math‑latex feature in action) +- Visual Studio 2022 (or any IDE you like) + +> **Pro tip:** If you’re on a CI/CD pipeline, add the Aspose.Words NuGet package to your project file: + +```xml + +``` + +Now let’s dive into the code. + +## Step 1: Load the Source Document with Automatic Recovery + +When dealing with real‑world Word files you might encounter corrupt sections or missing resources. Enabling automatic recovery ensures the loading process never throws an exception. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Why this matters:** +`RecoveryMode.AutoRecover` protects your pipeline from crashing on malformed input, which is especially handy when you **convert word to pdf** in bulk. + +## Step 2: Set Up PDF Save Options for Full Accessibility + +PDF/UA‑2 is the ISO standard for accessible PDFs. By configuring a few flags we get a file that screen readers can navigate, and we also make sure math equations are exported as hidden LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – makes sure the resulting PDF respects the original layout while staying semantically correct. +- **OfficeMathExportMode.LaTeX** – satisfies the **export math latex** requirement, letting downstream tools extract the equations if needed. + +## Step 3: Capture Warnings (e.g., Missing Fonts) + +Missing fonts are a common headache when converting documents. Aspose.Words can report these issues via a `WarningCallback`. We’ll collect them so you can log or act on them later. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Why you care:** +If the source uses a font that isn’t installed on the server, the PDF will fall back to a default font, potentially breaking the layout. By **handle missing fonts** we can alert the user or embed a substitute. + +## Step 4: Save the Document as an Accessible PDF + +Now the moment of truth—actually performing the conversion. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +If everything goes smoothly, you’ll end up with a PDF/UA‑2 file that contains hidden LaTeX for each equation and proper tagging for floating shapes. + +## Step 5: Review Captured Warnings (Optional but Recommended) + +After the save operation, you can iterate over the collected warnings and log them. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typical output might look like: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Seeing these messages early helps you **handle missing fonts** before they affect end‑users. + +## Full Working Example + +Putting everything together, here’s the complete, ready‑to‑run program. Replace the placeholder paths with your own. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` complies with PDF/UA‑2. +- All floating shapes are tagged as inline figures. +- Every Office Math object appears as hidden LaTeX (visible when you inspect the PDF’s structure). +- Any font‑related issues are printed to the console, giving you a chance to **handle missing fonts** before shipping the file. + +![Diagram showing the flow from Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flow diagram for saving document as pdf") + +*Image alt text:* **Diagram of how to save document as pdf using Aspose.Words** + +## Common Questions & Edge Cases + +### What if I’m using an older Aspose.Words version? + +The `OfficeMathExportMode.LaTeX` flag was introduced in 25.10. For older releases you can still **convert word to pdf**, but the math will be rasterized instead of exported as LaTeX. Upgrade for best accessibility. + +### Can I embed custom fonts to avoid fallback? + +Yes. Set `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` before calling `Save`. This also helps **handle missing fonts** by forcing the PDF to contain the required glyphs. + +### How do I verify the PDF/UA‑2 compliance? + +Open the file in Adobe Acrobat Pro → “Print Production” → “Preflight”. Choose the “PDF/A‑2b” or “PDF/UA‑2” profile; Acrobat will report any violations. + +### What about password‑protected Word files? + +Load the document with a `LoadOptions` that includes `Password`. Example: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +The rest of the pipeline stays unchanged. + +## Conclusion + +We’ve covered everything you need to **save document as pdf** using Aspose.Words in C#. The tutorial also demonstrated how to **convert word to pdf**, **export math latex**, and **handle missing fonts**—all while producing an accessible PDF/UA‑2 file. + +Give the code a spin, experiment with different `PdfSaveOptions` (e.g., image compression, PDF/A‑2b), and integrate it into your document‑processing service. If you need to go further, consider exploring Aspose’s PDF‑specific library for post‑processing or digital signatures. + +Got more scenarios you’d like to tackle? Feel free to drop a comment or check out our other guides on **PDF manipulation**, **image extraction**, and **batch conversion**. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-shapes/_index.md b/words/english/net/programming-with-shapes/_index.md index 0699aad0f1..605e7a3985 100644 --- a/words/english/net/programming-with-shapes/_index.md +++ b/words/english/net/programming-with-shapes/_index.md @@ -38,6 +38,7 @@ By using Aspose.Words for .NET and following these tutorials, you will be able t | [Create rectangle shape in Word using C# – Step‑by‑Step Guide](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Learn how to create a rectangle shape in a Word document using C# with Aspose.Words for .NET in this step‑by‑step guide. | | [Aspose.Words Shape Shadow Tutorial – Add a Shadow to Word Shape in C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Learn how to add shadows to shapes in Word documents using Aspose.Words for .NET with this step-by-step C# guide. | | [Create Blank Word Document with Shadowed Rectangle Shape – Step‑by‑Step Guide](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Learn how to create a blank Word document and add a shadowed rectangle shape using Aspose.Words for .NET in this step‑by‑step guide. | +| [How to Move Shadow in Aspose.Words – Complete C# Guide](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Learn how to move shape shadows in Word documents using Aspose.Words for .NET with this comprehensive C# guide. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/english/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/english/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..f758151bc6 --- /dev/null +++ b/words/english/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-01 +description: How to move shadow on a shape in Aspose.Words using C#. Learn to add + shadow to shape, change blur, set transparency, and rotate shadow in minutes. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: en +og_description: How to move shadow on a shape in Aspose.Words using C#. This tutorial + shows you how to add shadow to shape, change blur, set transparency, and rotate + shadow. +og_title: How to Move Shadow in Aspose.Words – Complete C# Guide +tags: +- Aspose.Words +- C# +- Document Automation +title: How to Move Shadow in Aspose.Words – Complete C# Guide +url: /net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Move Shadow in Aspose.Words – Complete C# Guide + +Ever wondered **how to move shadow** on a shape inside a Word document without opening Word manually? In my day‑to‑day work, I’ve often needed to tweak a shape’s shadow programmatically—whether it’s for a polished report or a dynamic template. The good news? With Aspose.Words you can do it in a handful of lines, and you’ll also learn **add shadow to shape**, **how to change blur**, **how to set transparency**, and **how to rotate shadow** in the same pass. + +In this tutorial we’ll walk through a real‑world scenario: loading an existing DOCX that already has a shape, adjusting the shadow’s position, softness, opacity, and direction, and finally saving the result. By the end you’ll have a reusable snippet that you can drop into any .NET project, and you’ll understand why each property matters. + +## Prerequisites – What You Need Before You Start + +- **Aspose.Words for .NET** (version 23.12 or later). You can grab it from NuGet with `Install-Package Aspose.Words`. +- A .NET 6+ development environment (Visual Studio, VS Code, Rider—whatever you prefer). +- An input Word file (`input.docx`) that already contains at least one shape (a rectangle, circle, or picture will do). +- Basic familiarity with C# syntax—nothing fancy. + +If you’re missing any of those, pause for a moment and install the library; the rest of the guide assumes the package is already referenced. + +## Step 1: Load the Document and Grab the Target Shape – **How to Move Shadow** Begins Here + +The first thing we do is load the source document and locate the shape we want to modify. Aspose.Words treats every object (paragraphs, tables, shapes) as a node in a tree, so we can query it directly. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Why this matters:** Loading the document once and reusing the same `Document` instance is efficient. The `GetChild` call is safe because it returns `null` if the index is out of range, letting us handle missing shapes gracefully. + +## Step 2: Adjust the Blur Radius – Master **How to Change Blur** + +A soft shadow looks professional, while a hard edge can feel cheap. The `BlurRadius` property controls the softness in points (1 pt ≈ 1/72 inch). Let’s bump it up to 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** The default blur is 0.5 pt. Anything above 5 pt is usually noticeable, but beware of making it too large—it can make the shape look detached from the page. + +## Step 3: Set Transparency – The Answer to **How to Set Transparency** + +Transparency determines how see‑through the shadow is. A value of `0` means fully opaque; `1` means completely invisible. For a subtle effect we’ll use `0.3` (30 % transparent). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Why you might care:** If the shape is dark, a fully opaque shadow can drown the underlying text. Adjusting transparency keeps the document readable while still giving depth. + +## Step 4: Move the Shadow – The Core of **How to Move Shadow** + +The `Distance` property defines how far the shadow is offset from the shape, measured in points. A larger distance pushes the shadow farther away, creating a more dramatic effect. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **What if you need a tiny offset?** Setting `Distance` to `0` will make the shadow sit directly behind the shape, which can be useful for embossing effects. + +## Step 5: Rotate the Light Source – Solving **How to Rotate Shadow** + +Shadows aren’t just straight down; they follow the light source’s angle. The `Angle` property (in degrees) rotates the shadow around the shape. Let’s tilt it 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Quick experiment:** Try `90` for a right‑hand shadow or `-30` for a left‑leaning one. The visual change is immediate. + +## Step 6: Save the Document – Seeing the Result of **Add Shadow to Shape** + +Now that we’ve tweaked the shadow, we’ll write the document back to disk. You can overwrite the original or create a new file; the example uses a new output file. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Expected output:** Open `output.docx`. The shape’s shadow will appear softer, slightly offset, semi‑transparent, and angled at 45°. If you compare it side‑by‑side with `input.docx`, the difference is unmistakable. + +### Full Working Example (Copy‑Paste Ready) + +Below is the entire program in one block. Paste it into a new console project, replace `YOUR_DIRECTORY` with an actual folder path, and run. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Common Questions & Edge Cases + +### What if the document has multiple shapes? + +You can loop through all shapes: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Can I add a shadow to a shape that currently has none? + +Absolutely. The `ShadowFormat` object is always present; you just need to enable it: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Does this work with pictures and SmartArt? + +Yes. Any node that derives from `Shape`—including pictures, charts, and SmartArt—exposes `ShadowFormat`. The same properties apply. + +### How do I control the shadow color? + +Use the `Color` property: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Compatibility concerns? + +Aspose.Words 23.12+ supports .NET 6, .NET Core 3.1, and .NET Framework 4.6.2+. The API shown is stable across these versions. + +## Conclusion + +We’ve just covered **how to move shadow** on a shape using Aspose.Words, and along the way we also demonstrated **add shadow to shape**, **how to change blur**, **how to set transparency**, and **how to rotate shadow**. The complete, runnable example lets you tweak any shape’s shadow in a matter of seconds, giving your documents a polished, professional look without ever opening Word. + +Ready for the next step? Try combining these shadow tweaks with **conditional formatting**—for example, only apply a deeper shadow to headings or to charts that exceed a certain size. Or explore **gradient fills** for the shape itself to create a truly eye‑catching design. + +If you hit any snags, drop a comment below. Happy coding, and may your shadows always fall just where you want them! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/basic-conversions/_index.md b/words/french/net/basic-conversions/_index.md index 2908e53d29..57afcd3d74 100644 --- a/words/french/net/basic-conversions/_index.md +++ b/words/french/net/basic-conversions/_index.md @@ -23,8 +23,9 @@ Conversions de base vous guide dans les conversions de documents de base avec la | --- | --- | | [Convertir un document en Docx](./doc-to-docx/) | Apprenez à convertir un fichier DOC en DOCX avec Aspose.Words pour .NET. Guide étape par étape avec exemples de code. Idéal pour les développeurs. | | [Convertir Docx en RTF](./docx-to-rtf/) | Apprenez à convertir un fichier DOCX en RTF avec Aspose.Words pour .NET grâce à notre guide étape par étape. Conversion facile pour un traitement fluide des documents. | -| [Convertir un fichier Word en PDF](./docx-to-pdf/) Découvrez comment convertir facilement des fichiers Word en PDF avec Aspose.Words pour .NET grâce à notre guide. Idéal pour les développeurs recherchant une conversion de documents rapide et fiable. | +| [Convertir un fichier Word en PDF](./docx-to-pdf/) Découvrez comment convertir facilement des fichiers Word en PDF avec Aspose.Words pour .NET grâce à notre guide. Idéal pour les développeurs recherchant une conversion de documents rapide et fiable. | | [Enregistrer un document Word au format PDF avec Aspose.Words – Guide complet C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Apprenez à enregistrer un document Word en PDF avec Aspose.Words en C#, guide complet pas à pas. | +| [Enregistrer un document Word au format PDF avec Aspose.Words – Guide complet](./save-word-as-pdf-with-aspose-words-complete-guide/) | Apprenez à enregistrer un document Word en PDF avec Aspose.Words, guide complet étape par étape. | | [Enregistrer un docx en PDF avec Aspose.Words – Guide complet C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Apprenez à convertir un fichier DOCX en PDF avec Aspose.Words en C#, guide complet pas à pas. | | [Convertir Docx en octets](./docx-to-byte/) | Apprenez à convertir un document Docx en tableau d'octets dans .NET avec Aspose.Words pour un traitement efficace des documents. Guide étape par étape inclus. | | [Convertir Docx en Epub](./docx-to-epub/) | Convertissez facilement vos fichiers DOCX en EPUB avec Aspose.Words pour .NET. Suivez notre tutoriel pour une intégration transparente à vos applications .NET. | diff --git a/words/french/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/french/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index dea21be6fe..76e1a12404 100644 --- a/words/french/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/french/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Comment exporter du LaTeX depuis Word avec Aspose.Words – apprenez à - convertir Word en LaTeX, à enregistrer le docx en txt et à gérer les équations en - texte brut. +date: 2026-05-01 +description: Apprenez comment exporter du LaTeX depuis un fichier Word, convertir + Word en txt et conserver les tableaux avec Aspose.Words en C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: fr -og_description: Comment exporter LaTeX depuis Word avec Aspose.Words. Ce guide vous - montre comment convertir Word en LaTeX, enregistrer le docx en txt et conserver - les équations intactes. -og_title: Comment exporter LaTeX depuis Word – Tutoriel C# rapide +og_description: Découvrez comment exporter du LaTeX depuis Word, convertir Word en + texte brut et garder la mise en page du tableau intacte avec Aspose.Words. +og_title: Comment exporter LaTeX depuis Word – Tutoriel complet C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Comment exporter LaTeX depuis Word – Guide étape par étape url: /fr/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,179 +26,215 @@ url: /fr/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Comment exporter du LaTeX depuis Word – Guide étape par étape +# Comment exporter du LaTeX depuis Word – Tutoriel complet en C# -Vous vous êtes déjà demandé **comment exporter du LaTeX depuis Word** sans perdre aucune de ces équations Office Math compliquées ? Vous n'êtes pas le seul. De nombreux développeurs se heurtent à un mur lorsqu'ils essaient de *convertir Word en LaTeX* pour des articles académiques, des rapports scientifiques ou des pipelines de publication automatisés. +Vous vous êtes déjà demandé **comment exporter du LaTeX** à partir d’un document Word sans perdre les équations ? Vous n’êtes pas seul. De nombreux développeurs doivent transformer un .docx contenant des Office Math en LaTeX propre tout en **convertissant Word en txt** pour un traitement en aval. Dans ce guide, nous parcourrons une solution pratique, prête à l’emploi, qui **préserve les tableaux**, vous fournit un fichier texte brut et garde le balisage LaTeX exactement où vous le souhaitez. -Dans ce tutoriel, nous parcourrons un exemple complet, prêt à l’emploi en C#, qui montre **comment exporter du LaTeX** en utilisant Aspose.Words, explique **comment enregistrer des fichiers txt** avec du balisage LaTeX, et couvre même les subtilités de **convert word equations latex** afin que rien ne se perde lors de la conversion. +Nous couvrirons tout, du chargement du fichier source à l’ajustement de `TxtSaveOptions` pour que la sortie soit à la fois lisible par l’homme et exploitable par la machine. À la fin, vous saurez **enregistrer docx en txt**, **convertir Word en texte brut**, et **comment préserver les tableaux** lors de l’exportation. Aucun script externe, aucune copie‑collage manuelle — juste du code C# pur que vous pouvez intégrer à n’importe quel projet .NET. -> **Astuce :** La même approche fonctionne pour n’importe quel .docx que vous avez—il suffit de pointer le code vers un autre chemin de fichier. +## Ce dont vous aurez besoin + +- **Aspose.Words for .NET** (dernière version, 2024.x ou plus récente). Le package NuGet est `Aspose.Words`. +- Un environnement de développement .NET (Visual Studio, VS Code, Rider—celui qui vous convient). +- Un fichier Word (`.docx`) contenant des équations Office Math et au moins un tableau (pour voir la magie de la préservation des tableaux). + +C’est tout. Si vous avez déjà ces éléments, continuez la lecture ; sinon, récupérez le package NuGet et un DOCX d’exemple avant d’aller plus loin. --- -## Ce dont vous aurez besoin +## Comment exporter du LaTeX depuis un document Word -Avant de commencer, assurez-vous de disposer des prérequis suivants : +Voici le cœur du tutoriel — trois étapes concises qui répondent à la question **comment exporter du latex** tout en gérant les objectifs secondaires de **convertir word en txt**, **convertir word en texte brut**, **enregistrer docx en txt**, et **comment préserver les tableaux**. -| Prérequis | Pourquoi c’est important | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words cible les runtimes .NET modernes. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | La bibliothèque effectue le travail lourd d’analyse de Word et d’émission du LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Pour voir la conversion LaTeX en action. | -| **Visual Studio 2022** (or any IDE you like) | Facilite le débogage et l’exécution de l’exemple. | +### Étape 1 : Charger le fichier DOCX -Si vous n’avez pas encore installé le package NuGet, exécutez : +Tout d’abord, nous devons lire le document Word dans un objet `Aspose.Words.Document`. Cette étape est identique que vous souhaitiez **convertir word en txt** ou **enregistrer docx en txt**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -C’est tout—pas de DLL supplémentaires, pas d’interop COM, juste une bibliothèque gérée propre. +> **Pourquoi c’est important :** Charger le fichier crée une représentation en mémoire de tous les éléments Word — paragraphes, tableaux et objets Office Math. Sans cet objet, vous ne pouvez pas manipuler les options d’exportation. ---- +### Étape 2 : Configurer `TxtSaveOptions` pour le LaTeX et la mise en page des tableaux -## Comment exporter du LaTeX depuis Word – Vue d’ensemble +La classe `TxtSaveOptions` vous permet de contrôler exactement comment le fichier texte brut est généré. Deux propriétés sont essentielles pour notre scénario : -Voici la vue d’ensemble de ce que nous allons réaliser : +| Propriété | Ce qu'elle fait | Pourquoi vous en avez besoin | +|-----------|----------------|------------------------------| +| `OfficeMathExportMode` | Détermine comment les Office Math sont rendus. Le définir sur `LaTeX` convertit les équations en syntaxe LaTeX. | C’est le cœur de **comment exporter du latex**. | +| `PreserveTableLayout` | Lorsque `true`, Aspose ajoute des espaces afin que les tableaux conservent une apparence en grille. | Cela satisfait **comment préserver les tableaux** pendant que vous **convertissez word en txt**. | -1. **Load** le document Word source (`.docx`). -2. **Configure** `TxtSaveOptions` afin que tout objet Office Math soit émis sous forme de code LaTeX. -3. **Save** le document en tant que fichier texte brut (`.txt`) que vous pouvez transmettre directement à n’importe quel compilateur LaTeX. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Exemple d'exportation de LaTeX depuis Word](image.png "Comment exporter du LaTeX depuis Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Astuce :** Si vous ne avez besoin que du LaTeX brut sans mise en forme de tableau, définissez `PreserveTableLayout` sur `false`. Le fichier devient plus petit, mais vous perdez l’indication visuelle du tableau. -## Étape 1 : Charger le document Word +### Étape 3 : Enregistrer le document en texte brut -Première chose à faire—ouvrir le .docx que vous souhaitez convertir. La classe `Document` abstrait tout le XML sous‑jacent, vous offrant un modèle d’objet convivial. +Nous écrivons maintenant le document dans un fichier `.txt` en utilisant les options que nous venons de définir. Cette ligne unique réalise **convertir word en texte brut**, **enregistrer docx en txt**, et, bien sûr, **comment exporter du latex** en une seule fois. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; - -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Pourquoi c’est important :** - -Charger le fichier dès le départ nous permet d’inspecter son contenu (par ex., compter les équations) avant de décider comment le sérialiser. Si le fichier est corrompu, `Document` lèvera une exception claire, vous évitant ainsi des sorties mystérieuses plus tard. +Une fois l’appel terminé, ouvrez `output.txt`. Vous verrez : ---- +- Des extraits LaTeX comme `\frac{a}{b}` pour chaque équation Office Math. +- Des tableaux rendus avec les caractères `|` et `-`, préservant l’alignement des colonnes. +- Des paragraphes ordinaires en texte brut, prêts pour n’importe quel parseur en aval. -## Étape 2 : Configurer TxtSaveOptions pour l’exportation LaTeX +### Exemple complet fonctionnel -La magie se produit dans `TxtSaveOptions`. En définissant `OfficeMathExportMode` sur `LaTeX`, chaque objet Office Math est transformé en sa représentation LaTeX correspondante. +En rassemblant le tout, voici un programme autonome que vous pouvez compiler et exécuter dès aujourd’hui : ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Pourquoi nous choisissons ces paramètres :** +**Sortie attendue** (extrait) : -- `OfficeMathExportMode.LaTeX` est le seul mode qui garantit une traduction mathématique fidèle. -- `PreserveTableLayout` conserve l’apparence des tableaux comme dans Word, ce qui est pratique lorsque vous intégrez ensuite la sortie dans un environnement LaTeX `tabular`. -- UTF‑8 assure que des caractères comme « α », « β » ou « ∑ » survivent au aller‑retour. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Si vous avez besoin de **convert word to latex** sans l’enveloppe texte brut, vous pouvez passer à `SaveFormat.LaTeX` à la place—juste une petite astuce pour les scénarios avancés. +Remarquez comment le tableau conserve sa grille et l’équation apparaît en LaTeX propre. C’est le compromis idéal lorsque vous **convertissez word en txt** tout en conservant une représentation fidèle de la structure et des mathématiques. --- -## Étape 3 : Enregistrer le document en tant que fichier texte +## Conseils pour convertir Word en TXT et préserver les tableaux -Nous écrivons maintenant le texte enrichi en LaTeX sur le disque. Le `.txt` résultant peut être renommé en `.tex` plus tard, ou envoyé directement à un compilateur LaTeX. +Si l’approche en trois étapes fonctionne dans la plupart des cas, les projets réels apportent souvent des surprises. Voici des suggestions pratiques pour rendre votre pipeline **convertir word en texte brut** robuste. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Utilisez un encodage cohérent -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` utilise UTF‑8 par défaut, ce qui couvre la plupart des caractères. Si vous avez besoin d’une autre page de code (par ex., les systèmes hérités attendent Windows‑1252), définissez la propriété `Encoding` : -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Ce que vous verrez dans `output.txt` :** +### Supprimez les espaces superflus -``` -\begin{equation} -E = mc^{2} -\end{equation} +Les tableaux avec de nombreuses colonnes peuvent générer des lignes très longues. Après l’enregistrement, vous pouvez post‑traiter le fichier pour transformer plusieurs espaces consécutifs en une seule tabulation : + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Tous les autres paragraphes apparaissent en texte brut, tandis que chaque équation Office Math est encapsulée dans un environnement LaTeX `equation` (ou `inline` si elle était en ligne dans Word). Cela satisfait parfaitement le besoin de **convert word equations latex**. +### Gérer les tableaux imbriqués ---- +Si votre DOCX contient des tableaux à l’intérieur d’autres tableaux, `PreserveTableLayout` conservera toujours la hiérarchie visuelle, mais l’indentation peut sembler étrange. Une solution rapide consiste à remplacer les espaces de début par un marqueur personnalisé (par ex., `>>`) afin que les parseurs en aval détectent les niveaux d’imbrication. -## Cas limites & questions fréquentes +### Traitement par lots de plusieurs fichiers -| Situation | Que faire | -|-----------|------------| -| **Pas d’équations dans la source** | La conversion fonctionne toujours ; vous obtiendrez simplement du texte brut. Aucun code LaTeX supplémentaire n’est ajouté. | -| **Documents très volumineux (>100 Mo)** | Envisagez de diffuser la sortie en utilisant `MemoryStream` pour éviter une forte consommation de mémoire. | -| **Constructions Math non prises en charge** | Aspose.Words couvre 99 % des Office Math. Pour le rare cas limite, vous devrez peut‑être post‑traiter le LaTeX manuellement. | -| **Besoin d’un fichier .tex au lieu de .txt** | Modifiez `outputPath` pour qu’il se termine par `.tex` et, éventuellement, définissez `txtOptions.Encoding` sur `Encoding.UTF8`. | -| **Exécution sous Linux/macOS** | Le même code fonctionne—assurez‑vous simplement que les chemins de fichiers utilisent des barres obliques ou `Path.Combine`. | +Lorsque vous devez **convertir word en txt** pour des dizaines de documents, encapsulez la logique dans une boucle : ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +Ainsi, vous pouvez **enregistrer docx en txt** en masse sans intervention manuelle. -## Comment enregistrer du TXT avec des équations LaTeX – Récapitulatif rapide +--- -1. **Load** le .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` dans `TxtSaveOptions`. -3. **Save** le fichier (`doc.Save`) avec ces options. +## Pièges courants et comment les éviter -C’est l’ensemble du flux de travail pour **how to save txt** les fichiers contenant des équations formatées en LaTeX. +1. **Mode d'exportation LaTeX manquant** – Si vous oubliez de définir `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, les équations retomberont en texte brut (ex. : “Equation 1”). Vérifiez toujours le bloc d’options. +2. **La mise en page du tableau est perdue** – `PreserveTableLayout` vaut `false` par défaut. Si votre sortie ressemble à un mur de texte, vous n’avez probablement pas activé le drapeau. +3. **Chemins de fichiers avec espaces** – Utiliser des chaînes verbatim (`@"C:\Mon Dossier\input.docx"`) évite les problèmes d’échappement. Sinon, vous obtiendrez une `FileNotFoundException`. +4. **Incompatibilité de version** – Les versions anciennes d’Aspose.Words (< 21.9) ne supportent pas `OfficeMathExportMode`. Mettez à jour vers le dernier package pour que **comment exporter du latex** fonctionne. +5. **Erreurs d'encodage pour les caractères non ASCII** – Si vous voyez des symboles �, définissez explicitement `options.Encoding` sur UTF‑8 ou la page de code appropriée. --- -## Bonus : Automatiser la conversion pour plusieurs fichiers +## Étendre la solution : du TXT au Markdown ou HTML -Si vous avez un dossier rempli de documents Word, encapsulez la logique ci‑dessus dans une boucle simple : +Parfois, vous avez besoin de plus qu’un texte brut — peut‑être un fichier Markdown contenant toujours des blocs LaTeX. La même logique peut être remplacée par `HtmlSaveOptions` ou `MarkdownSaveOptions` : ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Vous pouvez maintenant **convert word to latex** en masse—parfait pour les groupes de recherche qui reçoivent des dizaines de manuscrits chaque jour. +Ce petit changement vous permet de **convertir word en style txt** tout en conservant la syntaxe Markdown que vous adorez. --- ## Conclusion -Nous avons couvert **how to export LaTeX from Word** étape par étape, démontré **how to save txt** les fichiers qui conservent chaque équation Office Math, et même montré comment **convert word equations latex** sans perdre en fidélité. +Nous avons parcouru une réponse complète, prête pour la production, à **comment exporter du latex** depuis un document Word, tout en vous montrant comment **convertir word en txt**, **convertir word en texte brut**, **enregistrer docx en txt**, et **comment préserver les tableaux**. Les points clés sont : + +- Charger le DOCX avec `Aspose.Words.Document`. +- Définir `TxtSaveOptions.OfficeMathExportMode = LaTeX` et `PreserveTableLayout = true`. +- Appeler `doc.Save(outputPath, options)` pour obtenir un fichier texte brut riche en LaTeX. -Avec seulement quelques lignes de C# et la puissante bibliothèque Aspose.Words, vous pouvez transformer n’importe quel .docx en texte prêt pour LaTeX, prêt à être intégré dans des articles scientifiques, des manuels ou des pipelines de publication automatisés. +Essayez-le sur vos propres fichiers, jouez avec les réglages d’encodage, et n’hésitez pas à traiter par lots des dossiers entiers. Si vous rencontrez des cas particuliers — tableaux imbriqués, caractères exotiques, ou versions plus anciennes d’Aspose — revenez aux sections “Conseils” et “Pièges” pour des solutions rapides. -**Prochaines étapes ?** Essayez d’alimenter le `.txt` généré (ou renommez‑le en `.tex`) dans `pdflatex` ou `xelatex` pour produire un PDF, ou explorez l’option `SaveFormat.LaTeX` pour un fichier `.tex` direct. Si vous devez **save docx as txt** tout en préservant le formatage, expérimentez avec `PreserveTableLayout` et la gestion personnalisée des sauts de ligne. +Prêt pour l’étape suivante ? Essayez de convertir le même DOCX en Markdown, ou alimentez le `.txt` généré dans un générateur de site statique qui rend le LaTeX sur le web. Les possibilités sont infinies, et vous disposez maintenant d’une base solide pour tout workflow **convertir word en txt**. -Des questions sur les cas limites, les licences ou les ajustements de performance ? Laissez un commentaire ci‑dessous—bon codage ! +Bon codage, et que votre LaTeX compile toujours du premier coup ! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/french/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/french/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..bb42e37c91 --- /dev/null +++ b/words/french/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-01 +description: Enregistrez un document Word au format PDF avec Aspose.Words en C#. Apprenez + à convertir des fichiers docx en PDF, à détecter les polices manquantes et à gérer + efficacement les avertissements de substitution de polices. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: fr +og_description: Enregistrez Word au format PDF avec Aspose.Words. Ce tutoriel étape + par étape montre comment convertir un docx en PDF et détecter les polices manquantes. +og_title: Enregistrer Word en PDF avec Aspose.Words – Guide complet +tags: +- Aspose.Words +- C# +- PDF conversion +title: Enregistrer Word en PDF avec Aspose.Words – Guide complet +url: /fr/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enregistrer Word en PDF avec Aspose.Words – Guide complet + +Vous avez déjà eu besoin d'**enregistrer Word en PDF** à la volée et vous vous êtes demandé si une police pourrait manquer en cours de route ? Vous n'êtes pas seul—les développeurs sont constamment confrontés aux maux de tête liés aux polices manquantes lors de la conversion de documents. Dans ce guide, nous parcourrons une solution pratique qui non seulement **convertit docx en pdf** mais aussi **détecte les polices manquantes** en utilisant les avertissements de substitution de police d'Aspose.Words. + +Nous couvrirons tout, de la configuration du collecteur d'avertissements à l'interprétation du résultat, afin qu'à la fin vous sachiez exactement comment **enregistrer Word en PDF** sans surprise. Aucun outil externe, aucun paramètre obscur—juste du code C# propre que vous pouvez intégrer dans n'importe quel projet .NET. + +## Ce dont vous avez besoin + +- **Aspose.Words for .NET** (dernière version, par ex., 24.10) – vous pouvez l'obtenir via NuGet (`Install-Package Aspose.Words`). +- Un environnement de développement .NET (Visual Studio, Rider ou VS Code fonctionne parfaitement). +- Un fichier DOCX d'exemple qui peut contenir des polices non installées sur la machine cible. + +C'est tout. Si vous avez ces bases, nous sommes prêts à plonger. + +## Enregistrer Word en PDF – Vue d'ensemble étape par étape + +Voici le programme complet et exécutable. N'hésitez pas à le copier‑coller dans un projet d'application console et à appuyer sur **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Astuce :** Remplacez `YOUR_DIRECTORY` par un chemin absolu ou utilisez `Path.Combine(Environment.CurrentDirectory, "input.docx")` pour une approche relative et plus sûre. + +### Pourquoi nous utilisons un rappel d'avertissement + +Aspose.Words substitue silencieusement les polices manquantes par une police de secours (généralement Arial). Sans rappel, vous ne sauriez jamais que la substitution a eu lieu, ce qui peut entraîner des problèmes de mise en page dans le PDF résultant. En branchant `IWarningCallback`, nous obtenons une liste claire et programmatique de chaque événement de police manquante—parfait pour la journalisation ou la notification des utilisateurs finaux. + +### Détecter les polices manquantes – Ce qu'il faut rechercher + +Lorsque vous exécutez le programme, toute police manquante générera une ligne de console similaire à : + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Si la liste est vide, félicitations—l'**enregistrement de Word en PDF** a réussi avec toutes les polices originales intactes. + +## Convertir Docx en PDF – Personnaliser la sortie + +Parfois vous avez besoin d'une version PDF spécifique, d'une qualité d'image ou d'un niveau de conformité. Aspose.Words vous permet d'ajuster l'objet `PdfSaveOptions` avant d'appeler `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Pourquoi c'est important :** Si vous générez des PDF pour des archives légales, définir `PdfA1b` garantit que le fichier respecte des normes strictes. La même conversion respecte toujours notre rappel d'avertissement, vous pourrez donc toujours **détecter les polices manquantes**. + +## Substitution de police Aspose Words – Gestion des cas limites + +### Scénario 1 : Plusieurs polices manquantes + +If your source document uses several custom fonts, the warning collector will contain one entry per font. You can aggregate them: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scénario 2 : Fournir un répertoire de polices de secours + +Aspose.Words can search additional folders for fonts. Set the `FontsFolder` property on `FontSettings` before loading the document: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +La bibliothèque essaiera d'abord votre dossier personnalisé, réduisant ainsi le risque de substitution indésirable. + +### Scénario 3 : Ignorer les substitutions + +If you prefer the conversion to fail when a font is missing (instead of silently substituting), throw an exception inside the callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Cela vous oblige à résoudre la police manquante avant de poursuivre—utile dans les pipelines CI où les échecs silencieux sont inacceptables. + +## Exemple complet de bout en bout + +Putting everything together, here’s a compact version that demonstrates **how to convert Word to PDF**, sets custom PDF options, and logs any font issues: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Expected console output** (if Calibri is missing): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Si aucune alerte n'apparaît, votre opération d'**enregistrement de Word en PDF** a utilisé exactement les mêmes polices que le DOCX source. + +## Résumé visuel + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Texte alternatif de l'image :* **enregistrement de Word en PDF** workflow montrant le chargement, la collecte d'avertissements et la sortie PDF. + +## Questions fréquentes & réponses + +| Question | Réponse | +|----------|--------| +| **Ai-je besoin d'une licence pour Aspose.Words ?** | Une licence d'évaluation gratuite suffit pour les tests, mais en production une licence payante est requise pour supprimer le filigrane d'évaluation. | +| **Cela fonctionnera-t-il sur .NET Core / .NET 6+ ?** | Absolument—Aspose.Words cible .NET Standard 2.0, donc tout runtime .NET récent est compatible. | +| **Puis-je convertir plusieurs fichiers DOCX dans une boucle ?** | Oui, il suffit d'instancier un nouveau `Document` pour chaque fichier et de réutiliser le même `WarningInfoCollector` si vous souhaitez des résultats agrégés. | +| **Que se passe-t-il si le dossier de sortie n'existe pas ?** | `Document.Save` lèvera `DirectoryNotFoundException`. Créez le dossier d'abord ou utilisez `Directory.CreateDirectory`. | +| **Existe-t-il un moyen d'incorporer les polices manquantes dans le PDF ?** | Aspose.Words peut incorporer les polices automatiquement si elles sont disponibles sur la machine ; définissez `PdfSaveOptions.EmbedFullFonts = true`. | + +## Conclusion + +Vous disposez maintenant d'un modèle solide et prêt pour la production afin d'**enregistrer Word en PDF** tout en **détectant les polices manquantes** et en gérant les scénarios de **substitution de police Aspose.Words**. En attachant un rappel d'avertissement, en personnalisant les dossiers de polices, et éventuellement en ajustant `PdfSaveOptions`, vous pouvez de manière fiable **convertir docx en pdf** et tenir vos utilisateurs informés de tout problème de police pouvant affecter la fidélité de la mise en page. + +Prêt pour l'étape suivante ? Essayez de générer des PDF à partir de plusieurs documents en parallèle, ou explorez l'ajout de filigranes et de signatures numériques—les deux sont des extensions simples du code que vous venez de maîtriser. Bon codage, et que vos PDF ressemblent toujours exactement à ce que vous attendez ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-loadoptions/_index.md b/words/french/net/programming-with-loadoptions/_index.md index bfddfc6674..8aa911a949 100644 --- a/words/french/net/programming-with-loadoptions/_index.md +++ b/words/french/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Dans ces tutoriels, vous apprendrez à utiliser LoadOptions pour charger des doc | [Comment récupérer un docx – définir le mode de récupération et ouvrir des fichiers Word corrompus](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Apprenez à activer le mode de récupération et à ouvrir des fichiers Word corrompus avec Aspose.Words pour .NET. | | [Comment utiliser LoadOptions dans Aspose.Words – Guide complet](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Apprenez à exploiter pleinement LoadOptions avec Aspose.Words grâce à ce guide complet, étape par étape. | | [Récupérer un document corrompu en C# – Définir le mode de récupération et inviter l'utilisateur](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Apprenez à récupérer un document Word corrompu en C# en configurant le mode de récupération et en demandant à l'utilisateur. | +| [Récupérer un docx corrompu – Guide complet pour charger des fichiers Word endommagés en C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Apprenez à charger et réparer des fichiers DOCX endommagés en C# avec Aspose.Words grâce à ce guide complet. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/french/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..02af0418c8 --- /dev/null +++ b/words/french/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Récupérez rapidement les fichiers docx corrompus avec Aspose.Words. Apprenez + à définir le mode de récupération, à charger les docx en toute sécurité et à lire + les fichiers Word endommagés en quelques étapes seulement. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: fr +og_description: Récupérez les fichiers docx corrompus en C#. Activez le mode de récupération, + chargez le docx en toute sécurité et lisez les fichiers Word endommagés avec Aspose.Words. +og_title: Récupérer un docx corrompu – Guide rapide C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Récupérer un docx corrompu – Guide complet pour charger des fichiers Word endommagés + en C# +url: /fr/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Récupérer un docx corrompu – Guide rapide C# + +Vous avez déjà essayé d'ouvrir un fichier Word qui refusait de se charger et vous êtes demandé si le contenu était perdu à jamais ? Dans de nombreux projets réels, vous **récupérerez des docx corrompus** sans demander à l'utilisateur de renvoyer la pièce jointe. La bonne nouvelle, c’est qu’Aspose.Words rend cela très simple : il suffit de définir le mode de récupération et de laisser la bibliothèque faire le travail lourd. + +Dans ce tutoriel, nous passerons en revue les étapes exactes pour **récupérer des docx corrompus**, expliquer pourquoi l’option `RecoveryMode.AutoRecover` est le choix le plus sûr, et vous montrer **comment charger des docx** qui pourraient être partiellement endommagés. À la fin, vous serez capable de lire un fichier Word endommagé, d’extraire le texte qui a survécu et même d’enregistrer le format original pour des audits futurs. Aucun outil externe, juste du code C# propre. + +## Ce dont vous avez besoin + +- **Aspose.Words for .NET** (toute version récente ; l’API que nous utilisons fonctionne avec la 23.5 et les suivantes). +- Un environnement de développement .NET (Visual Studio, VS Code ou Rider). +- Le fichier `.docx` corrompu ou partiellement endommagé que vous souhaitez récupérer. + +Aucune permission spéciale, aucune interop COM, et pas besoin d’installer Microsoft Office sur le serveur. Simple, non ? + +## Étape 1 : définir le mode de récupération sur Auto‑Recover + +Lorsqu’un fichier Word est endommagé, le comportement de chargement par défaut lève une exception et interrompt le processus. En configurant un objet `LoadOptions`, vous indiquez à Aspose.Words de **définir le mode de récupération** sur `AutoRecover`, ce qui parcourt le package zip, ignore les parties illisibles et renvoie tout ce qu’il peut reconstituer. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Pourquoi AutoRecover ?** +> Il tente de lire le maximum tout en gardant l’objet document utilisable. Si vous choisissez `RecoveryMode.NoRecovery`, le chargement échouera dès la première corruption, ce qui va à l’encontre du but des scénarios de **récupération de docx corrompus**. + +## Étape 2 : charger le document avec les options configurées + +Maintenant que le mode de récupération est défini, vous pouvez tenter d’ouvrir le fichier en toute sécurité. Remplacez `"YOUR_DIRECTORY/input.docx"` par le chemin réel de votre fichier endommagé. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Si le fichier n’est que partiellement corrompu, l’instance `Document` sera tout de même créée. Vous pouvez vérifier `document.IsStructureValid` plus tard si vous avez besoin d’une validation supplémentaire. + +## Étape 3 : vérifier le format détecté + +Aspose.Words détecte automatiquement le format original (DOC, DOCX, ODT, etc.). Afficher cette valeur vous aide à confirmer que la bibliothèque a correctement reconnu le fichier, ce qui constitue un rapide contrôle de cohérence après une opération de **récupération de docx corrompus**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Sortie typique : + +``` +Loaded with Docx format. +``` + +Même si certaines parties manquaient, la détection du format réussit toujours—un autre avantage pour les flux de travail de **récupération de docx corrompus**. + +## Étape 4 : extraire ce que vous pouvez + +Une fois le document chargé, vous pouvez le traiter comme n’importe quel fichier Word sain. Ci-dessous un exemple compact qui extrait le texte brut et l’écrit dans la console. Cela montre que vous pouvez **lire le contenu d’un fichier Word endommagé** sans plantage. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Si le fichier original contenait des tableaux ou des images corrompus, ils seront simplement omis de la sortie texte. Le reste du document reste intact. + +## Étape 5 : enregistrer une copie propre (optionnel) + +Souvent, vous voudrez fournir à l’utilisateur une nouvelle version propre du fichier après la récupération. Enregistrer avec le même format garantit la compatibilité avec tous les processus en aval. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Vous avez maintenant un fichier **docx endommagé récupéré** que vous pouvez joindre en toute sécurité à un e‑mail ou transmettre à un autre service. + +## Exemple complet fonctionnel + +En assemblant le tout, voici le programme complet, prêt à être exécuté. Collez‑le dans un nouveau projet console, ajustez les chemins de fichiers, et appuyez sur F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Sortie attendue** (en supposant que le fichier contienne un seul paragraphe « Hello world! » et du XML corrompu) : + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Remarquez que le programme ne plante jamais—même si le fichier source était partiellement endommagé. C’est l’essence de la **récupération de docx corrompus** avec Aspose.Words. + +## Questions fréquentes et cas limites + +### Que faire si le fichier est complètement illisible ? + +Même `AutoRecover` a ses limites. Si le conteneur zip lui‑même est corrompu au point d’être irréparable, Aspose.Words lèvera une `CorruptedFileException`. Dans ce cas, vous pourriez avoir besoin d’un outil de réparation zip tiers avant d’essayer à nouveau de **récupérer des docx corrompus**. + +### Puis‑je récupérer d’autres formats (p. ex., `.doc`, `.odt`) ? + +Absolument. Le même `LoadOptions` fonctionne pour tout format supporté par Aspose.Words. Il suffit de changer l’extension du fichier et la bibliothèque détectera automatiquement le format original. Cela signifie que vous pouvez également **récupérer des fichiers similaires à des docx endommagés** comme `.doc` ou `.rtf` avec le même code. + +### Comment gérer de gros documents sans tout charger en mémoire ? + +Pour des fichiers de plusieurs gigaoctets, vous pouvez activer des **options de chargement** comme `LoadOptions.LoadFormat` ou diffuser le document page par page. Cependant, l’algorithme de récupération doit toujours lire l’ensemble du package, donc attendez‑vous à une utilisation mémoire plus élevée pour des fichiers très volumineux et corrompus. + +### Existe‑t‑il un moyen de savoir quelles parties ont été perdues ? + +Après le chargement, vous pouvez inspecter `document.GetChildNodes(NodeType.Any, true)` et comparer le nombre avec une référence attendue. Les tableaux, images ou en‑têtes manquants seront simplement absents de la collection de nœuds. Cela vous permet d’enregistrer exactement ce qui a été **récupéré d’un docx endommagé** et d’informer l’utilisateur. + +## Astuces pro pour une récupération fiable + +- **Valider la taille du fichier d’entrée** avant le chargement ; un fichier de zéro octet échouera toujours. +- **Enregistrer le résultat du `RecoveryMode`** en capturant `DocumentLoadingException` et en stockant le message d’exception ; il contient souvent des indices sur les parties qui ont été ignorées. +- **Exécuter la récupération sur un thread d’arrière‑plan** si vous traitez des téléchargements dans un service web—cela maintient la réactivité de la requête. +- **Combiner avec une somme de contrôle** (p. ex., MD5) pour détecter si le fichier récupéré diffère de l’original ; vous pouvez alors décider de conserver les deux versions. + +## Conclusion + +Nous venons de montrer comment **récupérer des docx corrompus** en C# en **définissant le mode de récupération** sur `AutoRecover`, en chargeant le document en toute sécurité, en extrayant le texte survivant, et éventuellement en enregistrant une copie propre. Cette approche vous permet de **charger des docx** qui autrement lèveraient des exceptions, et vous offre un moyen fiable de **lire le contenu d’un fichier Word endommagé** sans outils externes. + +Prochaines étapes ? Essayez d’échanger `RecoveryMode.AutoRecover` avec `RecoveryMode.NoRecovery` pour voir la différence, ou expérimentez les propriétés de `LoadOptions` qui contrôlent la gestion des mots de passe et la substitution des polices. Vous pourriez également intégrer la routine de récupération dans une API ASP.NET Core qui accepte les téléchargements et renvoie un fichier réparé—parfait pour les pipelines de gestion documentaire d’entreprise. + +Vous avez d’autres questions sur la récupération de documents Word, ou souhaitez voir comment **récupérer des docx endommagés** avec des callbacks personnalisés ? Laissez un commentaire ci‑dessus, et bon codage ! + +![Illustration d’un document récupéré – récupérer un docx corrompu](https://example.com/images/recover-corrupted-docx.png "récupérer un docx corrompu") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-markdownsaveoptions/_index.md b/words/french/net/programming-with-markdownsaveoptions/_index.md index 62774c531e..145b68c310 100644 --- a/words/french/net/programming-with-markdownsaveoptions/_index.md +++ b/words/french/net/programming-with-markdownsaveoptions/_index.md @@ -71,6 +71,8 @@ Apprenez à enregistrer un document Word au format Markdown avec un guide comple ### [Convertir Word en Markdown en C# – Guide complet avec extraction d'images](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) +### [Enregistrer docx en markdown – Exporter les formules Word en LaTeX avec Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/french/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..1c335bb8eb --- /dev/null +++ b/words/french/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-01 +description: Enregistrez un docx au format markdown avec Aspose.Words – apprenez à + convertir Word en markdown, à exporter les équations en LaTeX et à définir la résolution + des images markdown dans un flux de travail fluide. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: fr +og_description: Enregistrez le DOCX au format Markdown avec Aspose.Words. Ce tutoriel + montre comment convertir Word en Markdown, exporter les équations en LaTeX et définir + la résolution des images Markdown. +og_title: Enregistrer le DOCX en Markdown – Guide complet pour exporter les formules + Word en LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Enregistrer le DOCX en Markdown – Exporter les formules Word en LaTeX avec + Aspose.Words +url: /fr/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# enregistrer docx en markdown – Exporter les équations Word en LaTeX avec Aspose.Words + +Vous avez déjà eu besoin de **save docx as markdown** mais vous êtes bloqué sur la façon de garder ces équations Office Math nettes ? Vous n'êtes pas le seul. La plupart des développeurs se heurtent à un mur lorsque la conversion par défaut transforme les équations en images floues, obligeant à les réécrire manuellement en LaTeX. + +Bonne nouvelle : Aspose.Words peut faire le travail lourd pour vous. Dans ce tutoriel, nous allons **convert word to markdown**, dire au moteur d'**export equations to latex**, et même **set markdown image resolution** pour le reste du document. À la fin, vous disposerez d'une seule commande qui génère un fichier `.md` propre avec des mathématiques prêtes pour LaTeX et des images haute résolution. + +## Ce que vous apprendrez + +- Comment charger un `.docx` contenant des objets Office Math. +- Quelles propriétés de `MarkdownSaveOptions` contrôlent **export equations to latex** et **set markdown image resolution**. +- Un extrait complet et exécutable en C# que vous pouvez coller dans n'importe quel projet .NET. +- Conseils pour dépanner les problèmes courants, comme les polices manquantes ou les fonctionnalités d'équations non prises en charge. + +**Prerequisites** : .NET 6+ (ou .NET Framework 4.6+), une licence pour Aspose.Words for .NET, et une connaissance de base du C#. Si vous êtes à l'aise avec la création d'une application console, vous êtes prêt à démarrer. + +--- + +## Étape 1 – Enregistrer docx en markdown : charger votre fichier Word + +La première chose dont nous avons besoin est un objet `Document` qui pointe vers le `.docx` source. Considérez-le comme l'ouverture du livre avant de commencer à copier les chapitres. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Pourquoi c'est important* : Si le document ne contient aucune équation, l'étape **export equations to latex** sera une opération nulle, mais le reste de la conversion s'exécutera tout de même. Cette vérification vous évite de vous demander pourquoi votre Markdown de sortie ne contient pas de blocs LaTeX. + +--- + +## Étape 2 – Configurer l'exportation des équations en LaTeX + +Aspose.Words vous permet de décider comment les Office Math doivent être rendus. Par défaut, il les convertit en images PNG, ce qui explique pourquoi de nombreux tutoriels aboutissent à un fichier markdown granuleux. Passer `OfficeMathExportMode` à `LaTeX` vous fournit des équations propres, prêtes à copier‑coller. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Pourquoi `OfficeMathExportMode.LaTeX` ?* LaTeX est la lingua franca de la publication scientifique. Lorsque vous rendrez plus tard le markdown avec un générateur de site statique ou un notebook Jupyter, les équations apparaîtront nettes à n'importe quel niveau de zoom. + +--- + +## Étape 3 – Définir la résolution des images Markdown (pour le contenu non‑mathématique) + +Même si nous nous concentrons sur les mathématiques, la plupart des documents Word contiennent également des images, des graphiques ou des SVG intégrés. La propriété `ImageResolution` contrôle la façon dont Aspose.Words rasterise ces ressources. Une valeur de **300 DPI** est un bon compromis pour l'écran et l'impression. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Astuce pro* : Si votre markdown ne sera affiché que sur le web, vous pouvez le réduire à 150 DPI pour diminuer la taille du fichier. À l'inverse, pour des PDF prêts à l'impression, augmentez-le à 600 DPI. + +--- + +## Étape 4 – Exécuter la conversion – Convertir les équations Word en LaTeX + +Maintenant que tout est configuré, la conversion réelle se fait en une seule ligne. Aspose.Words effectue le travail lourd en coulisses. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output** : Ouvrez le fichier `.md` généré et vous devriez voir quelque chose comme : + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Remarquez les blocs LaTeX (`$...$` et `$$...$$`) qui remplacent les anciens extraits PNG. L'image en bas reste un PNG, rendu à 300 DPI comme demandé. + +--- + +## Étape 5 – Cas limites courants et comment les gérer + +| Situation | Ce qui se passe | Comment corriger | +|-----------|-----------------|------------------| +| **Missing fonts** (e.g., Cambria Math not installed) | La sortie LaTeX peut contenir des symboles inconnus. | Installez la police manquante sur le serveur ou intégrez‑la dans le document avant la conversion. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words peut revenir à une image malgré le mode `LaTeX`. | Mettez à jour vers la dernière version d'Aspose.Words ; la bibliothèque améliore continuellement la prise en charge des équations. | +| **Large documents** ( > 50 MB ) | La pression mémoire peut provoquer une `OutOfMemoryException`. | Utilisez `LoadOptions` avec `LoadFormat.Docx` et diffusez le fichier, ou divisez le document en sections avant la conversion. | +| **Image size too big** | Le fichier Markdown devient énorme, ralentissant les constructions de sites statiques. | Réduisez `ImageResolution` à 150 DPI pour les scénarios uniquement web (voir Étape 3). | + +--- + +## Étape 6 – Assembler le tout : exemple complet fonctionnel + +Ci-dessous se trouve le programme d'application console *complet* que vous pouvez copier‑coller dans `Program.cs`. Il inclut tous les éléments que nous avons abordés, plus un peu de gestion d'erreurs supplémentaire. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Exécutez le programme (`dotnet run`) et vous obtiendrez un fichier markdown qui **save docx as markdown** tout en préservant chaque équation en LaTeX. Aucun copier‑coller manuel, aucune image raster laide pour les mathématiques. + +--- + +## Conclusion + +Nous avons parcouru l'ensemble du processus de **saving docx as markdown** avec Aspose.Words, du chargement du fichier Word à la configuration de **export equations to latex** et **set markdown image resolution**. L'extrait final est prêt pour la production, et vous pouvez l'intégrer dans n'importe quel projet .NET qui doit **convert word to markdown** à la volée. + +Et ensuite ? Essayez d'alimenter le `.md` généré dans un générateur de site statique comme Hugo ou Jekyll et observez vos équations s'afficher magnifiquement. Si vous devez **convert word math latex** vers d'autres formats (PDF, HTML), remplacez simplement `MarkdownSaveOptions` par `PdfSaveOptions` ou `HtmlSaveOptions` — le même drapeau `OfficeMathExportMode` fonctionne pour tous. + +Vous avez une variante dans votre flux de travail, comme récupérer des fichiers Word depuis Azure Blob storage ou les diffuser depuis une API ? Le même schéma s'applique ; il suffit de remplacer le constructeur `Document` basé sur le système de fichiers par un constructeur basé sur un flux. + +N'hésitez pas à expérimenter, et dites‑nous dans les commentaires comment cette approche a résolu vos problèmes de conversion. Bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-pdfsaveoptions/_index.md b/words/french/net/programming-with-pdfsaveoptions/_index.md index f6dbf2f555..ec1ab30b1b 100644 --- a/words/french/net/programming-with-pdfsaveoptions/_index.md +++ b/words/french/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ Que vous souhaitiez convertir des documents Word en PDF pour une distribution en | [Créer un PDF accessible en C# – Tutoriel d'accessibilité PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Apprenez à générer des PDF accessibles conformes aux normes d'accessibilité avec Aspose.Words pour .NET en C#. | | [Créer un PDF accessible à partir de Word – Guide complet](./create-accessible-pdf-from-word-complete-guide/) | Apprenez à créer un PDF accessible depuis un document Word avec Aspose.Words pour .NET grâce à ce guide complet. | | [Créer un PDF accessible – Guide étape par étape pour la conformité PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Apprenez à créer des PDF accessibles conformes aux normes PDF/UA grâce à ce guide détaillé étape par étape. | +| [Enregistrer un document au format PDF avec Aspose.Words – Guide complet C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Apprenez à enregistrer un document Word au format PDF en C# avec Aspose.Words grâce à ce guide complet étape par étape. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/french/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..de655c4ba1 --- /dev/null +++ b/words/french/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-05-01 +description: Apprenez à enregistrer un document au format PDF à l'aide d'Aspose.Words + en C#. Le tutoriel couvre également la conversion de Word en PDF, l'exportation + de formules LaTeX et la gestion des polices manquantes. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: fr +og_description: Enregistrez facilement un document au format PDF avec Aspose.Words. + Ce guide montre également comment convertir Word en PDF, exporter les formules LaTeX + et gérer les polices manquantes. +og_title: Enregistrer le document au format PDF avec Aspose.Words – Guide complet + C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Enregistrer le document au format PDF avec Aspose.Words – Guide complet C# +url: /fr/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enregistrer un document au format PDF avec Aspose.Words – Guide complet C# + +Vous vous êtes déjà demandé **comment enregistrer un document au format pdf** directement à partir d'un fichier Word sans perdre les fonctionnalités d'accessibilité ? Vous n'êtes pas le seul — les développeurs demandent constamment un moyen fiable de convertir Word en PDF tout en préservant les équations mathématiques et en gérant les polices manquantes de façon élégante. + +Dans ce tutoriel, nous parcourrons une solution étape par étape qui non seulement **enregistre un document au format pdf**, mais montre également **convertir word en pdf**, **exporter les mathématiques en latex**, et **gérer les polices manquantes** en utilisant la dernière version d’Aspose.Words pour .NET. À la fin, vous disposerez d’un programme C# prêt à l’emploi qui génère des fichiers conformes à PDF/UA‑2, parfaits pour les audits d’accessibilité. + +## Ce dont vous avez besoin + +- .NET 6 ou version ultérieure (le code fonctionne également avec .NET Core et .NET Framework) +- Aspose.Words for .NET 25.10 ou plus récent – vous pouvez obtenir un essai gratuit sur le site web d’Aspose +- Un document Word modeste (`input.docx`) contenant au moins une forme flottante et une équation mathématique (pour voir la fonctionnalité d’export‑math‑latex en action) +- Visual Studio 2022 (ou tout IDE de votre choix) + +> **Astuce :** Si vous utilisez un pipeline CI/CD, ajoutez le package NuGet Aspose.Words à votre fichier de projet : + +```xml + +``` + +Maintenant, plongeons dans le code. + +## Étape 1 : Charger le document source avec récupération automatique + +Lorsque vous traitez des fichiers Word du monde réel, vous pouvez rencontrer des sections corrompues ou des ressources manquantes. Activer la récupération automatique garantit que le processus de chargement ne lève jamais d’exception. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Pourquoi c’est important :** +`RecoveryMode.AutoRecover` protège votre pipeline des plantages sur des entrées malformées, ce qui est particulièrement pratique lorsque vous **convertissez word en pdf** en masse. + +## Étape 2 : Configurer les options d’enregistrement PDF pour une accessibilité complète + +PDF/UA‑2 est la norme ISO pour les PDF accessibles. En configurant quelques indicateurs, nous obtenons un fichier que les lecteurs d’écran peuvent parcourir, et nous nous assurons également que les équations mathématiques sont exportées en LaTeX caché. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Points clés :** + +- **ExportFloatingShapesAsInlineTag** – garantit que le PDF résultant respecte la mise en page originale tout en restant sémantiquement correct. +- **OfficeMathExportMode.LaTeX** – répond à l’exigence **exporter les mathématiques en latex**, permettant aux outils en aval d’extraire les équations si nécessaire. + +## Étape 3 : Capturer les avertissements (par ex., polices manquantes) + +Les polices manquantes sont un problème fréquent lors de la conversion de documents. Aspose.Words peut signaler ces problèmes via un `WarningCallback`. Nous les collecterons afin que vous puissiez les consigner ou les traiter ultérieurement. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Pourquoi cela vous importe :** +Si la source utilise une police qui n’est pas installée sur le serveur, le PDF reviendra à une police par défaut, ce qui peut rompre la mise en page. En **gérant les polices manquantes**, nous pouvons alerter l’utilisateur ou incorporer un substitut. + +## Étape 4 : Enregistrer le document en PDF accessible + +Voici le moment de vérité — effectuer réellement la conversion. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Si tout se passe bien, vous obtiendrez un fichier PDF/UA‑2 contenant du LaTeX caché pour chaque équation et un balisage approprié pour les formes flottantes. + +## Étape 5 : Examiner les avertissements capturés (optionnel mais recommandé) + +Après l’opération d’enregistrement, vous pouvez parcourir les avertissements collectés et les consigner. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Un exemple de sortie pourrait ressembler à : + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Voir ces messages tôt vous aide à **gérer les polices manquantes** avant qu’elles n’affectent les utilisateurs finaux. + +## Exemple complet fonctionnel + +En réunissant tous les éléments, voici le programme complet, prêt à l’exécution. Remplacez les chemins factices par les vôtres. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Résultat attendu :** +- `output.pdf` est conforme à PDF/UA‑2. +- Toutes les formes flottantes sont balisées comme figures en ligne. +- Chaque objet Office Math apparaît comme du LaTeX caché (visible lorsque vous inspectez la structure du PDF). +- Tout problème lié aux polices est affiché dans la console, vous donnant la possibilité de **gérer les polices manquantes** avant de diffuser le fichier. + +![Diagramme montrant le flux de Word → Aspose.Words → PDF accessible (enregistrement du document en pdf)](conversion-diagram.png "Diagramme du flux pour enregistrer le document en pdf") + +*Texte alternatif de l'image :* **Diagramme montrant comment enregistrer le document en pdf avec Aspose.Words** + +## Questions fréquentes & cas particuliers + +### Que faire si j’utilise une version plus ancienne d’Aspose.Words ? + +Le drapeau `OfficeMathExportMode.LaTeX` a été introduit dans la version 25.10. Pour les versions antérieures, vous pouvez toujours **convertir word en pdf**, mais les mathématiques seront rasterisées au lieu d’être exportées en LaTeX. Mettez à jour pour une accessibilité optimale. + +### Puis-je incorporer des polices personnalisées pour éviter le repli ? + +Oui. Définissez `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` avant d’appeler `Save`. Cela aide également à **gérer les polices manquantes** en forçant le PDF à contenir les glyphes requis. + +### Comment vérifier la conformité PDF/UA‑2 ? + +Ouvrez le fichier dans Adobe Acrobat Pro → « Print Production » → « Preflight ». Choisissez le profil « PDF/A‑2b » ou « PDF/UA‑2 » ; Acrobat signalera toute violation. + +### Et les fichiers Word protégés par mot de passe ? + +Chargez le document avec un `LoadOptions` incluant `Password`. Exemple : + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +## Conclusion + +Nous avons couvert tout ce dont vous avez besoin pour **enregistrer un document au format pdf** avec Aspose.Words en C#. Le tutoriel a également montré comment **convertir word en pdf**, **exporter les mathématiques en latex**, et **gérer les polices manquantes** — le tout en produisant un fichier PDF/UA‑2 accessible. + +Testez le code, expérimentez avec différents `PdfSaveOptions` (par ex., compression d’image, PDF/A‑2b), et intégrez‑le à votre service de traitement de documents. Si vous devez aller plus loin, envisagez d’explorer la bibliothèque spécifique PDF d’Aspose pour le post‑traitement ou les signatures numériques. + +Vous avez d’autres scénarios à aborder ? N’hésitez pas à laisser un commentaire ou à consulter nos autres guides sur **la manipulation de PDF**, **l’extraction d’images**, et **la conversion par lots**. Bon codage ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-shapes/_index.md b/words/french/net/programming-with-shapes/_index.md index b720ccc1b9..08de5a90e0 100644 --- a/words/french/net/programming-with-shapes/_index.md +++ b/words/french/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ En utilisant Aspose.Words pour .NET et en suivant ces tutoriels, vous maîtriser | [Créer une forme rectangulaire dans Word avec C# – Guide étape par étape](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Apprenez à créer une forme rectangulaire dans Word à l'aide d'Aspose.Words pour .NET avec ce guide étape par étape. | | [Tutoriel Ombre de forme Aspose.Words – Ajouter une ombre à une forme Word en C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Apprenez à ajouter une ombre à une forme dans un document Word avec Aspose.Words pour .NET en C# grâce à ce guide étape par étape. | | [Créer un document Word vierge avec une forme de rectangle ombrée – Guide étape par étape](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Apprenez à créer un document Word vierge contenant une forme de rectangle avec ombre à l'aide d'Aspose.Words pour .NET. | +| [Comment déplacer l'ombre dans Aspose.Words – Guide complet C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Apprenez à déplacer l'ombre d'une forme dans un document Word avec Aspose.Words pour .NET grâce à ce guide complet en C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/french/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..58a4430636 --- /dev/null +++ b/words/french/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Comment déplacer l'ombre sur une forme dans Aspose.Words avec C#. Apprenez + à ajouter une ombre à une forme, modifier le flou, régler la transparence et faire + pivoter l'ombre en quelques minutes. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: fr +og_description: Comment déplacer l’ombre sur une forme dans Aspose.Words en C#. Ce + tutoriel vous montre comment ajouter une ombre à une forme, modifier le flou, régler + la transparence et faire pivoter l’ombre. +og_title: Comment déplacer l’ombre dans Aspose.Words – Guide complet C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Comment déplacer l’ombre dans Aspose.Words – Guide complet C# +url: /fr/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment déplacer l'ombre dans Aspose.Words – Guide complet C# + +Vous vous êtes déjà demandé **comment déplacer l'ombre** d’une forme dans un document Word sans ouvrir Word manuellement ? Dans mon travail quotidien, j’ai souvent dû ajuster l’ombre d’une forme de façon programmatique—que ce soit pour un rapport soigné ou un modèle dynamique. Bonne nouvelle : avec Aspose.Words, vous pouvez le faire en quelques lignes, et vous apprendrez également **ajouter une ombre à la forme**, **comment modifier le flou**, **comment définir la transparence**, et **comment faire pivoter l'ombre** en une seule passe. + +Dans ce tutoriel, nous allons parcourir un scénario réel : charger un DOCX existant contenant déjà une forme, ajuster la position, la douceur, l’opacité et la direction de l’ombre, puis enregistrer le résultat. À la fin, vous disposerez d’un extrait réutilisable à intégrer dans n’importe quel projet .NET, et vous comprendrez l’importance de chaque propriété. + +## Prérequis – Ce dont vous avez besoin avant de commencer + +- **Aspose.Words for .NET** (version 23.12 ou ultérieure). Vous pouvez l’obtenir via NuGet avec `Install-Package Aspose.Words`. +- Un environnement de développement .NET 6+ (Visual Studio, VS Code, Rider—au choix). +- Un fichier Word d’entrée (`input.docx`) contenant déjà au moins une forme (un rectangle, un cercle ou une image suffit). +- Une connaissance de base de la syntaxe C#—rien de compliqué. + +Si l’un de ces éléments vous manque, faites une pause et installez la bibliothèque ; le reste du guide suppose que le package est déjà référencé. + +## Étape 1 : Charger le document et récupérer la forme cible – **Comment déplacer l'ombre** commence ici + +La première chose à faire est de charger le document source et de localiser la forme que nous voulons modifier. Aspose.Words traite chaque objet (paragraphes, tableaux, formes) comme un nœud d’un arbre, ce qui permet de l’interroger directement. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Pourquoi c’est important :** Charger le document une seule fois et réutiliser la même instance `Document` est efficace. L’appel `GetChild` est sûr car il renvoie `null` si l’indice est hors limites, ce qui nous permet de gérer les formes manquantes sans problème. + +## Étape 2 : Ajuster le rayon de flou – Maîtriser **Comment modifier le flou** + +Une ombre douce paraît professionnelle, tandis qu’un bord dur peut sembler bon marché. La propriété `BlurRadius` contrôle la douceur en points (1 pt ≈ 1/72 pouce). Augmentons-la à 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Astuce pro :** Le flou par défaut est de 0,5 pt. Tout ce qui dépasse 5 pt devient généralement perceptible, mais attention à ne pas exagérer — une valeur trop élevée peut donner l’impression que la forme est détachée de la page. + +## Étape 3 : Définir la transparence – La réponse à **Comment définir la transparence** + +La transparence détermine le degré de visibilité de l’ombre. Une valeur de `0` signifie totalement opaque ; `1` signifie complètement invisible. Pour un effet subtil, nous utiliserons `0.3` (30 % transparent). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Pourquoi cela peut vous intéresser :** Si la forme est sombre, une ombre totalement opaque peut masquer le texte sous‑jacent. Ajuster la transparence garde le document lisible tout en apportant de la profondeur. + +## Étape 4 : Déplacer l'ombre – Le cœur de **Comment déplacer l'ombre** + +La propriété `Distance` définit la distance entre l’ombre et la forme, mesurée en points. Une distance plus grande décale davantage l’ombre, créant un effet plus dramatique. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Et si vous avez besoin d’un léger décalage ?** Fixer `Distance` à `0` placera l’ombre directement derrière la forme, ce qui peut être utile pour des effets d’embossage. + +## Étape 5 : Faire pivoter la source de lumière – Résoudre **Comment faire pivoter l'ombre** + +Les ombres ne sont pas toujours verticales ; elles suivent l’angle de la source lumineuse. La propriété `Angle` (en degrés) fait pivoter l’ombre autour de la forme. Inclinez‑la de 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Expérience rapide :** Essayez `90` pour une ombre à droite ou `-30` pour une ombre inclinée à gauche. Le changement visuel est immédiat. + +## Étape 6 : Enregistrer le document – Voir le résultat de **Ajouter une ombre à la forme** + +Maintenant que nous avons ajusté l’ombre, nous écrivons le document sur le disque. Vous pouvez écraser le fichier original ou créer un nouveau ; l’exemple utilise un nouveau fichier de sortie. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Résultat attendu :** Ouvrez `output.docx`. L’ombre de la forme apparaîtra plus douce, légèrement décalée, semi‑transparente et inclinée à 45°. Si vous la comparez côte à côte avec `input.docx`, la différence est flagrante. + +### Exemple complet (prêt à copier‑coller) + +Voici le programme complet en un seul bloc. Collez‑le dans un nouveau projet console, remplacez `YOUR_DIRECTORY` par un chemin de dossier réel, puis exécutez. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Questions fréquentes & cas particuliers + +### Et si le document contient plusieurs formes ? + +Vous pouvez parcourir toutes les formes : + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Puis‑je ajouter une ombre à une forme qui n’en a pas encore ? + +Absolument. L’objet `ShadowFormat` existe toujours ; il suffit de l’activer : + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Cela fonctionne‑t‑il avec les images et les SmartArt ? + +Oui. Tout nœud dérivé de `Shape`—y compris les images, graphiques et SmartArt—expose `ShadowFormat`. Les mêmes propriétés s’appliquent. + +### Comment contrôler la couleur de l’ombre ? + +Utilisez la propriété `Color` : + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Problèmes de compatibilité ? + +Aspose.Words 23.12+ prend en charge .NET 6, .NET Core 3.1 et .NET Framework 4.6.2+. L’API présentée est stable sur ces versions. + +## Conclusion + +Nous venons de couvrir **comment déplacer l'ombre** d’une forme avec Aspose.Words, et nous avons également démontré **ajouter une ombre à la forme**, **comment modifier le flou**, **comment définir la transparence**, et **comment faire pivoter l'ombre**. L’exemple complet et exécutable vous permet de modifier l’ombre de n’importe quelle forme en quelques secondes, donnant à vos documents un aspect poli et professionnel sans jamais ouvrir Word. + +Prêt pour l’étape suivante ? Essayez de combiner ces ajustements d’ombre avec **la mise en forme conditionnelle**—par exemple, n’appliquer une ombre plus profonde qu’aux titres ou aux graphiques dépassant une certaine taille. Ou explorez les **dégradés de remplissage** pour la forme elle‑même afin de créer un design vraiment accrocheur. + +Si vous rencontrez des difficultés, laissez un commentaire ci‑dessous. Bon codage, et que vos ombres tombent toujours exactement où vous le souhaitez ! + +![Diagramme montrant l’effet du déplacement d’une ombre sur une forme – exemple de déplacement d’ombre](https://example.com/images/shadow-demo.png "exemple de déplacement d’ombre") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/basic-conversions/_index.md b/words/german/net/basic-conversions/_index.md index d527cbf9ad..ab36573ce2 100644 --- a/words/german/net/basic-conversions/_index.md +++ b/words/german/net/basic-conversions/_index.md @@ -25,15 +25,16 @@ | [Konvertieren Sie Docx in RTF](./docx-to-rtf/) | Erfahren Sie in unserer Schritt-für-Schritt-Anleitung, wie Sie DOCX mit Aspose.Words für .NET in RTF konvertieren. Einfache Konvertierung für nahtlose Dokumentenverarbeitung. | | [Word-Datei in PDF konvertieren](./docx-to-pdf/) | Erfahren Sie in unserem Leitfaden, wie Sie Word-Dateien mit Aspose.Words für .NET einfach in PDF konvertieren. Perfekt für Entwickler, die eine schnelle und zuverlässige Dokumentkonvertierung wünschen. | | [Word in PDF konvertieren in C# mit Aspose.Words – Anleitung](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Erfahren Sie, wie Sie Word-Dokumente mit Aspose.Words in C# einfach in PDF konvertieren. | -| [Konvertieren Sie Docx in Byte](./docx-to-byte/) | Erfahren Sie, wie Sie Docx mit Aspose.Words in .NET in ein Byte-Array konvertieren, um eine effiziente Dokumentverarbeitung zu gewährleisten. Schritt-für-Schritt-Anleitung enthalten. | +| [Konvertieren Sie Docx in Byte](./docx-to-byte/) | Erfahren Sie, wie Sie Docx mit Aspose.Words in .NET in ein Byte-Array konvertieren, um eine effiziente Dokumentverarbeitung zu gewährleisten. Schritt‑für‑Schritt‑Anleitung enthalten. | | [Docx in Epub konvertieren](./docx-to-epub/) | Konvertieren Sie DOCX einfach in EPUB mit Aspose.Words für .NET. Folgen Sie unserem Tutorial für die nahtlose Integration in Ihre .NET-Anwendungen. | -| [Konvertieren Sie Docx in Mhtml und senden Sie E-Mails](./docx-to-mhtml-and-sending-email/) | Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie DOCX in MHTML konvertieren und E-Mails mit Aspose.Words für .NET versenden. Steigern Sie Ihre Produktivität durch einfache Automatisierung. | +| [Konvertieren Sie Docx in Mhtml und senden Sie E-Mails](./docx-to-mhtml-and-sending-email/) | Erfahren Sie in dieser Schritt‑für‑Schritt‑Anleitung, wie Sie DOCX in MHTML konvertieren und E-Mails mit Aspose.Words für .NET versenden. Steigern Sie Ihre Produktivität durch einfache Automatisierung. | | [Docx-Datei in Markdown konvertieren](./docx-to-markdown/) | Erfahren Sie, wie Sie DOCX-Dateien mit Aspose.Words für .NET in Markdown konvertieren. Folgen Sie unserer ausführlichen Anleitung für die nahtlose Integration in Ihre .NET-Anwendungen. | -| [Konvertieren Sie Docx in Txt](./docx-to-txt/) | Konvertieren Sie DOCX mit Aspose.Words für .NET in TXT mit unserer Schritt-für-Schritt-Anleitung. Lernen Sie, Dokumente effizient und mühelos zu transformieren. | +| [Konvertieren Sie Docx in Txt](./docx-to-txt/) | Konvertieren Sie DOCX mit Aspose.Words für .NET in TXT mit unserer Schritt‑für‑Schritt‑Anleitung. Lernen Sie, Dokumente effizient und mühelos zu transformieren. | | [Textdatei in Word-Dokument konvertieren](./txt-to-docx/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET Textdateien in Word-Dokumente konvertieren. Verwalten Sie Dokumentkonvertierungen effizient mit unserem umfassenden Leitfaden. | | [PDF als JPEG speichern](./pdf-to-jpeg/) | Konvertieren Sie PDFs mühelos in JPEGs mit Aspose.Words für .NET. Folgen Sie unserer ausführlichen Anleitung mit Beispielen und FAQs. Ideal für Entwickler und Enthusiasten. | -| [PDF im Word-Format (Docx) speichern](./pdf-to-docx/) | Erfahren Sie in dieser detaillierten Schritt-für-Schritt-Anleitung, wie Sie mit Aspose.Words für .NET ein PDF in ein Word-Dokument (Docx) konvertieren. Perfekt für Entwickler. | +| [PDF im Word-Format (Docx) speichern](./pdf-to-docx/) | Erfahren Sie in dieser detaillierten Schritt‑für‑Schritt‑Anleitung, wie Sie mit Aspose.Words für .NET ein PDF in ein Word-Dokument (Docx) konvertieren. Perfekt für Entwickler. | | [Wie man LaTeX aus Word exportiert – Schritt‑für‑Schritt‑Anleitung](./how-to-export-latex-from-word-step-by-step-guide/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET LaTeX aus Word-Dokumenten exportieren – detaillierte Anleitung mit Codebeispielen. | +| [Word als PDF speichern mit Aspose.Words – Vollständige Anleitung](./save-word-as-pdf-with-aspose-words-complete-guide/) | Erfahren Sie, wie Sie Word-Dokumente mit Aspose.Words vollständig als PDF speichern – Schritt‑für‑Schritt‑Anleitung. | | [Word als PDF speichern mit Aspose.Words – Vollständige C#‑Anleitung](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Erfahren Sie, wie Sie Word-Dokumente mit Aspose.Words in C# einfach als PDF speichern – Schritt‑für‑Schritt‑Anleitung. | | [Docx als PDF speichern mit Aspose.Words – Vollständige C#‑Anleitung](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Erfahren Sie, wie Sie DOCX‑Dateien mit Aspose.Words in C# einfach als PDF speichern – Schritt‑für‑Schritt‑Anleitung. | diff --git a/words/german/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/german/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index e657522059..6c7edcea41 100644 --- a/words/german/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/german/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Wie man LaTeX aus Word mit Aspose.Words exportiert – lernen Sie, Word - in LaTeX zu konvertieren, docx als txt zu speichern und Gleichungen im Klartext - zu verarbeiten. +date: 2026-05-01 +description: Erfahren Sie, wie Sie LaTeX aus einer Word‑Datei exportieren, Word in txt + konvertieren und Tabellen mit Aspose.Words in C# beibehalten. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: de -og_description: Wie man LaTeX aus Word mit Aspose.Words exportiert. Diese Anleitung - zeigt, wie man Word in LaTeX konvertiert, docx als txt speichert und Gleichungen - intakt hält. -og_title: Wie man LaTeX aus Word exportiert – Schnelles C#‑Tutorial +og_description: Entdecken Sie, wie Sie LaTeX aus Word exportieren, Word in Klartext + konvertieren und das Tabellenlayout mit Aspose.Words unverändert beibehalten. +og_title: Wie man LaTeX aus Word exportiert – Vollständiges C#‑Tutorial tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Wie man LaTeX aus Word exportiert – Schritt‑für‑Schritt‑Anleitung url: /de/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,178 +26,215 @@ url: /de/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Wie man LaTeX aus Word exportiert – Schritt‑für‑Schritt‑Anleitung +# Wie man LaTeX aus Word exportiert – Vollständiges C#‑Tutorial -Haben Sie sich jemals gefragt, **wie man LaTeX aus Word** exportiert, ohne dass dabei knifflige Office‑Math‑Formeln verloren gehen? Sie sind nicht allein. Viele Entwickler stoßen an ihre Grenzen, wenn sie *Word zu LaTeX* für wissenschaftliche Arbeiten, technische Berichte oder automatisierte Veröffentlichungs‑Pipelines konvertieren wollen. +Haben Sie sich jemals gefragt, **wie man LaTeX** aus einem Word‑Dokument exportiert, ohne dabei mathematische Formeln zu verlieren? Sie sind nicht allein. Viele Entwickler müssen ein .docx, das Office‑Math enthält, in sauberes LaTeX umwandeln und gleichzeitig **Word in txt konvertieren** für die Weiterverarbeitung. In diesem Leitfaden führen wir Sie durch eine praktische, sofort einsetzbare Lösung, die **Tabellen erhält**, Ihnen eine Nur‑Text‑Datei liefert und das LaTeX‑Markup genau dort belässt, wo Sie es benötigen. -In diesem Tutorial führen wir Sie durch ein komplettes, sofort ausführbares C#‑Beispiel, das **zeigt, wie man LaTeX exportiert** mit Aspose.Words, erklärt **wie man txt**‑Dateien mit LaTeX‑Markup speichert und sogar die Feinheiten von **convert word equations latex** behandelt, sodass nichts bei der Übersetzung verloren geht. +Wir behandeln alles vom Laden der Quelldatei bis zum Anpassen von `TxtSaveOptions`, sodass die Ausgabe sowohl menschen‑lesbar als auch maschinen‑freundlich ist. Am Ende können Sie **docx als txt speichern**, **Word in Nur‑Text konvertieren** und wissen **wie man Tabellen erhält** während des Exports. Keine externen Skripte, kein manuelles Kopieren‑Einfügen — nur reiner C#‑Code, den Sie in jedes .NET‑Projekt einbinden können. -> **Pro‑Tipp:** Der gleiche Ansatz funktioniert für jede .docx‑Datei – einfach den Code auf einen anderen Dateipfad zeigen. +## Was Sie benötigen + +- **Aspose.Words for .NET** (neueste Version, 2024.x oder neuer). Das NuGet‑Paket heißt `Aspose.Words`. +- Eine .NET‑Entwicklungsumgebung (Visual Studio, VS Code, Rider — jede ist geeignet). +- Eine Word‑Datei (`.docx`), die Office‑Math‑Formeln und mindestens eine Tabelle enthält (damit wir die tabellen‑erhaltende Magie sehen können). + +Das ist alles. Wenn Sie das bereits haben, lesen Sie weiter; andernfalls holen Sie sich das NuGet‑Paket und ein Beispiel‑DOCX, bevor wir tiefer einsteigen. --- -## Was Sie benötigen +## Wie man LaTeX aus einem Word‑Dokument exportiert -Bevor wir starten, stellen Sie sicher, dass Sie die folgenden Voraussetzungen erfüllen: +Im Folgenden finden Sie das Herzstück des Tutorials — drei kompakte Schritte, die die Frage **wie man LaTeX exportiert** beantworten und gleichzeitig die sekundären Ziele **Word in txt konvertieren**, **Word in Nur‑Text konvertieren**, **docx als txt speichern** und **wie man Tabellen erhält** abdecken. -| Voraussetzung | Warum es wichtig ist | -|--------------|----------------------| -| **.NET 6.0+** (oder .NET Framework 4.6+) | Aspose.Words richtet sich an moderne .NET‑Laufzeiten. | -| **Aspose.Words for .NET** NuGet‑Paket (`Aspose.Words`) | Die Bibliothek übernimmt das schwere Heben beim Parsen von Word und Erzeugen von LaTeX. | -| **Eine Beispiel‑.docx** mit mindestens einer Office‑Math‑Formel | Um die LaTeX‑Konvertierung in Aktion zu sehen. | -| **Visual Studio 2022** (oder jede andere IDE Ihrer Wahl) | Macht das Debuggen und Ausführen des Beispiels trivial. | +### Schritt 1: Laden der DOCX‑Datei -Falls Sie das NuGet‑Paket noch nicht installiert haben, führen Sie aus: +Zuerst müssen wir das Word‑Dokument in ein `Aspose.Words.Document`‑Objekt einlesen. Dieser Schritt ist identisch, egal ob Sie später **Word in txt konvertieren** oder **docx als txt speichern**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -Das war’s – keine zusätzlichen DLLs, kein COM‑Interop, nur eine saubere verwaltete Bibliothek. +> **Warum das wichtig ist:** Das Laden der Datei erzeugt eine In‑Memory‑Repräsentation aller Word‑Elemente — Absätze, Tabellen und Office‑Math‑Objekte. Ohne dieses Objekt können Sie Export‑Optionen nicht manipulieren. ---- +### Schritt 2: `TxtSaveOptions` für LaTeX und Tabellenlayout konfigurieren -## Wie man LaTeX aus Word exportiert – Überblick +Die Klasse `TxtSaveOptions` ermöglicht die genaue Steuerung, wie die Nur‑Text‑Datei erzeugt wird. Zwei Eigenschaften sind für unser Szenario entscheidend: -Im Folgenden das große Ganze, das wir erreichen werden: +| Eigenschaft | Was es tut | Warum Sie es benötigen | +|-------------|------------|------------------------| +| `OfficeMathExportMode` | Bestimmt, wie Office‑Math gerendert wird. Wird sie auf `LaTeX` gesetzt, konvertiert das Gleichungen in LaTeX‑Syntax. | Das ist der Kern von **wie man LaTeX exportiert**. | +| `PreserveTableLayout` | Wenn `true`, fügt Aspose Leerzeichen hinzu, sodass Tabellen ein raster‑ähnliches Aussehen behalten. | Das erfüllt **wie man Tabellen erhält**, während Sie **Word in txt konvertieren**. | -1. **Laden** des Quell‑Word‑Dokuments (`.docx`). -2. **Konfigurieren** von `TxtSaveOptions`, sodass alle Office‑Math‑Objekte als LaTeX‑Code ausgegeben werden. -3. **Speichern** des Dokuments als Klartext‑Datei (`.txt`), die Sie direkt in jeden LaTeX‑Compiler einspeisen können. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Wie man LaTeX aus Word exportiert Beispiel](image.png "Wie man LaTeX aus Word exportiert") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro‑Tipp:** Wenn Sie nur das rohe LaTeX ohne Tabellenformatierung benötigen, setzen Sie `PreserveTableLayout` auf `false`. Die Datei wird kleiner, aber Sie verlieren die visuelle Tabellen‑Hinweis. -## Schritt 1: Das Word‑Dokument laden +### Schritt 3: Dokument als Nur‑Text speichern -Zuerst öffnen wir die .docx, die Sie konvertieren möchten. Die Klasse `Document` abstrahiert das zugrundeliegende XML und bietet Ihnen ein benutzerfreundliches Objektmodell. +Jetzt schreiben wir das Dokument mit den zuvor definierten Optionen in eine `.txt`‑Datei. Diese eine Zeile erledigt **Word in Nur‑Text konvertieren**, **docx als txt speichern** und natürlich **wie man LaTeX exportiert** gleichzeitig. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Warum das wichtig ist:** -Das frühe Laden der Datei ermöglicht es uns, ihren Inhalt zu inspizieren (z. B. die Anzahl der Formeln), bevor wir entscheiden, wie wir sie serialisieren. Ist die Datei beschädigt, wirft `Document` eine klare Ausnahme, sodass Sie nicht später rätselhafte Ausgaben erhalten. +Nachdem der Aufruf abgeschlossen ist, öffnen Sie `output.txt`. Sie sehen: ---- +- LaTeX‑Snippets wie `\frac{a}{b}` für jede Office‑Math‑Gleichung. +- Tabellen, dargestellt mit `|`‑ und `-`‑Zeichen, wobei die Spaltenausrichtung erhalten bleibt. +- Normale Absätze als Nur‑Text, bereit für jeden nachgelagerten Parser. -## Schritt 2: TxtSaveOptions für den LaTeX‑Export konfigurieren +### Vollständiges funktionierendes Beispiel -Die Magie passiert in `TxtSaveOptions`. Durch Setzen von `OfficeMathExportMode` auf `LaTeX` wird jedes Office‑Math‑Objekt in seine entsprechende LaTeX‑Darstellung umgewandelt. +Alles zusammengeführt, hier ein eigenständiges Programm, das Sie noch heute kompilieren und ausführen können: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Warum wir diese Einstellungen wählen:** +**Erwartete Ausgabe** (Auszug): -- `OfficeMathExportMode.LaTeX` ist der einzige Modus, der eine treue mathematische Übersetzung garantiert. -- `PreserveTableLayout` lässt Tabellen so aussehen wie in Word, was praktisch ist, wenn Sie die Ausgabe später in eine LaTeX‑`tabular`‑Umgebung einbetten. -- UTF‑8 stellt sicher, dass Zeichen wie „α“, „β“ oder „∑“ die Rundreise überstehen. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Falls Sie jemals **convert word to latex** ohne den Klartext‑Wrapper benötigen, könnten Sie stattdessen `SaveFormat.LaTeX` wählen – ein kurzer Hinweis für fortgeschrittene Szenarien. +Beachten Sie, wie die Tabelle ihr Raster behält und die Gleichung als sauberes LaTeX erscheint. Das ist der ideale Kompromiss, wenn Sie **Word in txt konvertieren** und gleichzeitig eine getreue Darstellung von Struktur und Mathematik benötigen. --- -## Schritt 3: Das Dokument als Textdatei speichern +## Tipps zum Konvertieren von Word zu TXT und zum Erhalten von Tabellen -Jetzt schreiben wir den LaTeX‑reichen Text auf die Festplatte. Die resultierende `.txt` kann später in `.tex` umbenannt oder direkt in einen LaTeX‑Compiler gepiped werden. +Während der Drei‑Schritte‑Ansatz für die meisten Fälle funktioniert, werfen reale Projekte oft Stolpersteine auf. Nachfolgend praktische Vorschläge, die Ihre **Word in Nur‑Text konvertieren**‑Pipeline robust machen. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Konsistente Kodierung verwenden -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` verwendet standardmäßig UTF‑8, das die meisten Zeichen abdeckt. Wenn Sie eine andere Codepage benötigen (z. B. Legacy‑Systeme, die Windows‑1252 erwarten), setzen Sie die Eigenschaft `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Was Sie in `output.txt` sehen werden:** +### Überschüssige Leerzeichen trimmen -``` -\begin{equation} -E = mc^{2} -\end{equation} +Tabellen mit vielen Spalten können lange Zeilen erzeugen. Nach dem Speichern möchten Sie eventuell mehrere Leerzeichen zu einem Tab zusammenfassen: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Alle anderen Absätze erscheinen als Klartext, während jede Office‑Math‑Formel in eine LaTeX‑`equation`‑Umgebung (oder `inline`, falls sie in Word inline war) eingebettet wird. Das erfüllt die Anforderung **convert word equations latex** perfekt. +### Verschachtelte Tabellen handhaben ---- +Enthält Ihr DOCX Tabellen in Tabellen, behält `PreserveTableLayout` die visuelle Hierarchie bei, aber die Einrückung kann merkwürdig aussehen. Eine schnelle Lösung ist, führende Leerzeichen durch ein benutzerdefiniertes Marker‑Zeichen (z. B. `>>`) zu ersetzen, sodass nachgelagerte Parser die Verschachtelung erkennen können. -## Sonderfälle & Häufige Fragen +### Stapelverarbeitung mehrerer Dateien -| Situation | Was zu tun ist | -|-----------|----------------| -| **Keine Formeln in der Quelle** | Die Konvertierung funktioniert weiterhin; Sie erhalten nur Klartext. Es wird kein zusätzlicher LaTeX‑Code eingefügt. | -| **Sehr große Dokumente (> 100 MB)** | Nutzen Sie `MemoryStream`, um die Ausgabe zu streamen und hohen Speicherverbrauch zu vermeiden. | -| **Nicht unterstützte mathematische Konstrukte** | Aspose.Words deckt 99 % der Office‑Math‑Funktionen ab. Für die seltenen Randfälle müssen Sie das LaTeX manuell nachbearbeiten. | -| **Eine .tex‑Datei statt .txt benötigen** | Ändern Sie `outputPath` so, dass er mit `.tex` endet, und setzen Sie optional `txtOptions.Encoding` auf `Encoding.UTF8`. | -| **Ausführung unter Linux/macOS** | Der gleiche Code funktioniert – achten Sie nur darauf, dass Dateipfade Vorwärtsschrägstriche oder `Path.Combine` verwenden. | +Wenn Sie **Word in txt konvertieren** für Dutzende von Dokumenten benötigen, wickeln Sie die Logik in eine Schleife: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +So können Sie **docx als txt speichern** massenhaft, ohne manuelles Eingreifen. -## Schnell‑Zusammenfassung: TXT mit LaTeX‑Formeln speichern +--- -1. **Laden** Sie die .docx (`Document`). -2. **Setzen** Sie `OfficeMathExportMode = LaTeX` in `TxtSaveOptions`. -3. **Speichern** Sie die Datei (`doc.Save`) mit diesen Optionen. +## Häufige Fallstricke und wie man sie vermeidet -Damit haben Sie den gesamten Workflow, um **wie man txt**‑Dateien zu erstellen, die LaTeX‑formatierte Formeln enthalten. +1. **Fehlender LaTeX‑Exportmodus** – Wenn Sie vergessen, `OfficeMathExportMode = OfficeMathExportMode.LaTeX` zu setzen, fallen Gleichungen auf Nur‑Text zurück (z. B. „Equation 1“). Prüfen Sie immer den Options‑Block. +2. **Tabellenlayout geht verloren** – Der Standardwert von `PreserveTableLayout` ist `false`. Wenn Ihre Ausgabe wie ein Wand‑von‑Text aussieht, haben Sie die Flagge wahrscheinlich nicht aktiviert. +3. **Dateipfade mit Leerzeichen** – Die Verwendung von Roh‑Strings (`@"C:\My Folder\input.docx"`) verhindert Escape‑Probleme. Andernfalls erhalten Sie eine `FileNotFoundException`. +4. **Versionskonflikt** – Ältere Aspose.Words‑Versionen (< 21.9) unterstützen `OfficeMathExportMode` nicht. Aktualisieren Sie auf das neueste Paket, damit **wie man LaTeX exportiert** funktioniert. +5. **Kodierungsfehler bei Nicht‑ASCII‑Zeichen** – Wenn Sie das Symbol � sehen, setzen Sie `options.Encoding` explizit auf UTF‑8 oder die passende Codepage. --- -## Bonus: Die Konvertierung für mehrere Dateien automatisieren +## Lösung erweitern: Von TXT zu Markdown oder HTML -Wenn Sie einen Ordner voller Word‑Dokumente haben, verpacken Sie die obige Logik in eine einfache Schleife: +Manchmal benötigen Sie mehr als Nur‑Text — vielleicht eine Markdown‑Datei, die noch LaTeX‑Blöcke enthält. Die gleichen `TxtSaveOptions` können durch `HtmlSaveOptions` oder `MarkdownSaveOptions` ersetzt werden: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Jetzt können Sie **convert word to latex** stapelweise durchführen – ideal für Forschungsgruppen, die täglich Dutzende Manuskripte erhalten. +Diese kleine Änderung lässt Sie **Word in txt‑ähnliche** Ausgabe erhalten, während Sie die von Ihnen gewünschte Markdown‑Syntax beibehalten. --- ## Fazit -Wir haben **wie man LaTeX aus Word exportiert** Schritt für Schritt behandelt, gezeigt, **wie man txt**‑Dateien speichert, die jede Office‑Math‑Formel bewahren, und demonstriert, wie man **convert word equations latex** ohne Qualitätsverlust durchführt. +Wir haben eine komplette, produktionsreife Antwort auf **wie man LaTeX exportiert** aus einem Word‑Dokument durchgegangen und gleichzeitig gezeigt, wie Sie **Word in txt konvertieren**, **Word in Nur‑Text konvertieren**, **docx als txt speichern** und **wie man Tabellen erhält**. Die wichtigsten Erkenntnisse sind: + +- Laden Sie das DOCX mit `Aspose.Words.Document`. +- Setzen Sie `TxtSaveOptions.OfficeMathExportMode = LaTeX` und `PreserveTableLayout = true`. +- Rufen Sie `doc.Save(outputPath, options)` auf, um eine saubere LaTeX‑reiche Nur‑Text‑Datei zu erhalten. -Mit nur wenigen Zeilen C# und der leistungsstarken Aspose.Words‑Bibliothek können Sie jedes .docx in LaTeX‑bereiten Text verwandeln, der sich in wissenschaftlichen Arbeiten, Lehrbüchern oder automatisierten Veröffentlichungs‑Pipelines einfügt. +Probieren Sie es mit Ihren eigenen Dateien aus, experimentieren Sie mit Kodierungs‑Anpassungen und verarbeiten Sie ganze Ordner stapelweise. Wenn Sie auf Sonderfälle stoßen — verschachtelte Tabellen, exotische Zeichen oder ältere Aspose‑Versionen — schlagen Sie in den Abschnitten „Tipps“ und „Fallstricke“ nach schnellen Lösungen nach. -**Nächste Schritte?** Versuchen Sie erzeugte `.txt` (oder benennen Sie sie in `.tex` um) mit `pdflatex` oder `xelatex` zu einem PDF zu verarbeiten, oder erkunden Sie die Option `SaveFormat.LaTeX` für eine direkte `.tex`‑Datei. Wenn Sie **save docx as txt** mit Erhalt der Formatierung benötigen, experimentieren Sie mit `PreserveTableLayout` und einer eigenen Zeilenumbruch‑Logik. +Bereit für den nächsten Schritt? Versuchen Sie, dasselbe DOCX in Markdown zu konvertieren, oder leiten Sie die erzeugte `.txt` an einen Static‑Site‑Generator weiter, der LaTeX im Web rendert. Die Möglichkeiten sind endlos, und jetzt haben Sie ein solides Fundament für jeden **Word in txt**‑Workflow. -Fragen zu Sonderfällen, Lizenzierung oder Performance‑Optimierungen? Hinterlassen Sie einen Kommentar unten – happy coding! +Viel Spaß beim Coden, und möge Ihr LaTeX beim ersten Versuch kompilieren! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/german/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/german/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..84957be630 --- /dev/null +++ b/words/german/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Speichern Sie Word als PDF mit Aspose.Words in C#. Lernen Sie, DOCX in + PDF zu konvertieren, fehlende Schriftarten zu erkennen und Warnungen zur Schriftart‑Ersetzung + effizient zu behandeln. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: de +og_description: Speichern Sie Word als PDF mit Aspose.Words. Dieses Schritt‑für‑Schritt‑Tutorial + zeigt, wie man docx in PDF konvertiert und fehlende Schriftarten erkennt. +og_title: Word als PDF mit Aspose.Words speichern – Vollständiger Leitfaden +tags: +- Aspose.Words +- C# +- PDF conversion +title: Word als PDF mit Aspose.Words speichern – Komplettanleitung +url: /de/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word als PDF speichern mit Aspose.Words – Komplettanleitung + +Haben Sie jemals **Word als PDF** sofort speichern müssen und sich gefragt, ob Ihnen dabei eine Schriftart fehlt? Sie sind nicht allein – Entwickler kämpfen ständig mit fehlenden Schriftarten, wenn Dokumente konvertiert werden. In diesem Leitfaden führen wir Sie durch eine praktische Lösung, die nicht nur **docx zu pdf konvertiert**, sondern auch **fehlende Schriftarten erkennt** mithilfe der Schriftart‑Ersetzungshinweise von Aspose.Words. + +Wir behandeln alles von der Einrichtung des Warnsammlers bis zur Interpretation der Ausgabe, sodass Sie am Ende genau wissen, wie Sie **Word als PDF** ohne Überraschungen speichern. Keine externen Tools, keine obskuren Einstellungen – nur sauberer C#‑Code, den Sie in jedes .NET‑Projekt einbinden können. + +## Was Sie benötigen + +- **Aspose.Words for .NET** (neueste Version, z. B. 24.10) – Sie können es über NuGet erhalten (`Install-Package Aspose.Words`). +- Eine .NET‑Entwicklungsumgebung (Visual Studio, Rider oder VS Code funktionieren einwandfrei). +- Eine Beispiel‑DOCX‑Datei, die Schriftarten enthalten kann, die auf dem Zielrechner nicht installiert sind. +Das ist alles. Wenn Sie diese Grundlagen haben, können wir loslegen. + +## Word als PDF speichern – Schritt‑für‑Schritt‑Übersicht + +Unten finden Sie das vollständige, ausführbare Programm. Kopieren Sie es gern in ein Konsolen‑App‑Projekt und drücken Sie **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro Tipp:** Ersetzen Sie `YOUR_DIRECTORY` durch einen absoluten Pfad oder verwenden Sie `Path.Combine(Environment.CurrentDirectory, "input.docx")` für einen relativen, sichereren Ansatz. + +### Warum wir einen Warn‑Callback verwenden + +Aspose.Words ersetzt fehlende Schriftarten stillschweigend durch eine Ersatzschrift (in der Regel Arial). Ohne Callback würden Sie nie erfahren, dass eine Ersetzung stattgefunden hat, was zu Layout‑Fehlern im resultierenden PDF führen kann. Durch das Anbinden von `IWarningCallback` erhalten wir eine klare, programmatische Liste jedes fehlenden‑Schriftart‑Ereignisses – ideal zum Protokollieren oder Benachrichtigen von End‑Benutzern. + +### Fehlende Schriftarten erkennen – Worauf Sie achten sollten + +Wenn Sie das Programm ausführen, erzeugt jede fehlende Schriftart eine Konsolenzeile ähnlich wie: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Ist die Liste leer, herzlichen Glückwunsch – **save word as pdf** war erfolgreich und alle ursprünglichen Schriftarten sind erhalten geblieben. + +## Docx zu PDF konvertieren – Ausgabe anpassen + +Manchmal benötigen Sie eine bestimmte PDF‑Version, Bildqualität oder Konformitätsstufe. Aspose.Words ermöglicht das Anpassen des `PdfSaveOptions`‑Objekts, bevor `Save` aufgerufen wird. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Warum das wichtig ist:** Wenn Sie PDFs für rechtliche Archive erzeugen, stellt das Setzen von `PdfA1b` sicher, dass die Datei strengen Standards entspricht. Die gleiche Konvertierung respektiert weiterhin unseren Warn‑Callback, sodass Sie weiterhin **fehlende Schriftarten erkennen**. + +## Aspose Words Font Substitution – Sonderfälle behandeln + +### Szenario 1: Mehrere fehlende Schriftarten + +Verwendet Ihr Quell‑Dokument mehrere benutzerdefinierte Schriftarten, enthält der Warn‑Collector einen Eintrag pro Schriftart. Sie können sie aggregieren: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Szenario 2: Bereitstellung eines Ersatz‑Schriftarten‑Verzeichnisses + +Aspose.Words kann zusätzliche Ordner nach Schriftarten durchsuchen. Setzen Sie die Eigenschaft `FontsFolder` auf `FontSettings`, bevor Sie das Dokument laden: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Jetzt versucht die Bibliothek zuerst Ihren benutzerdefinierten Ordner, wodurch die Wahrscheinlichkeit unerwünschter Ersetzungen reduziert wird. + +### Szenario 3: Ersetzungen ignorieren + +Wenn Sie bevorzugen, dass die Konvertierung fehlschlägt, sobald eine Schriftart fehlt (statt stillschweigend zu ersetzen), werfen Sie innerhalb des Callbacks eine Ausnahme: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Damit zwingen Sie sich, die fehlende Schriftart vor dem Fortfahren zu beheben – nützlich in CI‑Pipelines, in denen stille Fehler nicht akzeptabel sind. + +## Vollständiges End‑zu‑End‑Beispiel + +Alles zusammengeführt, hier eine kompakte Version, die demonstriert, **wie man Word zu PDF konvertiert**, benutzerdefinierte PDF‑Optionen setzt und etwaige Schrift‑Probleme protokolliert: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Erwartete Konsolenausgabe** (wenn Calibri fehlt): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Erscheinen keine Warnungen, hat Ihre **save word as pdf**‑Operation exakt dieselben Schriftarten wie das Quell‑DOCX verwendet. + +## Visuelle Zusammenfassung + +![Save Word as PDF Workflow-Diagramm](https://example.com/diagram.png "Save Word as PDF workflow") + +*Bildbeschreibung:* **save word as pdf** Workflow, der Laden, Warnsammlung und PDF‑Ausgabe zeigt. + +## Häufige Fragen & Antworten + +| Frage | Antwort | +|-------|----------| +| **Benötige ich eine Lizenz für Aspose.Words?** | Eine kostenlose Evaluationslizenz funktioniert für Tests, aber für den Produktionseinsatz ist eine kostenpflichtige Lizenz erforderlich, um das Evaluations‑Wasserzeichen zu entfernen. | +| **Funktioniert das auf .NET Core / .NET 6+?** | Absolut – Aspose.Words zielt auf .NET Standard 2.0 ab, sodass jede aktuelle .NET‑Runtime kompatibel ist. | +| **Kann ich mehrere DOCX‑Dateien in einer Schleife konvertieren?** | Ja, einfach für jede Datei ein neues `Document` instanziieren und denselben `WarningInfoCollector` wiederverwenden, wenn Sie aggregierte Ergebnisse wünschen. | +| **Was passiert, wenn der Ausgabepfad nicht existiert?** | `Document.Save` wirft eine `DirectoryNotFoundException`. Erstellen Sie den Ordner zuerst oder verwenden Sie `Directory.CreateDirectory`. | +| **Gibt es eine Möglichkeit, fehlende Schriftarten in das PDF einzubetten?** | Aspose.Words kann Schriftarten automatisch einbetten, sofern sie auf dem Rechner verfügbar sind; setzen Sie `PdfSaveOptions.EmbedFullFonts = true`. | + +## Fazit + +Sie haben nun ein solides, produktionsreifes Muster, um **Word als PDF** zu speichern, **fehlende Schriftarten zu erkennen** und **Aspose.Words‑Schriftart‑Ersetzungen** zu handhaben. Durch das Anbinden eines Warn‑Callbacks, das Anpassen von Schrift‑Ordnern und optionales Feintuning von `PdfSaveOptions` können Sie zuverlässig **docx zu pdf** konvertieren und Ihre Benutzer über mögliche Schrift‑Probleme informieren, die die Layout‑Treue beeinträchtigen könnten. + +Bereit für den nächsten Schritt? Versuchen Sie, PDFs aus mehreren Dokumenten parallel zu erzeugen, oder erkunden Sie das Hinzufügen von Wasserzeichen und digitalen Signaturen – beides lässt sich leicht aus dem gerade erlernten Code ableiten. Viel Spaß beim Coden, und mögen Ihre PDFs stets exakt so aussehen, wie Sie es beabsichtigen! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-loadoptions/_index.md b/words/german/net/programming-with-loadoptions/_index.md index 6e5b4f3f75..6ad99c09c5 100644 --- a/words/german/net/programming-with-loadoptions/_index.md +++ b/words/german/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ In diesen Tutorials lernen Sie, wie Sie mit LoadOptions Word-Dokumente mit benut | [Word-Dokument mit Aspose.Words in C# wiederherstellen](./recover-word-document-with-aspose-words-in-c/) | Erfahren Sie, wie Sie beschädigte Word-Dokumente mit Aspose.Words in C# wiederherstellen. | | [Wie man LoadOptions in Aspose.Words verwendet – Komplettanleitung](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Erfahren Sie, wie Sie LoadOptions in Aspose.Words umfassend einsetzen, um Dokumente flexibel zu laden und zu konfigurieren. | | [Beschädigtes Dokument in C# wiederherstellen – Wiederherstellungsmodus festlegen & Benutzer auffordern](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Erfahren Sie, wie Sie beschädigte Dokumente in C# mit Aspose.Words wiederherstellen, den Wiederherstellungsmodus aktivieren und den Benutzer informieren. | +| [Beschädigtes DOCX wiederherstellen – Vollständige Anleitung zum Laden beschädigter Word-Dateien in C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Erfahren Sie, wie Sie beschädigte DOCX-Dateien in C# mit Aspose.Words laden und vollständig wiederherstellen – Schritt‑für‑Schritt‑Anleitung. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/german/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..5341853b11 --- /dev/null +++ b/words/german/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-01 +description: Stellen Sie beschädigte DOCX-Dateien schnell mit Aspose.Words wieder + her. Erfahren Sie, wie Sie den Wiederherstellungsmodus einstellen, DOCX sicher laden + und beschädigte Word-Dateien in nur wenigen Schritten lesen. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: de +og_description: Stellen Sie beschädigte docx-Dateien in C# wieder her. Setzen Sie + den Wiederherstellungsmodus, laden Sie docx sicher und lesen Sie beschädigte Word-Dateien + mit Aspose.Words. +og_title: Beschädigte docx wiederherstellen – Kurzleitfaden für C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Beschädigte DOCX wiederherstellen – Vollständige Anleitung zum Laden beschädigter + Word‑Dateien in C# +url: /de/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Beschädigte docx wiederherstellen – Schnellleitfaden für C# + +Haben Sie schon einmal versucht, eine Word‑Datei zu öffnen, die einfach nicht geladen werden wollte, und sich gefragt, ob der Inhalt für immer verloren ist? In vielen realen Projekten werden Sie **recover corrupted docx** Dateien wiederherstellen, ohne den Benutzer zu bitten, den Anhang erneut zu senden. Die gute Nachricht ist, dass Aspose.Words das Kinderspiel macht: Sie setzen einfach den Wiederherstellungsmodus und lassen die Bibliothek die schwere Arbeit erledigen. + +In diesem Tutorial gehen wir die genauen Schritte durch, um **recover corrupted docx** Dateien wiederherzustellen, erklären, warum die Option `RecoveryMode.AutoRecover` die sicherste Wahl ist, und zeigen Ihnen, wie Sie **how to load docx** Dateien laden, die teilweise beschädigt sein könnten. Am Ende können Sie eine beschädigte Word‑Datei lesen, den überlebenden Text extrahieren und sogar das ursprüngliche Format für zukünftige Audits protokollieren. Keine externen Werkzeuge, nur sauberer C#‑Code. + +## Was Sie benötigen + +- **Aspose.Words for .NET** (jede aktuelle Version; die von uns verwendete API funktioniert mit 23.5 und neuer). +- Eine .NET‑Entwicklungsumgebung (Visual Studio, VS Code oder Rider). +- Die beschädigte oder teilweise beschädigte `.docx`, die Sie retten möchten. + +Keine besonderen Berechtigungen, kein COM‑Interop und keine Notwendigkeit, Microsoft Office auf dem Server zu installieren. Einfach, oder? + +## Schritt 1: Wiederherstellungsmodus auf Auto‑Recover setzen + +Wenn eine Word‑Datei beschädigt ist, wirft das Standard‑Ladeverhalten eine Ausnahme und bricht ab. Durch die Konfiguration eines `LoadOptions`‑Objekts teilen Sie Aspose.Words mit, **set recovery mode** auf `AutoRecover` zu setzen, wodurch das ZIP‑Paket durchsucht, nicht lesbare Teile übersprungen und alles, was zusammengefügt werden kann, zurückgegeben wird. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Warum AutoRecover?** +> Es versucht, so viel wie möglich zu lesen, während das Dokumentobjekt nutzbar bleibt. Wenn Sie `RecoveryMode.NoRecovery` wählen, schlägt das Laden beim ersten Fehler fehl, was den Zweck von **recover corrupted docx**‑Szenarien zunichte macht. + +## Schritt 2: Dokument mit den konfigurierten Optionen laden + +Da der Wiederherstellungsmodus nun gesetzt ist, können Sie versuchen, die Datei sicher zu öffnen. Ersetzen Sie `"YOUR_DIRECTORY/input.docx"` durch den tatsächlichen Pfad zu Ihrer beschädigten Datei. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Wenn die Datei nur teilweise beschädigt ist, wird die `Document`‑Instanz trotzdem erstellt. Sie können später `document.IsStructureValid` prüfen, falls Sie zusätzliche Validierung benötigen. + +## Schritt 3: Erkannten Format überprüfen + +Aspose.Words erkennt automatisch das ursprüngliche Format (DOC, DOCX, ODT usw.). Das Ausgeben dieses Wertes hilft Ihnen zu bestätigen, dass die Bibliothek die Datei korrekt erkannt hat, was ein schneller Plausibilitätstest nach einer **recover corrupted docx**‑Operation ist. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typische Ausgabe: + +``` +Loaded with Docx format. +``` + +Selbst wenn einige Teile fehlen, gelingt die Formatserkennung weiterhin – ein weiterer Gewinn für **recover corrupted docx**‑Workflows. + +## Schritt 4: Extrahieren, was Sie können + +Sobald das Dokument geladen ist, können Sie es wie jede gesunde Word‑Datei behandeln. Unten finden Sie ein kompaktes Beispiel, das Klartext extrahiert und in die Konsole schreibt. Das zeigt, dass Sie **read damaged word file** Inhalte ohne Abstürze lesen können. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Wenn die Originaldatei Tabellen oder Bilder enthielt, die beschädigt waren, werden sie einfach aus der Textausgabe weggelassen. Der Rest des Dokuments bleibt intakt. + +## Schritt 5: Saubere Kopie speichern (optional) + +Oft möchten Sie dem Benutzer nach der Wiederherstellung eine neue, saubere Version der Datei geben. Das Speichern im selben Format gewährleistet die Kompatibilität mit nachgelagerten Prozessen. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Jetzt haben Sie eine **recover damaged docx** Datei, die Sie sicher an eine E‑Mail anhängen oder an einen anderen Dienst weitergeben können. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengefügt, hier das komplette, sofort ausführbare Programm. Fügen Sie es in ein neues Konsolenprojekt ein, passen Sie die Dateipfade an und drücken Sie F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Erwartete Ausgabe** (unter der Annahme, dass die Datei einen einzelnen Absatz „Hello world!“ und etwas beschädigtes XML enthält): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Beachten Sie, dass das Programm nie abstürzt – obwohl die Quelldatei teilweise beschädigt war. Das ist das Wesentliche von **recover corrupted docx** mit Aspose.Words. + +## Häufige Fragen & Sonderfälle + +### Was ist, wenn die Datei völlig unlesbar ist? + +Selbst `AutoRecover` hat Grenzen. Wenn der ZIP‑Container selbst irreparabel beschädigt ist, wirft Aspose.Words eine `CorruptedFileException`. In diesem Fall benötigen Sie möglicherweise ein Drittanbieter‑ZIP‑Reparaturtool, bevor Sie erneut versuchen, **recover corrupted docx** durchzuführen. + +### Kann ich andere Formate wiederherstellen (z. B. `.doc`, `.odt`)? + +Absolut. Die gleichen `LoadOptions` funktionieren für jedes von Aspose.Words unterstützte Format. Ändern Sie einfach die Dateierweiterung und die Bibliothek erkennt das ursprüngliche Format automatisch. Das bedeutet, dass Sie auch **recover damaged docx**‑ähnliche Dateien wie `.doc` oder `.rtf` mit identischem Code wiederherstellen können. + +### Wie gehe ich mit großen Dokumenten um, ohne alles in den Speicher zu laden? + +Für Dateien in Gigabyte‑Größe können Sie **load options** wie `LoadOptions.LoadFormat` aktivieren oder das Dokument seitenweise streamen. Der Wiederherstellungsalgorithmus muss jedoch das gesamte Paket lesen, sodass bei sehr großen beschädigten Dateien mit höherem Speicherverbrauch zu rechnen ist. + +### Gibt es eine Möglichkeit zu erkennen, welche Teile verloren gingen? + +Nach dem Laden können Sie `document.GetChildNodes(NodeType.Any, true)` inspizieren und die Anzahl mit einer erwarteten Basis vergleichen. Fehlende Tabellen, Bilder oder Kopfzeilen fehlen einfach in der Knotensammlung. So können Sie genau protokollieren, was **recover damaged docx** wurde, und den Benutzer informieren. + +## Profi‑Tipps für zuverlässige Wiederherstellung + +- **Validieren Sie die Eingabedateigröße** vor dem Laden; eine Null‑Byte‑Datei schlägt immer fehl. +- **Protokollieren Sie das Ergebnis von `RecoveryMode`**, indem Sie `DocumentLoadingException` abfangen und die Fehlermeldung speichern; sie enthält oft Hinweise darauf, welche Teile übersprungen wurden. +- **Führen Sie die Wiederherstellung in einem Hintergrund‑Thread aus**, wenn Sie Uploads in einem Web‑Service verarbeiten – das hält die Anfrage reaktionsfähig. +- **Kombinieren Sie es mit einer Prüfsumme** (z. B. MD5), um zu erkennen, ob sich die wiederhergestellte Datei vom Original unterscheidet; Sie können dann entscheiden, ob beide Versionen behalten werden sollen. + +## Fazit + +Wir haben gerade gezeigt, wie man **recover corrupted docx** Dateien in C# durch **setting recovery mode** auf `AutoRecover` wiederherstellt, das Dokument sicher lädt, den überlebenden Text extrahiert und optional eine saubere Kopie speichert. Dieser Ansatz ermöglicht es Ihnen, **how to load docx** Dateien zu laden, die sonst Ausnahmen werfen würden, und bietet Ihnen eine zuverlässige Methode, **read damaged word file** Inhalte ohne externe Werkzeuge zu lesen. + +Nächste Schritte? Versuchen Sie, `RecoveryMode.AutoRecover` durch `RecoveryMode.NoRecovery` zu ersetzen, um den Unterschied zu sehen, oder experimentieren Sie mit den `LoadOptions`‑Eigenschaften, die die Passwortbehandlung und Schriftart‑Substitution steuern. Sie könnten die Wiederherstellungsroutine auch in eine ASP.NET Core‑API integrieren, die Uploads entgegennimmt und eine reparierte Datei zurückgibt – perfekt für Unternehmens‑Dokumenten‑Management‑Pipelines. + +Haben Sie weitere Fragen zur Word‑Dokumenten‑Wiederherstellung oder möchten sehen, wie man **recover damaged docx** Dateien mit benutzerdefinierten Callbacks wiederherstellt? Hinterlassen Sie unten einen Kommentar und viel Spaß beim Coden! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-markdownsaveoptions/_index.md b/words/german/net/programming-with-markdownsaveoptions/_index.md index 13cb7cb648..c49f5a940a 100644 --- a/words/german/net/programming-with-markdownsaveoptions/_index.md +++ b/words/german/net/programming-with-markdownsaveoptions/_index.md @@ -74,6 +74,11 @@ Erfahren Sie, wie Sie Bilder aus Word‑Dokumenten extrahieren und beim Konverti ### [Word in Markdown konvertieren – Vollständige C#‑Anleitung mit Bildextraktion](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) Erfahren Sie, wie Sie Word‑Dateien in Markdown konvertieren und dabei Bilder extrahieren – umfassende Schritt‑für‑Schritt‑Anleitung in C#. +### [DOCX als Markdown speichern – Word‑Mathematik nach LaTeX exportieren mit Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) + +### [Bilder beim Konvertieren von Word zu Markdown in die Cloud hochladen](./upload-images-to-cloud-when-converting-word-to-markdown/) +Erfahren Sie, wie Sie Bilder beim Konvertieren von Word zu Markdown in die Cloud hochladen. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/german/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..76ad4d53b8 --- /dev/null +++ b/words/german/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Speichern Sie DOCX als Markdown mit Aspose.Words – lernen Sie, Word in + Markdown zu konvertieren, Gleichungen nach LaTeX zu exportieren und die Bildauflösung + in Markdown in einem reibungslosen Workflow festzulegen. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: de +og_description: Speichern Sie DOCX als Markdown mit Aspose.Words. Dieses Tutorial + zeigt, wie man Word in Markdown konvertiert, Gleichungen nach LaTeX exportiert und + die Bildauflösung in Markdown festlegt. +og_title: DOCX als Markdown speichern – Vollständige Anleitung zum Exportieren von + Word‑Mathematik als LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx als Markdown speichern – Word‑Mathematik nach LaTeX exportieren mit Aspose.Words +url: /de/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx als markdown speichern – Word‑Mathematik nach LaTeX exportieren mit Aspose.Words + +Haben Sie jemals versucht, **docx als markdown zu speichern**, sind aber auf das Problem gestoßen, die Office Math‑Gleichungen scharf zu erhalten? Sie sind nicht allein. Die meisten Entwickler stoßen auf ein Hindernis, wenn die Standardkonvertierung Gleichungen als unscharfe Bilder ausgibt und ein manuelles Umschreiben in LaTeX erforderlich macht. + +Gute Neuigkeiten: Aspose.Words übernimmt die schwere Arbeit für Sie. In diesem Tutorial werden wir **word zu markdown konvertieren**, der Engine **export equations to latex** sagen und sogar **set markdown image resolution** für den Rest des Dokuments festlegen. Am Ende haben Sie einen einzigen Befehl, der eine saubere `.md`‑Datei mit LaTeX‑bereiten Formeln und hochauflösenden Bildern erzeugt. + +## Was Sie lernen werden + +- Wie man ein `.docx` lädt, das Office‑Math‑Objekte enthält. +- Welche `MarkdownSaveOptions`‑Eigenschaften **export equations to latex** und **set markdown image resolution** steuern. +- Ein vollständiges, ausführbares C#‑Snippet, das Sie in jedes .NET‑Projekt einfügen können. +- Tipps zur Fehlersuche bei häufigen Problemen, wie fehlenden Schriften oder nicht unterstützten Gleichungs‑Features. + +**Voraussetzungen**: .NET 6+ (oder .NET Framework 4.6+), eine Lizenz für Aspose.Words für .NET und Grundkenntnisse in C#. Wenn Sie sich mit der Erstellung einer Konsolen‑App auskennen, können Sie loslegen. + +--- + +## Schritt 1 – docx als markdown speichern: Laden Sie Ihre Word‑Datei + +Das Erste, was wir benötigen, ist ein `Document`‑Objekt, das auf die Quell‑`.docx`‑Datei verweist. Stellen Sie sich das vor wie das Öffnen eines Buches, bevor Sie Kapitel kopieren. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Warum das wichtig ist*: Wenn das Dokument keine Mathematik enthält, ist der Schritt **export equations to latex** ein No‑Op, aber der Rest der Konvertierung wird trotzdem ausgeführt. Die Prüfung verhindert, dass Sie sich fragen, warum Ihr ausgegebenes Markdown LaTeX‑Blöcke fehlt. + +--- + +## Schritt 2 – Export von Gleichungen nach LaTeX konfigurieren + +Aspose.Words lässt Sie entscheiden, wie Office Math gerendert werden soll. Standardmäßig werden sie in PNG‑Bilder umgewandelt, weshalb viele Tutorials in einer körnigen Markdown‑Datei enden. Das Umschalten von `OfficeMathExportMode` auf `LaTeX` liefert saubere, kopier‑und‑einfüg‑bereite Gleichungen. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Warum `OfficeMathExportMode.LaTeX`?* LaTeX ist die Lingua Franca des wissenschaftlichen Publizierens. Wenn Sie das Markdown später mit einem Static‑Site‑Generator oder einem Jupyter‑Notebook rendern, erscheinen die Gleichungen bei jedem Zoom‑Level scharf. + +--- + +## Schritt 3 – Markdown‑Bildauflösung festlegen (für Nicht‑Mathe‑Inhalte) + +Obwohl wir uns auf Mathematik konzentrieren, enthalten die meisten Word‑Dokumente auch Bilder, Diagramme oder eingebettete SVGs. Die Eigenschaft `ImageResolution` steuert, wie Aspose.Words diese Assets rastert. Ein Wert von **300 DPI** ist ein guter Kompromiss für Bildschirm und Druck. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro‑Tipp*: Wenn Ihr Markdown nur im Web angezeigt wird, können Sie den Wert auf 150 DPI reduzieren, um die Dateigröße zu verringern. Für druckfertige PDFs erhöhen Sie ihn dagegen auf 600 DPI. + +--- + +## Schritt 4 – Konvertierung ausführen – Word‑Mathe nach LaTeX konvertieren + +Jetzt, wo alles konfiguriert ist, erfolgt die eigentliche Konvertierung in einer einzigen Zeile. Aspose.Words übernimmt die schwere Arbeit im Hintergrund. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Erwartete Ausgabe**: Öffnen Sie die erzeugte `.md`‑Datei und Sie sollten etwas Ähnliches sehen: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Beachten Sie die LaTeX‑Blöcke (`$...$` und `$$...$$`), die die vorherigen PNG‑Schnipsel ersetzen. Das Bild am unteren Rand ist weiterhin ein PNG, gerendert mit 300 DPI, wie wir es angefordert haben. + +--- + +## Schritt 5 – Häufige Randfälle & deren Behandlung + +| Situation | Was passiert | Wie zu beheben | +|-----------|--------------|----------------| +| **Fehlende Schriften** (z. B. Cambria Math nicht installiert) | Die LaTeX‑Ausgabe kann unbekannte Symbole enthalten. | Installieren Sie die fehlende Schrift auf dem Server oder betten Sie sie vor der Konvertierung in das Dokument ein. | +| **Komplexe Gleichungen** (Matrix mit benutzerdefinierten Trennzeichen) | Aspose.Words kann trotz `LaTeX`‑Modus auf ein Bild zurückgreifen. | Aktualisieren Sie auf die neueste Aspose.Words‑Version; die Bibliothek erweitert kontinuierlich die Gleichungsunterstützung. | +| **Große Dokumente** ( > 50 MB ) | Speicherbelastung kann zu `OutOfMemoryException` führen. | Verwenden Sie `LoadOptions` mit `LoadFormat.Docx` und streamen Sie die Datei, oder teilen Sie das Dokument vor der Konvertierung in Abschnitte. | +| **Bildgröße zu groß** | Die Markdown‑Datei wird riesig und verlangsamt den Build von Static‑Site‑Generatoren. | Reduzieren Sie `ImageResolution` auf 150 DPI für reine Web‑Szenarien (siehe Schritt 3). | + +--- + +## Schritt 6 – Alles zusammenführen: Vollständiges funktionierendes Beispiel + +Unten finden Sie das *vollständige* Konsolen‑App‑Programm, das Sie in `Program.cs` kopieren und einfügen können. Es enthält alle besprochenen Teile sowie ein wenig zusätzliche Fehlerbehandlung. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Führen Sie das Programm (`dotnet run`) aus und Sie erhalten eine Markdown‑Datei, die **docx als markdown speichert**, während jede Gleichung als LaTeX erhalten bleibt. Kein manuelles Kopieren‑Einfügen, keine hässlichen Rasterbilder für Mathematik. + +--- + +## Fazit + +Wir haben den gesamten Prozess des **docx als markdown Speicherns** mit Aspose.Words durchlaufen, vom Laden der Word‑Datei bis zur Konfiguration von **export equations to latex** und **set markdown image resolution**. Das abschließende Snippet ist produktionsreif und kann in jedes .NET‑Projekt eingefügt werden, das **word zu markdown konvertieren** muss. + +Was kommt als Nächstes? Versuchen Sie, die erzeugte `.md`‑Datei in einen Static‑Site‑Generator wie Hugo oder Jekyll zu speisen und beobachten Sie, wie Ihre Gleichungen wunderschön gerendert werden. Wenn Sie **word math latex** in andere Formate (PDF, HTML) konvertieren müssen, ersetzen Sie einfach `MarkdownSaveOptions` durch `PdfSaveOptions` oder `HtmlSaveOptions` – das gleiche `OfficeMathExportMode`‑Flag funktioniert dabei ebenfalls. + +Haben Sie eine Besonderheit in Ihrem Workflow, z. B. das Abrufen von Word‑Dateien aus Azure Blob Storage oder das Streamen aus einer API? Das gleiche Muster gilt; ersetzen Sie einfach den dateisystembasierten `Document`‑Konstruktor durch einen stream‑basierten. + +Experimentieren Sie gern und teilen Sie uns in den Kommentaren mit, wie dieser Ansatz Ihre Konvertierungsprobleme gelöst hat. Viel Spaß beim Coden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/german/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..6a2a9afdca --- /dev/null +++ b/words/german/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: Bilder in die Cloud hochladen, während ein Word‑Dokument in Markdown + konvertiert wird. Erfahren Sie, wie Sie Bilder aus docx extrahieren und in Azure + Blob Storage speichern. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: de +og_description: Bilder in die Cloud hochladen, während ein Word-Dokument in Markdown + konvertiert wird. Dieser Leitfaden zeigt, wie man Bilder aus einer DOCX-Datei extrahiert + und sie im Azure Blob Storage speichert. +og_title: Bilder beim Konvertieren von Word nach Markdown in die Cloud hochladen +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Bilder beim Konvertieren von Word zu Markdown in die Cloud hochladen +url: /de/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bilder in die Cloud hochladen beim Konvertieren von Word zu Markdown + +Haben Sie schon einmal **Bilder in die Cloud hochladen** müssen, während Sie eine Word‑Datei in Markdown umwandelten? Sie sind nicht allein – Entwickler jonglieren ständig mit Dokumentkonvertierung und Asset‑Management, und beides in einem reibungslosen Ablauf zu erledigen, kann sich anfühlen, als würde man einem sich ständig bewegenden Ziel hinterherlaufen. + +Die gute Nachricht? Mit Aspose.Words können Sie jedes Bild, Diagramm oder jede Grafik aus einer .docx extrahieren, direkt in Azure Blob Storage hochladen und das erzeugte Markdown auf diese Cloud‑URLs verweisen lassen, anstatt auf lokale Dateien. In diesem Tutorial führen wir Sie durch den gesamten Prozess – vom Laden des Quelldokuments bis zum fertigen Markdown‑File, das auf Ihren Azure‑Container zeigt. + +Am Ende dieses Leitfadens können Sie **docx zu Markdown konvertieren**, **Bilder aus docx extrahieren** und **Bilder in Azure Blob speichern** – alles mit nur wenigen Zeilen C#. Keine externen Tools, kein manuelles Kopieren‑Einfügen und definitiv keine kaputten Bild‑Links. + +## Was Sie benötigen + +- **.NET 6.0** oder höher (der Code funktioniert auch mit .NET Core und .NET Framework) +- **Aspose.Words für .NET** (NuGet‑Paket `Aspose.Words`) +- Ein **Azure Storage‑Konto** mit einem Container (z. B. `images`) und einem Shared‑Access‑Key – Sie benötigen die Verbindungszeichenfolge, um Dateien hochzuladen. +- Grundkenntnisse in C# und async/await (optional, aber hilfreich). + +Wenn Sie diese Bausteine bereits haben, großartig – wir springen direkt zur Lösung. Wenn nicht, weist der Abschnitt „Voraussetzungen“ am Ende auf schnelle Einrichtungsschritte hin. + +## Schritt 1: Azure‑Blob‑Hilfsklasse einrichten (Warum das wichtig ist) + +Bevor wir überhaupt das Word‑Dokument berühren, benötigen wir einen kleinen Helfer, der weiß, wie man ein Byte‑Array in Azure Blob Storage hochlädt und eine öffentliche URL zurückgibt. Diese Abstraktion hält die Konvertierungslogik sauber und ermöglicht später ein einfaches Austauschen des Speicherdienstes. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Warum dieser Helfer?** +1. **Trennung der Verantwortlichkeiten** – der Markdown‑Konvertierungscode bleibt auf die Dokumentenverarbeitung fokussiert, nicht auf HTTP‑Details. +2. **Wiederverwendbarkeit** – Sie können `UploadAsync` von überall in Ihrer Anwendung aus aufrufen (z. B. für vom Benutzer hochgeladene Bilder). +3. **Zukunftssicherheit** – ein Wechsel zu Amazon S3 oder Google Cloud Storage erfordert nur eine neue Implementierung derselben Schnittstelle. + +> **Pro‑Tipp:** Setzen Sie die Zugriffs‑Stufe des Containers auf `Blob` (öffentlich) nur, wenn Sie damit einverstanden sind, dass jeder die Bilder lesen kann. Für private Szenarien erzeugen Sie SAS‑Tokens pro Upload und betten diese URLs ein. + +## Schritt 2: Callback zum Speichern von Ressourcen definieren (Der Kern des Upload‑während‑Konvertieren) + +Aspose.Words ermöglicht es Ihnen, jede Ressource (Bild, Diagramm usw.) abzufangen, die normalerweise beim Speichern eines Dokuments als Markdown auf die Festplatte geschrieben würde. Indem wir einen `ResourceSavingCallback` bereitstellen, können wir jede Ressource nach Azure Blob hochladen und den lokalen Dateinamen durch die Cloud‑URL ersetzen. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Was passiert hier?** + +- **Extrahieren** – Aspose.Words liefert für jedes Bild einen Stream. +- **Hochladen** – Wir übergeben diesen Stream an `AzureBlobUploader`. +- **Ersetzen** – Der Markdown‑Writer erhält die öffentliche URL und schreibt sie in die Markdown‑Bildsyntax (`![](https://…)`). + +Da wir `args.AlreadyExists = true` setzen, entstehen keine temporären Dateien im Dateisystem – ein sauberer, zustandsloser Vorgang, ideal für serverlose Funktionen. + +## Schritt 3: Markdown‑Speicheroptionen konfigurieren (Alles zusammenführen) + +Jetzt verknüpfen wir den Callback mit den `MarkdownSaveOptions` von Aspose.Words. Die entscheidenden Flags sind `ExportImagesAsBase64 = false` (damit wir externe Links erhalten) und `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Warum wir Base64 deaktivieren?** +Wenn `ExportImagesAsBase64` auf true steht, bettet Aspose jedes Bild direkt als Data‑URI in das Markdown ein. Das untergräbt den Zweck von **Bilder in die Cloud hochladen**, weil die Markdown‑Datei dadurch stark anwächst und die Bilder im CDN verborgen bleiben. Durch das Ausschalten erhalten wir saubere, externe Links, die auf Azure Blob zeigen – genau das, was moderne Static‑Site‑Generatoren erwarten. + +## Schritt 4: Alles zusammenführen – Eine minimale Konsolen‑App + +Unten finden Sie ein vollständiges, sofort lauffähiges Konsolen‑Programm. Ersetzen Sie die Platzhalter durch Ihre tatsächliche Azure‑Verbindungszeichenfolge und den Containernamen. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Erwartete Ausgabe + +Das Ausführen des Programms mit `sample.docx`, das zwei Bilder enthält, erzeugt: + +- `output.md` mit Markdown‑Bildsyntax wie: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-pdfsaveoptions/_index.md b/words/german/net/programming-with-pdfsaveoptions/_index.md index 99eed72937..a374bd531b 100644 --- a/words/german/net/programming-with-pdfsaveoptions/_index.md +++ b/words/german/net/programming-with-pdfsaveoptions/_index.md @@ -30,7 +30,7 @@ Egal, ob Sie Word-Dokumente für die Online-Verteilung, Archivierung oder den Dr | [Schriftarten in PDF-Dokumente einbetten](./embedded-all-fonts/) | Betten Sie Schriftarten mühelos in PDF-Dokumente ein – mit Aspose.Words für .NET und dieser detaillierten Schritt-für-Schritt-Anleitung. Sorgen Sie für ein einheitliches Erscheinungsbild auf allen Geräten. | | [Einbetten von Teilmengen von Schriftarten in PDF-Dokumente](./embedded-subset-fonts/) Reduzieren Sie die PDF-Dateigröße, indem Sie mit Aspose.Words für .NET nur die benötigten Schriftarten einbetten. Folgen Sie unserer Schritt-für-Schritt-Anleitung, um Ihre PDFs effizient zu optimieren. | | [Reduzieren Sie die PDF-Größe, indem Sie eingebettete Schriftarten deaktivieren](./disable-embed-windows-fonts/) | Reduzieren Sie die PDF-Größe, indem Sie eingebettete Schriftarten mit Aspose.Words für .NET deaktivieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung, um Ihre Dokumente für effizientes Speichern und Teilen zu optimieren. | -| [Optimieren Sie die PDF-Größe, indem Sie eingebettete Schriftarten wie Arial und Times Roman überspringen](./skip-embedded-arial-and-times-roman-fonts/) | Optimieren Sie die PDF-Größe, indem Sie eingebettete Schriftarten wie Arial und Times Roman mit Aspose.Words für .NET überspringen. Folgen Sie dieser Schritt-für-Schritt-Anleitung, um Ihre PDF-Dateien zu optimieren. | +| [Optimieren Sie die PDF Größe, indem Sie eingebettete Schriftarten wie Arial und Times Roman überspringen](./skip-embedded-arial-and-times-roman-fonts/) | Optimieren Sie die PDF Größe, indem Sie eingebettete Schriftarten wie Arial und Times Roman mit Aspose.Words für .NET überspringen. Folgen Sie dieser Schritt-für-Schritt-Anleitung, um Ihre PDF-Dateien zu optimieren. | | [Reduzieren Sie die PDF-Dateigröße, indem Sie keine Kernschriftarten einbetten](./avoid-embedding-core-fonts/) | Erfahren Sie, wie Sie die PDF-Dateigröße reduzieren, indem Sie mit Aspose.Words für .NET keine Kernschriftarten einbetten. Folgen Sie unserer Schritt-für-Schritt-Anleitung zur Optimierung Ihrer PDFs. | | [Escape-URI im PDF-Dokument](./escape-uri/) Erfahren Sie, wie Sie URIs in PDFs mit Aspose.Words für .NET maskieren. Diese ausführliche Anleitung führt Sie Schritt für Schritt durch den Vorgang. | | [Kopf- und Fußzeilenlesezeichen eines Word-Dokuments in ein PDF-Dokument exportieren](./export-header-footer-bookmarks/) | Erfahren Sie in unserer Schritt-für-Schritt-Anleitung, wie Sie mit Aspose.Words für .NET Kopf- und Fußzeilenlesezeichen aus einem Word-Dokument in PDF exportieren. | @@ -50,6 +50,7 @@ Egal, ob Sie Word-Dokumente für die Online-Verteilung, Archivierung oder den Dr | [Barrierefreies PDF in C# erstellen – PDF-Zugänglichkeitstutorial](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET barrierefreie PDFs in C# erzeugen. | | [Barrierefreies PDF aus Word erstellen – Komplettanleitung](./create-accessible-pdf-from-word-complete-guide/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET ein barrierefreies PDF aus einem Word-Dokument erstellen. | | [Erstellen eines barrierefreien PDFs – Schritt‑für‑Schritt‑Anleitung für PDF/UA‑Konformität](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET ein PDF erstellen, das den PDF/UA‑Barrierefreiheitsstandards entspricht. | +| [Dokument als PDF speichern mit Aspose.Words – Vollständige C#‑Anleitung](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Erfahren Sie, wie Sie ein Word‑Dokument mit Aspose.Words in ein PDF konvertieren – vollständige Schritt‑für‑Schritt‑C#‑Anleitung. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/german/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..ff9d83b18a --- /dev/null +++ b/words/german/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Lernen Sie, wie Sie ein Dokument mit Aspose.Words in C# als PDF speichern. + Das Tutorial behandelt außerdem die Konvertierung von Word zu PDF, den Export von + mathematischem LaTeX und den Umgang mit fehlenden Schriftarten. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: de +og_description: Speichern Sie Dokumente mühelos als PDF mit Aspose.Words. Dieser Leitfaden + zeigt außerdem, wie man Word in PDF konvertiert, mathematischen LaTeX exportiert + und fehlende Schriftarten behandelt. +og_title: Dokument als PDF mit Aspose.Words speichern – Vollständiger C#‑Leitfaden +tags: +- Aspose.Words +- C# +- PDF generation +title: Dokument als PDF mit Aspose.Words speichern – Vollständiger C#‑Leitfaden +url: /de/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Dokument als PDF speichern mit Aspose.Words – Vollständige C#‑Anleitung + +Haben Sie sich jemals gefragt, **wie man ein Dokument als PDF** direkt aus einer Word‑Datei speichert, ohne die Barrierefreiheits‑Features zu verlieren? Sie sind nicht allein – Entwickler fragen ständig nach einer zuverlässigen Methode, Word in PDF zu konvertieren, dabei mathematische Gleichungen zu erhalten und fehlende Schriftarten elegant zu behandeln. + +In diesem Tutorial führen wir Sie durch eine Schritt‑für‑Schritt‑Lösung, die nicht nur **save document as pdf** demonstriert, sondern auch **convert word to pdf**, **export math latex** und **handle missing fonts** mit der neuesten Aspose.Words für .NET verwendet. Am Ende haben Sie ein sofort ausführbares C#‑Programm, das PDF/UA‑2‑konforme Dateien erzeugt – ideal für Barrierefreiheits‑Audits. + +## Was Sie benötigen + +- .NET 6 oder höher (der Code funktioniert auch mit .NET Core und .NET Framework) +- Aspose.Words für .NET 25.10 oder neuer – Sie können eine kostenlose Testversion von der Aspose‑Website herunterladen +- Ein einfaches Word‑Dokument (`input.docx`), das mindestens eine schwebende Form und eine mathematische Gleichung enthält (um die export‑math‑latex‑Funktion zu sehen) +- Visual Studio 2022 (oder jede andere IDE Ihrer Wahl) + +> **Pro‑Tipp:** Wenn Sie in einer CI/CD‑Pipeline arbeiten, fügen Sie das Aspose.Words‑NuGet‑Paket zu Ihrer Projektdatei hinzu: + +```xml + +``` + +Jetzt tauchen wir in den Code ein. + +## Schritt 1: Laden des Quelldokuments mit automatischer Wiederherstellung + +Beim Umgang mit realen Word‑Dateien können Sie beschädigte Abschnitte oder fehlende Ressourcen antreffen. Das Aktivieren der automatischen Wiederherstellung stellt sicher, dass der Ladevorgang niemals eine Ausnahme wirft. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Warum das wichtig ist:** +`RecoveryMode.AutoRecover` schützt Ihre Pipeline vor Abstürzen bei fehlerhaften Eingaben, was besonders praktisch ist, wenn Sie **convert word to pdf** in großen Mengen durchführen. + +## Schritt 2: PDF‑Speicheroptionen für vollständige Barrierefreiheit einrichten + +PDF/UA‑2 ist der ISO‑Standard für barrierefreie PDFs. Durch das Konfigurieren einiger Flags erhalten wir eine Datei, die von Screen‑Readern navigiert werden kann, und wir stellen zudem sicher, dass mathematische Gleichungen als verstecktes LaTeX exportiert werden. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Wichtige Punkte:** + +- **ExportFloatingShapesAsInlineTag** – sorgt dafür, dass das resultierende PDF das ursprüngliche Layout beibehält und gleichzeitig semantisch korrekt bleibt. +- **OfficeMathExportMode.LaTeX** – erfüllt die Anforderung **export math latex** und ermöglicht es nachgelagerten Tools, die Gleichungen bei Bedarf zu extrahieren. + +## Schritt 3: Warnungen erfassen (z. B. fehlende Schriftarten) + +Fehlende Schriftarten sind ein häufiges Ärgernis beim Konvertieren von Dokumenten. Aspose.Words kann diese Probleme über einen `WarningCallback` melden. Wir sammeln sie, damit Sie sie später protokollieren oder darauf reagieren können. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Warum das für Sie wichtig ist:** +Wenn die Quelle eine Schriftart verwendet, die nicht auf dem Server installiert ist, fällt das PDF auf eine Standardschrift zurück, was das Layout potenziell zerstören kann. Durch **handle missing fonts** können wir den Benutzer warnen oder einen Ersatz einbetten. + +## Schritt 4: Dokument als barrierefreies PDF speichern + +Jetzt ist der entscheidende Moment – die eigentliche Durchführung der Konvertierung. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Wenn alles reibungslos verläuft, erhalten Sie eine PDF/UA‑2‑Datei, die für jede Gleichung verstecktes LaTeX enthält und die schwebenden Formen korrekt taggt. + +## Schritt 5: Erfasste Warnungen überprüfen (optional, aber empfohlen) + +Nach dem Speichervorgang können Sie über die gesammelten Warnungen iterieren und sie protokollieren. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typische Ausgabe könnte folgendermaßen aussehen: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Das frühe Erkennen dieser Meldungen hilft Ihnen, **handle missing fonts** durchzuführen, bevor sie End‑benutzer beeinträchtigen. + +## Vollständiges funktionierendes Beispiel + +Wenn wir alles zusammenfügen, erhalten Sie das komplette, sofort ausführbare Programm. Ersetzen Sie die Platzhalter‑Pfade durch Ihre eigenen. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Erwartetes Ergebnis:** +- `output.pdf` entspricht PDF/UA‑2. +- Alle schwebenden Formen werden als Inline‑Abbildungen getaggt. +- Jedes Office‑Math‑Objekt erscheint als verstecktes LaTeX (sichtbar, wenn Sie die PDF‑Struktur untersuchen). +- Alle font‑bezogenen Probleme werden in der Konsole ausgegeben, sodass Sie die Möglichkeit haben, **handle missing fonts** auszuführen, bevor Sie die Datei ausliefern. + +![Diagramm, das den Ablauf von Word → Aspose.Words → Barrierefreies PDF (save document as pdf) zeigt](conversion-diagram.png "Flussdiagramm zum Speichern eines Dokuments als PDF") + +*Bild‑Alt‑Text:* **Diagramm, wie man ein Dokument als PDF mit Aspose.Words speichert** + +## Häufige Fragen & Sonderfälle + +### Was ist, wenn ich eine ältere Aspose.Words‑Version verwende? + +Der Flag `OfficeMathExportMode.LaTeX` wurde in Version 25.10 eingeführt. Für ältere Versionen können Sie weiterhin **convert word to pdf** durchführen, jedoch werden die Gleichungen gerastert anstatt als LaTeX exportiert. Ein Upgrade sorgt für optimale Barrierefreiheit. + +### Kann ich benutzerdefinierte Schriftarten einbetten, um ein Zurückfallen zu vermeiden? + +Ja. Setzen Sie `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` bevor Sie `Save` aufrufen. Das hilft ebenfalls beim **handle missing fonts**, indem das PDF gezwungen wird, die benötigten Glyphen zu enthalten. + +### Wie überprüfe ich die PDF/UA‑2‑Konformität? + +Öffnen Sie die Datei in Adobe Acrobat Pro → „Print Production“ → „Preflight“. Wählen Sie das Profil „PDF/A‑2b“ oder „PDF/UA‑2“; Acrobat meldet etwaige Verstöße. + +### Was ist mit passwortgeschützten Word‑Dateien? + +Laden Sie das Dokument mit einem `LoadOptions`, das `Password` enthält. Beispiel: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Der Rest der Pipeline bleibt unverändert. + +## Fazit + +Wir haben alles behandelt, was Sie benötigen, um **save document as pdf** mit Aspose.Words in C# zu verwenden. Das Tutorial zeigte zudem, wie man **convert word to pdf**, **export math latex** und **handle missing fonts** durchführt – alles bei der Erstellung einer barrierefreien PDF/UA‑2‑Datei. + +Probieren Sie den Code aus, experimentieren Sie mit verschiedenen `PdfSaveOptions` (z. B. Bildkompression, PDF/A‑2b) und integrieren Sie ihn in Ihren Dokument‑Verarbeitungs‑Service. Wenn Sie weiter gehen möchten, prüfen Sie Asposes PDF‑spezifische Bibliothek für Nachbearbeitung oder digitale Signaturen. + +Haben Sie weitere Szenarien, die Sie angehen möchten? Hinterlassen Sie gern einen Kommentar oder schauen Sie sich unsere anderen Anleitungen zu **PDF manipulation**, **image extraction** und **batch conversion** an. Viel Spaß beim Coden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-shapes/_index.md b/words/german/net/programming-with-shapes/_index.md index bf4a15665d..5d3f794d41 100644 --- a/words/german/net/programming-with-shapes/_index.md +++ b/words/german/net/programming-with-shapes/_index.md @@ -36,8 +36,8 @@ Mit Aspose.Words für .NET und diesen Tutorials meistern Sie die Bearbeitung von | [Rechteckform in Word mit Aspose.Words – Schritt-für-Schritt-Anleitung](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Erfahren Sie in diesem Schritt-für-Schritt-Tutorial, wie Sie mit Aspose.Words für .NET ein Rechteck in ein Word-Dokument einfügen und anpassen. | | [Rechteckform in Word mit C# erstellen – Schritt‑für‑Schritt‑Anleitung](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET ein Rechteck in ein Word‑Dokument einfügen – Schritt für Schritt in C#. | | [Aspose.Words Formschatten-Tutorial – Schatten zu Word-Form in C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET in C# Schatten zu Word-Formen hinzufügen und das Layout verbessern. | - | [Leeres Word-Dokument mit schattierter Rechteckform erstellen – Schritt‑für‑Schritt‑Anleitung](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET ein leeres Word-Dokument erstellen und eine schattierte Rechteckform hinzufügen. | +| [Wie man Schatten in Aspose.Words verschiebt – Vollständige C#‑Anleitung](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET Schatten in Word-Formen per C# verschieben und anpassen. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/german/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..88c566f1af --- /dev/null +++ b/words/german/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Wie man den Schatten einer Form in Aspose.Words mit C# verschiebt. Erfahren + Sie, wie Sie einer Form einen Schatten hinzufügen, die Unschärfe ändern, die Transparenz + einstellen und den Schatten in wenigen Minuten drehen. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: de +og_description: Wie man den Schatten einer Form in Aspose.Words mit C# verschiebt. + Dieses Tutorial zeigt, wie man einer Form einen Schatten hinzufügt, die Unschärfe + ändert, die Transparenz einstellt und den Schatten dreht. +og_title: Wie man den Schatten in Aspose.Words verschiebt – Vollständiger C#‑Leitfaden +tags: +- Aspose.Words +- C# +- Document Automation +title: Wie man den Schatten in Aspose.Words verschiebt – vollständiger C#‑Leitfaden +url: /de/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Schatten in Aspose.Words verschiebt – vollständiger C# Leitfaden + +Haben Sie sich jemals gefragt, **how to move shadow** auf einer Form in einem Word‑Dokument, ohne Word manuell zu öffnen? In meiner täglichen Arbeit musste ich häufig den Schatten einer Form programmatisch anpassen – sei es für einen professionellen Bericht oder eine dynamische Vorlage. Die gute Nachricht? Mit Aspose.Words können Sie das in wenigen Zeilen erledigen, und Sie lernen außerdem **add shadow to shape**, **how to change blur**, **how to set transparency**, und **how to rotate shadow** in einem Durchgang. + +In diesem Tutorial gehen wir ein reales Szenario durch: Laden eines bestehenden DOCX, das bereits eine Form enthält, Anpassen der Position, Weichheit, Deckkraft und Richtung des Schattens und schließlich Speichern des Ergebnisses. Am Ende haben Sie einen wiederverwendbaren Code‑Snippet, den Sie in jedes .NET‑Projekt einbinden können, und Sie verstehen, warum jede Eigenschaft wichtig ist. + +## Voraussetzungen – Was Sie vor dem Start benötigen + +- **Aspose.Words for .NET** (Version 23.12 oder höher). Sie können es von NuGet mit `Install-Package Aspose.Words` beziehen. +- Eine .NET 6+ Entwicklungsumgebung (Visual Studio, VS Code, Rider – ganz wie Sie möchten). +- Eine Eingabe‑Word‑Datei (`input.docx`), die bereits mindestens eine Form enthält (ein Rechteck, Kreis oder Bild reicht aus). +- Grundlegende Kenntnisse der C#‑Syntax – nichts Besonderes. + +Falls Ihnen etwas davon fehlt, machen Sie kurz Pause und installieren Sie die Bibliothek; der Rest der Anleitung geht davon aus, dass das Paket bereits referenziert ist. + +## Schritt 1: Dokument laden und Ziel‑Form erfassen – **How to Move Shadow** beginnt hier + +Das Erste, was wir tun, ist das Quell‑Dokument zu laden und die Form zu finden, die wir ändern wollen. Aspose.Words behandelt jedes Objekt (Absätze, Tabellen, Formen) als Knoten in einem Baum, sodass wir es direkt abfragen können. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Warum das wichtig ist:** Das Dokument einmal zu laden und dieselbe `Document`‑Instanz wiederzuverwenden ist effizient. Der Aufruf `GetChild` ist sicher, weil er `null` zurückgibt, wenn der Index außerhalb des Bereichs liegt, sodass wir fehlende Formen elegant behandeln können. + +## Schritt 2: Blur‑Radius anpassen – Master **How to Change Blur** + +Ein weicher Schatten wirkt professionell, während ein harter Rand billig erscheinen kann. Die Eigenschaft `BlurRadius` steuert die Weichheit in Punkten (1 pt ≈ 1/72 Zoll). Erhöhen wir sie auf 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro‑Tipp:** Der Standard‑Blur beträgt 0,5 pt. Alles über 5 pt ist in der Regel bemerkbar, aber Vorsicht, ihn zu stark zu erhöhen – das kann die Form vom Blatt getrennt wirken lassen. + +## Schritt 3: Transparenz festlegen – Die Antwort auf **How to Set Transparency** + +Transparenz bestimmt, wie durchscheinend der Schatten ist. Ein Wert von `0` bedeutet vollständig undurchsichtig; `1` bedeutet komplett unsichtbar. Für einen dezenten Effekt verwenden wir `0.3` (30 % transparent). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Warum das für Sie wichtig sein könnte:** Wenn die Form dunkel ist, kann ein vollständig undurchsichtiger Schatten den darunterliegenden Text überlagern. Das Anpassen der Transparenz hält das Dokument lesbar und verleiht dennoch Tiefe. + +## Schritt 4: Schatten verschieben – Der Kern von **How to Move Shadow** + +Die Eigenschaft `Distance` definiert, wie weit der Schatten von der Form versetzt ist, gemessen in Punkten. Eine größere Distanz schiebt den Schatten weiter weg und erzeugt einen dramatischeren Effekt. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Was, wenn Sie nur eine winzige Verschiebung benötigen?** Das Setzen von `Distance` auf `0` lässt den Schatten direkt hinter der Form liegen, was für Prägeeffekte nützlich sein kann. + +## Schritt 5: Lichtquelle rotieren – Lösung für **How to Rotate Shadow** + +Schatten fallen nicht nur gerade nach unten; sie folgen dem Winkel der Lichtquelle. Die Eigenschaft `Angle` (in Grad) rotiert den Schatten um die Form. Neigen wir ihn um 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Schnelles Experiment:** Versuchen Sie `90` für einen rechten Schatten oder `-30` für einen nach links geneigten. Die visuelle Änderung ist sofort sichtbar. + +## Schritt 6: Dokument speichern – Ergebnis von **Add Shadow to Shape** sehen + +Nachdem wir den Schatten angepasst haben, schreiben wir das Dokument zurück auf die Festplatte. Sie können das Original überschreiben oder eine neue Datei erstellen; das Beispiel verwendet eine neue Ausgabedatei. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Erwartete Ausgabe:** Öffnen Sie `output.docx`. Der Schatten der Form erscheint weicher, leicht versetzt, halbtransparent und um 45° gedreht. Wenn Sie ihn nebeneinander mit `input.docx` vergleichen, ist der Unterschied unverkennbar. + +### Vollständiges funktionierendes Beispiel (Kopieren‑Einfügen bereit) + +Unten finden Sie das gesamte Programm in einem Block. Fügen Sie es in ein neues Konsolenprojekt ein, ersetzen Sie `YOUR_DIRECTORY` durch einen tatsächlichen Ordnerpfad und führen Sie es aus. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Häufige Fragen & Sonderfälle + +### Was, wenn das Dokument mehrere Formen enthält? + +Sie können durch alle Formen iterieren: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Kann ich einer Form, die derzeit keinen Schatten hat, einen Schatten hinzufügen? + +Ja. Das `ShadowFormat`‑Objekt ist immer vorhanden; Sie müssen es nur aktivieren: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Funktioniert das mit Bildern und SmartArt? + +Ja. Jeder Knoten, der von `Shape` abgeleitet ist – einschließlich Bilder, Diagramme und SmartArt – stellt `ShadowFormat` bereit. Die gleichen Eigenschaften gelten. + +### Wie steuere ich die Schattenfarbe? + +Verwenden Sie die `Color`‑Eigenschaft: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Kompatibilitätsfragen? + +Aspose.Words 23.12+ unterstützt .NET 6, .NET Core 3.1 und .NET Framework 4.6.2+. Die gezeigte API ist in diesen Versionen stabil. + +## Fazit + +Wir haben gerade **how to move shadow** auf einer Form mit Aspose.Words behandelt und dabei auch **add shadow to shape**, **how to change blur**, **how to set transparency** und **how to rotate shadow** demonstriert. Das vollständige, ausführbare Beispiel ermöglicht es Ihnen, den Schatten jeder Form in wenigen Sekunden anzupassen und Ihren Dokumenten ein poliertes, professionelles Aussehen zu verleihen, ohne Word zu öffnen. + +Bereit für den nächsten Schritt? Versuchen Sie, diese Schattenanpassungen mit **conditional formatting** zu kombinieren – zum Beispiel, nur bei Überschriften oder Diagrammen, die eine bestimmte Größe überschreiten, einen stärkeren Schatten anzuwenden. Oder erkunden Sie **gradient fills** für die Form selbst, um ein wirklich auffälliges Design zu schaffen. + +Wenn Sie auf Probleme stoßen, hinterlassen Sie unten einen Kommentar. Viel Spaß beim Programmieren, und mögen Ihre Schatten immer genau dort fallen, wo Sie sie haben möchten! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/basic-conversions/_index.md b/words/greek/net/basic-conversions/_index.md index 08ead9accd..e04f923d5b 100644 --- a/words/greek/net/basic-conversions/_index.md +++ b/words/greek/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ | [Μετατροπή Word σε PDF σε C# χρησιμοποιώντας το Aspose.Words – Οδηγός](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Μάθετε πώς να μετατρέπετε αρχεία Word σε PDF χρησιμοποιώντας το Aspose.Words για .NET σε C# με οδηγίες βήμα‑βήμα. | | [Αποθήκευση Word ως PDF με Aspose.Words – Πλήρης Οδηγός C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Μάθετε πώς να αποθηκεύετε έγγραφα Word ως PDF χρησιμοποιώντας το Aspose.Words σε C# με πλήρη οδηγό βήμα‑βήμα. | | [Αποθήκευση docx ως pdf με Aspose.Words – Πλήρης Οδηγός C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Μάθετε πώς να αποθηκεύετε αρχεία docx ως PDF χρησιμοποιώντας το Aspose.Words σε C# με πλήρη οδηγό βήμα‑βήμα. | +| [Αποθήκευση Word ως PDF με Aspose.Words – Πλήρης Οδηγός](./save-word-as-pdf-with-aspose-words-complete-guide/) | Μάθετε πώς να αποθηκεύετε έγγραφα Word ως PDF χρησιμοποιώντας το Aspose.Words με πλήρη οδηγίες βήμα‑βήμα. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/greek/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 3da503c760..d5dc8217a5 100644 --- a/words/greek/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/greek/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Πώς να εξάγετε LaTeX από το Word χρησιμοποιώντας το Aspose.Words – μάθετε - πώς να μετατρέπετε το Word σε LaTeX, να αποθηκεύετε το docx ως txt και να διαχειρίζεστε - εξισώσεις σε απλό κείμενο. +date: 2026-05-01 +description: Μάθετε πώς να εξάγετε LaTeX από αρχείο Word, να μετατρέψετε το Word σε + txt και να διατηρήσετε τους πίνακες χρησιμοποιώντας το Aspose.Words σε C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: el -og_description: Πώς να εξάγετε LaTeX από το Word με το Aspose.Words. Αυτός ο οδηγός - σας δείχνει πώς να μετατρέψετε το Word σε LaTeX, να αποθηκεύσετε το docx ως txt - και να διατηρήσετε τις εξισώσεις ανέπαφες. -og_title: Πώς να εξάγετε LaTeX από το Word – Σύντομο σεμινάριο C# +og_description: Ανακαλύψτε πώς να εξάγετε LaTeX από το Word, να μετατρέψετε το Word + σε απλό κείμενο και να διατηρήσετε την διάταξη των πινάκων αμετάβλητη με το Aspose.Words. +og_title: Πώς να εξάγετε LaTeX από το Word – Πλήρης οδηγός C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Πώς να εξάγετε LaTeX από το Word – Οδηγός βήμα‑προς‑βήμα url: /el/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,178 +26,213 @@ url: /el/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Πώς να Εξάγετε LaTeX από το Word – Οδηγός Βήμα‑Βήμα +# Πώς να Εξάγετε LaTeX από το Word – Πλήρης Οδηγός C# -Έχετε αναρωτηθεί ποτέ **πώς να εξάγετε LaTeX από το Word** χωρίς να χάσετε τις δύσκολες εξισώσεις Office Math; Δεν είστε οι μόνοι. Πολλοί προγραμματιστές συναντούν πρόβλημα όταν προσπαθούν να *μετατρέψουν Word σε LaTeX* για ακαδημαϊκά άρθρα, επιστημονικές αναφορές ή αυτοματοποιημένες διαδικασίες δημοσίευσης. +Έχετε αναρωτηθεί ποτέ **πώς να εξάγετε LaTeX** από ένα έγγραφο Word χωρίς να χάσετε καμία από τις μαθηματικές εξισώσεις; Δεν είστε μόνοι. Πολλοί προγραμματιστές χρειάζονται να μετατρέψουν ένα .docx που περιέχει Office Math σε καθαρό LaTeX ενώ ταυτόχρονα **convert Word to txt** για επεξεργασία σε επόμενα στάδια. Σε αυτόν τον οδηγό θα περάσουμε βήμα‑βήμα από τη φόρτωση του αρχείου πηγής μέχρι τη ρύθμιση του `TxtSaveOptions` ώστε η έξοδος να είναι τόσο φιλική προς τον άνθρωπο όσο και προς το μηχάνημα. Στο τέλος θα μπορείτε να **save docx as txt**, **convert Word to plain text**, και να γνωρίζετε **πώς να διατηρήσετε πίνακες** κατά την εξαγωγή. Χωρίς εξωτερικά scripts, χωρίς χειροκίνητο copy‑pasting—απλός κώδικας C# που μπορείτε να ενσωματώσετε σε οποιοδήποτε .NET project. -Σε αυτό το tutorial θα περάσουμε από ένα πλήρες, έτοιμο‑για‑εκτέλεση παράδειγμα C# που δείχνει **πώς να εξάγετε LaTeX** χρησιμοποιώντας το Aspose.Words, εξηγεί **πώς να αποθηκεύσετε txt** αρχεία με σήμανση LaTeX, και καλύπτει ακόμη τις λεπτομέρειες του **convert word equations latex** ώστε τίποτα να μην χαθεί στη μετάφραση. +## Τι Θα Χρειαστείτε + +- **Aspose.Words for .NET** (τελευταία έκδοση, 2024.x ή νεότερη). Το πακέτο NuGet είναι `Aspose.Words`. +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio, VS Code, Rider—όποιο προτιμάτε). +- Ένα αρχείο Word (`.docx`) που περιέχει εξισώσεις Office Math και τουλάχιστον έναν πίνακα (για να δούμε τη μαγεία διατήρησης πινάκων). -> **Συμβουλή:** Η ίδια προσέγγιση λειτουργεί για οποιοδήποτε .docx έχετε—απλώς δείξτε τον κώδικα σε διαφορετική διαδρομή αρχείου. +Αυτό είναι όλο. Αν τα έχετε ήδη, συνεχίστε την ανάγνωση· διαφορετικά κατεβάστε το πακέτο NuGet και ένα δείγμα DOCX πριν προχωρήσουμε πιο βαθιά. --- -## Τι Θα Χρειαστείτε +## Πώς να Εξάγετε LaTeX από Ένα Έγγραφο Word + +Παρακάτω βρίσκεται η ουσία του tutorial—τρεις σύντομα βήματα που απαντούν στην ερώτηση **how to export latex** ενώ ταυτόχρονα εξυπηρετούν τους δευτερεύοντες στόχους **convert word to txt**, **convert word to plain text**, **save docx as txt**, και **how to preserve tables**. -Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε τα παρακάτω προαπαιτούμενα: +### Βήμα 1: Φόρτωση του Αρχείου DOCX -| Προαπαιτούμενο | Γιατί είναι σημαντικό | -|----------------|-----------------------| -| **.NET 6.0+** (ή .NET Framework 4.6+) | Το Aspose.Words στοχεύει σε σύγχρονες εκτελέσεις .NET. | -| **Aspose.Words for .NET** πακέτο NuGet (`Aspose.Words`) | Η βιβλιοθήκη κάνει τη βαριά δουλειά της ανάλυσης του Word και δημιουργίας LaTeX. | -| **Ένα δείγμα .docx** που περιέχει τουλάχιστον μία εξίσωση Office Math | Για να δείτε τη μετατροπή LaTeX σε δράση. | -| **Visual Studio 2022** (ή οποιοδήποτε IDE προτιμάτε) | Κάνει το debugging και την εκτέλεση του δείγματος εύκολη. | +Πρώτα πρέπει να διαβάσουμε το έγγραφο Word σε ένα αντικείμενο `Aspose.Words.Document`. Αυτό το βήμα είναι το ίδιο είτε αργότερα **convert word to txt** είτε **save docx as txt**. -Αν δεν έχετε εγκαταστήσει ακόμη το πακέτο NuGet, τρέξτε: +```csharp +using Aspose.Words; +using Aspose.Words.Saving; -```bash -dotnet add package Aspose.Words +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -Αυτό είναι όλο—χωρίς επιπλέον DLLs, χωρίς COM interop, μόνο μια καθαρή διαχειριζόμενη βιβλιοθήκη. +> **Γιατί είναι σημαντικό:** Η φόρτωση του αρχείου δημιουργεί μια αναπαράσταση στη μνήμη όλων των στοιχείων του Word—παραγράφων, πινάκων και αντικειμένων Office Math. Χωρίς αυτό το αντικείμενο δεν μπορείτε να χειριστείτε τις επιλογές εξαγωγής. ---- +### Βήμα 2: Ρύθμιση του `TxtSaveOptions` για LaTeX και Διάταξη Πίνακα -## Πώς να Εξάγετε LaTeX από το Word – Επισκόπηση +Η κλάση `TxtSaveOptions` σας επιτρέπει να ελέγξετε ακριβώς πώς δημιουργείται το αρχείο plain‑text. Δύο ιδιότητες είναι κλειδιά για το σενάριό μας: -Ακολουθεί η γενική εικόνα του τι θα πετύχουμε: +| Ιδιότητα | Τι κάνει | Γιατί το χρειάζεστε | +|----------|----------|----------------------| +| `OfficeMathExportMode` | Καθορίζει πώς αποδίδεται το Office Math. Ορίζοντάς το σε `LaTeX` μετατρέπει τις εξισώσεις σε σύνταξη LaTeX. | Αυτό είναι ο πυρήνας του **how to export latex**. | +| `PreserveTableLayout` | Όταν είναι `true`, το Aspose προσθέτει κενά ώστε οι πίνακες να διατηρούν μια εμφάνιση πλέγματος. | Αυτό ικανοποιεί το **how to preserve tables** ενώ εσείς **convert word to txt**. | -1. **Φορτώνουμε** το πηγαίο έγγραφο Word (`.docx`). -2. **Ρυθμ το `TxtSaveOptions` ώστε οποιαδήποτε αντικείμενα Office Math να εκτυπώνονται ως κώδικας LaTeX. -3. **Αποθηκεύουμε** το έγγραφο ως αρχείο απλού κειμένου (`.txt`) που μπορείτε να δώσετε απευθείας σε οποιονδήποτε μεταγλωττιστή LaTeX. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Συμβουλή:** Αν χρειάζεστε μόνο το ακατέργαστο LaTeX χωρίς μορφοποίηση πινάκων, ορίστε `PreserveTableLayout` σε `false`. Το αρχείο γίνεται μικρότερο, αλλά χάνετε το οπτικό σήμα του πίνακα. -## Βήμα 1: Φόρτωση του Εγγράφου Word +### Βήμα 3: Αποθήκευση του Εγγράφου ως Plain Text -Πρώτα απ' όλα—ανοίξτε το .docx που θέλετε να μετατρέψετε. Η κλάση `Document` αφαιρεί την πολυπλοκότητα του υποκείμενου XML, παρέχοντάς σας ένα φιλικό μοντέλο αντικειμένων. +Τώρα γράφουμε το έγγραφο σε ένα αρχείο `.txt` χρησιμοποιώντας τις επιλογές που μόλις ορίσαμε. Αυτή η μία γραμμή εκτελεί **convert word to plain text**, **save docx as txt**, και φυσικά **how to export latex** ταυτόχρονα. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; - -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Γιατί είναι σημαντικό:** -Η πρώιμη φόρτωση του αρχείου μας επιτρέπει να ελέγξουμε το περιεχόμενό του (π.χ. αριθμό εξισώσεων) πριν αποφασίσουμε πώς θα το σειριοποιήσουμε. Αν το αρχείο είναι κατεστραμμένο, η `Document` θα ρίξει μια σαφή εξαίρεση, σώζοντάς σας από μυστηριώδη έξοδο αργότερα. +Μετά την ολοκλήρωση, ανοίξτε το `output.txt`. Θα δείτε: ---- +- Αποσπάσματα LaTeX όπως `\frac{a}{b}` για κάθε εξίσωση Office Math. +- Πίνακες που αποτυπώνονται με χαρακτήρες `|` και `-`, διατηρώντας την ευθυγράμμιση των στηλών. +- Κανονικές παραγράφους ως plain text, έτοιμες για οποιονδήποτε downstream parser. -## Βήμα 2: Ρύθμιση TxtSaveOptions για Εξαγωγή LaTeX +### Πλήρες Παράδειγμα Εργασίας -Η μαγεία συμβαίνει στο `TxtSaveOptions`. Ορίζοντας το `OfficeMathExportMode` σε `LaTeX`, κάθε αντικείμενο Office Math μετατρέπεται στην αντίστοιχη αναπαράσταση LaTeX. +Συνδυάζοντας τα παραπάνω, εδώ είναι ένα αυτόνομο πρόγραμμα που μπορείτε να μεταγλωττίσετε και να τρέξετε σήμερα: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} +``` + +**Αναμενόμενη έξοδος** (απόσπασμα): + ``` +This is a sample paragraph. -**Γιατί επιλέγουμε αυτές τις ρυθμίσεις:** +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | -- `OfficeMathExportMode.LaTeX` είναι η μοναδική λειτουργία που εγγυάται πιστή μαθηματική μετάφραση. -- `PreserveTableLayout` διατηρεί τις πίνακες όπως εμφανίζονται στο Word, κάτι χρήσιμο όταν ενσωματώνετε το αποτέλεσμα σε περιβάλλον LaTeX `tabular`. -- UTF‑8 εξασφαλίζει ότι χαρακτήρες όπως “α”, “β”, ή “∑” παραμένουν αμετάβλητοι. +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Αν ποτέ χρειαστείτε **convert word to latex** χωρίς το περιτύλιγμα plain‑text, μπορείτε να αλλάξετε σε `SaveFormat.LaTeX`—μια γρήγορη υπόδειξη για προχωρημένα σενάρια. +Παρατηρήστε πώς ο πίνακας διατηρεί το πλέγμα του και η εξίσωση εμφανίζεται ως καθαρό LaTeX. Αυτό είναι το ιδανικό αποτέλεσμα όταν **convert word to txt** και χρειάζεστε πιστή αναπαράσταση τόσο της δομής όσο και των μαθηματικών. --- -## Βήμα 3: Αποθήκευση του Εγγράφου ως Αρχείο Κειμένου +## Συμβουλές για Convert Word to TXT και Διατήρηση Πινάκων -Τώρα γράφουμε το κείμενο πλούσιο σε LaTeX στο δίσκο. Το παραγόμενο `.txt` μπορεί αργότερα να μετονομαστεί σε `.tex`, ή να περάσει απευθείας σε μεταγλωττιστή LaTeX. +Αν και η τρι‑βήμα προσέγγιση λειτουργεί στις περισσότερες περιπτώσεις, τα πραγματικά έργα συχνά φέρνουν εκπλήξεις. Ακολουθούν πρακτικές προτάσεις που κάνουν το pipeline **convert word to plain text** πιο ανθεκτικό. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Χρησιμοποιήστε Συνεπή Κωδικοποίηση -// Save using the configured options -doc.Save(outputPath, txtOptions); +Το `TxtSaveOptions` προεπιλογή είναι UTF‑8, που καλύπτει τους περισσότερους χαρακτήρες. Αν χρειάζεστε διαφορετική κωδικοσελίδα (π.χ. παλαιά συστήματα που απαιτούν Windows‑1252), ορίστε την ιδιότητα `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Τι θα δείτε στο `output.txt`:** +### Αφαιρέστε Περιττά Κενά -``` -\begin{equation} -E = mc^{2} -\end{equation} +Πίνακες με πολλές στήλες μπορούν να δημιουργήσουν μακριές γραμμές. Μετά την αποθήκευση, ίσως θελήσετε να επεξεργαστείτε το αρχείο ώστε να συμπτύξετε πολλαπλά κενά σε μία καρτέλα: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Όλες οι άλλες παράγραφοι εμφανίζονται ως απλό κείμενο, ενώ κάθε εξίσωση Office Math τυλίγεται σε περιβάλλον LaTeX `equation` (ή `inline` αν ήταν ενσωματωμένη στο Word). Αυτό ικανοποιεί τέλεια την απαίτηση **convert word equations latex**. +### Διαχείριση Φωλιασμένων Πινάκων ---- +Αν το DOCX περιέχει πίνακες μέσα σε πίνακες, το `PreserveTableLayout` θα διατηρήσει την οπτική ιεραρχία, αλλά η εσοχή μπορεί να φαίνεται περίεργη. Μια γρήγορη λύση είναι να αντικαταστήσετε τα αρχικά κενά με έναν προσαρμοσμένο δείκτη (π.χ. `>>`) ώστε οι downstream parsers να εντοπίζουν τα επίπεδα εμφώλευσης. -## Ακραίες Περιπτώσεις & Συχνές Ερωτήσεις +### Επεξεργασία Πολλών Αρχείων Μαζί -| Κατάσταση | Τι πρέπει να κάνετε | -|-----------|---------------------| -| **Δεν υπάρχουν εξισώσεις στην πηγή** | Η μετατροπή λειτουργεί κανονικά· θα λάβετε απλό κείμενο χωρίς πρόσθετο LaTeX. | -| **Πολύ μεγάλα έγγραφα (>100 MB)** | Σκεφτείτε να κάνετε streaming του αποτελέσματος με `MemoryStream` για να αποφύγετε υψηλή χρήση μνήμης. | -| **Μη υποστηριζόμενες μαθηματικές κατασκευές** | Το Aspose.Words καλύπτει το 99 % του Office Math. Για σπάνιες περιπτώσεις, ίσως χρειαστεί να επεξεργαστείτε το LaTeX χειροκίνητα. | -| **Χρειάζεστε αρχείο .tex αντί για .txt** | Αλλάξτε το `outputPath` ώστε να λήγει σε `.tex` και προαιρετικά ορίστε `txtOptions.Encoding` σε `Encoding.UTF8`. | -| **Εκτέλεση σε Linux/macOS** | Ο ίδιος κώδικας λειτουργεί—απλώς βεβαιωθείτε ότι οι διαδρομές αρχείων χρησιμοποιούν forward slashes ή `Path.Combine`. | +Όταν χρειάζεται να **convert word to txt** για δεκάδες έγγραφα, τυλίξτε τη λογική σε βρόχο: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +Με αυτόν τον τρόπο μπορείτε να **save docx as txt** μαζικά χωρίς χειροκίνητη παρέμβαση. -## Πώς να Αποθηκεύσετε TXT με Εξισώσεις LaTeX – Σύντομη Ανακεφαλαίωση +--- -1. **Φορτώστε** το .docx (`Document`). -2. **Ορίστε** `OfficeMathExportMode = LaTeX` στο `TxtSaveOptions`. -3. **Αποθηκεύστε** το αρχείο (`doc.Save`) με αυτές τις επιλογές. +## Συνηθισμένα Παράπλοκα και Πώς να τα Αποφύγετε -Αυτή είναι η πλήρης ροή για **how to save txt** αρχεία που περιέχουν εξισώσεις σε μορφή LaTeX. +1. **Λείπει η Λειτουργία Εξαγωγής LaTeX** – Αν ξεχάσετε να ορίσετε `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, οι εξισώσεις θα επιστρέψουν σε απλό κείμενο (π.χ. “Equation 1”). Ελέγξτε πάντα το μπλοκ επιλογών. +2. **Χαμένη Διάταξη Πίνακα** – Η προεπιλογή είναι `PreserveTableLayout = false`. Αν το αποτέλεσμα μοιάζει με τοίχο κειμένου, πιθανότατα δεν ενεργοποιήσατε τη σημαία. +3. **Διαδρομές Αρχείων με Κενά** – Η χρήση raw strings (`@"C:\My Folder\input.docx"`) αποφεύγει προβλήματα escaping. Διαφορετικά μπορεί να προκύψει `FileNotFoundException`. +4. **Ασυμφωνία Εκδόσεων** – Παλαιότερες εκδόσεις Aspose.Words (< 21.9) δεν υποστηρίζουν `OfficeMathExportMode`. Αναβαθμίστε στο τελευταίο πακέτο για να εξασφαλίσετε ότι το **how to export latex** λειτουργεί. +5. **Σφάλματα Κωδικοποίησης για Μη‑ASCII Χαρακτήρες** – Αν βλέπετε σύμβολα �, ορίστε ρητά `options.Encoding` σε UTF‑8 ή τη σωστή κωδικοσελίδα. --- -## Bonus: Αυτοματοποίηση της Μετατροπής για Πολλά Αρχεία +## Επέκταση της Λύσης: Από TXT σε Markdown ή HTML -Αν έχετε έναν φάκελο γεμάτο Word έγγραφα, τυλίξτε τη λογική παραπάνω σε έναν απλό βρόχο: +Μερικές φορές χρειάζεστε κάτι παραπάνω από plain text—ίσως ένα αρχείο Markdown που διατηρεί τα LaTeX blocks. Η ίδια λογική `TxtSaveOptions` μπορεί να αντικατασταθεί από `HtmlSaveOptions` ή `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Τώρα μπορείτε να **convert word to latex** μαζικά—ιδανικό για ερευνητικές ομάδες που λαμβάνουν δεκάδες χειρόγραφα καθημερινά. +Αυτή η μικρή αλλαγή σας επιτρέπει να **convert word to txt**‑στυλ έξοδο ενώ διατηρείτε τη σύνταξη markdown που αγαπάτε. --- ## Συμπέρασμα -Καλύψαμε **πώς να εξάγετε LaTeX από το Word** βήμα‑βήμα, δείξαμε **πώς να αποθηκεύσετε txt** αρχεία που διατηρούν κάθε εξίσωση Office Math, και ακόμη σας παρουσιάσαμε πώς να **convert word equations latex** χωρίς απώλεια πιστότητας. +Διασχίσαμε μια πλήρη, έτοιμη για παραγωγή απάντηση στο **how to export latex** από ένα έγγραφο Word, ενώ ταυτόχρονα σας δείξαμε πώς να **convert word to txt**, **convert word to plain text**, **save docx as txt**, και **how to preserve tables**. Τα βασικά σημεία είναι: + +- Φορτώστε το DOCX με `Aspose.Words.Document`. +- Ορίστε `TxtSaveOptions.OfficeMathExportMode = LaTeX` και `PreserveTableLayout = true`. +- Καλέστε `doc.Save(outputPath, options)` για να λάβετε ένα καθαρό LaTeX‑πλούσιο αρχείο plain‑text. -Με λίγες μόνο γραμμές C# και τη δυναμική βιβλιοθήκη Aspose.Words, μπορείτε να μετατρέψετε οποιοδήποτε .docx σε κείμενο έτοιμο για LaTeX, κατάλληλο για επιστημονικά άρθρα, βιβλία ή αυτοματοποιημένες αλυσίδες δημοσίευσης. +Δοκιμάστε το στα δικά σας αρχεία, πειραματιστείτε με ρυθμίσεις κωδικοποίησης, και μη διστάσετε να επεξεργαστείτε ολόκληρους φακέλους. Αν αντιμετωπίσετε edge cases—φωλιασμένους πίνακες, εξωτικούς χαρακτήρες ή παλιές εκδόσεις Aspose—επιστρέψτε στις ενότητες “Συμβουλές” και “Παράπλοκα” για γρήγορες λύσεις. -**Τι θα κάνετε στη συνέχεια;** Δοκιμάστε να τροφοδοτήσετε το παραγόμενο `.txt` (ή μετονομάστε το σε `.tex`) σε `pdflatex` ή `xelatex` για να δημιουργήσετε PDF, ή εξερευνήστε την επιλογή `SaveFormat.LaTeX` για άμεσο αρχείο `.tex`. Αν χρειάζεστε **save docx as txt** διατηρώντας τη μορφοποίηση, πειραματιστείτε με `PreserveTableLayout` και προσαρμοσμένο χειρισμό αλλαγών γραμμής. +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να μετατρέψετε το ίδιο DOCX σε Markdown, ή τροφοδοτήστε το παραγόμενο `.txt` σε έναν static‑site generator που αποδίδει LaTeX στο web. Οι δυνατότητες είναι απεριόριστες, και τώρα έχετε μια σταθερή βάση για οποιοδήποτε **convert word to txt** workflow. -Έχετε ερωτήσεις σχετικά με ακραίες περιπτώσεις, άδειες ή βελτιστοποιήσεις απόδοσης; Αφήστε ένα σχόλιο παρακάτω—καλή προγραμματιστική! +Καλή προγραμματιστική δουλειά, και εύχομαι το LaTeX σας να μεταγλωττίζεται πάντα με την πρώτη προσπάθεια! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/greek/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/greek/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..8c5110252a --- /dev/null +++ b/words/greek/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-01 +description: Αποθήκευση Word ως PDF χρησιμοποιώντας το Aspose.Words σε C#. Μάθετε + πώς να μετατρέπετε docx σε PDF, να εντοπίζετε ελλιπείς γραμματοσειρές και να διαχειρίζεστε + αποδοτικά τις προειδοποιήσεις αντικατάστασης γραμματοσειρών. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: el +og_description: Αποθηκεύστε το Word ως PDF χρησιμοποιώντας το Aspose.Words. Αυτός + ο βήμα‑προς‑βήμα οδηγός δείχνει πώς να μετατρέψετε docx σε pdf και να εντοπίσετε + τις ελλείπουσες γραμματοσειρές. +og_title: Αποθήκευση Word ως PDF με το Aspose.Words – Πλήρης Οδηγός +tags: +- Aspose.Words +- C# +- PDF conversion +title: Αποθήκευση Word ως PDF με το Aspose.Words – Πλήρης Οδηγός +url: /el/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αποθήκευση Word ως PDF με Aspose.Words – Πλήρης Οδηγός + +Έχετε ποτέ χρειαστεί να **αποθηκεύσετε Word ως PDF** άμεσα και αναρωτηθήκατε αν θα λείψει κάποιο γράμμα κατά τη διαδικασία; Δεν είστε μόνοι—οι προγραμματιστές αντιμετωπίζουν συνεχώς προβλήματα με ελλιπείς γραμματοσειρές κατά τη μετατροπή εγγράφων. Σε αυτόν τον οδηγό θα περάσουμε βήμα-βήμα από μια πρακτική λύση που όχι μόνο **μετατρέπει docx σε pdf**, αλλά επίσης **ανιχνεύει ελλιπείς γραμματοσειρές** χρησιμοποιώντας τις προειδοποιήσεις αντικατάστασης γραμματοσειρών του Aspose.Words. + +Θα καλύψουμε τα πάντα, από τη ρύθμιση του συλλέκτη προειδοποιήσεων μέχρι την ερμηνεία των αποτελεσμάτων, ώστε στο τέλος να ξέρετε ακριβώς πώς να **αποθηκεύσετε Word ως PDF** χωρίς εκπλήξεις. Χωρίς εξωτερικά εργαλεία, χωρίς περίπλοκες ρυθμίσεις—απλός κώδικας C# που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET. + +## Τι Θα Χρειαστεί + +- **Aspose.Words for .NET** (τελευταία έκδοση, π.χ., 24.10) – μπορείτε να το αποκτήσετε μέσω NuGet (`Install-Package Aspose.Words`). +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio, Rider ή VS Code λειτουργούν καλά). +- Ένα δείγμα αρχείου DOCX που μπορεί να περιέχει γραμματοσειρές που δεν είναι εγκατεστημένες στο μηχάνημα-στόχο. + +Αυτό είναι όλο. Αν έχετε αυτά τα βασικά, είμαστε έτοιμοι να ξεκινήσουμε. + +## Αποθήκευση Word ως PDF – Επισκόπηση Βήμα‑βήμα + +Παρακάτω είναι το πλήρες, εκτελέσιμο πρόγραμμα. Μπορείτε να το αντιγράψετε‑και‑επικολλήσετε σε ένα έργο console app και να πατήσετε **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Συμβουλή:** Αντικαταστήστε το `YOUR_DIRECTORY` με μια απόλυτη διαδρομή ή χρησιμοποιήστε `Path.Combine(Environment.CurrentDirectory, "input.docx")` για μια σχετική, ασφαλέστερη προσέγγιση. + +### Γιατί Χρησιμοποιούμε Callback Προειδοποίησης + +Το Aspose.Words αντικαθιστά σιωπηλά τις ελλιπείς γραμματοσειρές με μια εναλλακτική (συνήθως Arial). Χωρίς ένα callback δεν θα γνωρίζετε ποτέ ότι έγινε η αντικατάσταση, κάτι που μπορεί να προκαλέσει σφάλματα διάταξης στο παραγόμενο PDF. Συνδέοντας το `IWarningCallback`, λαμβάνουμε μια σαφή, προγραμματιστική λίστα με κάθε συμβάν ελλιπούς γραμματοσειράς—ιδανική για καταγραφή ή ενημέρωση των τελικών χρηστών. + +### Ανίχνευση Ελλιπών Γραμματοσειρών – Τι Να Παρατηρήσετε + +Όταν εκτελέσετε το πρόγραμμα, οποιαδήποτε ελλιπής γραμματοσειρά θα εμφανίσει μια γραμμή στην κονσόλα παρόμοια με: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Αν η λίστα είναι κενή, συγχαρητήρια—η **αποθήκευση word ως pdf** ολοκληρώθηκε με όλες τις αρχικές γραμματοσειρές ανέπαφες. + +## Μετατροπή Docx σε PDF – Προσαρμογή του Αποτελέσματος + +Μερικές φορές χρειάζεστε μια συγκεκριμένη έκδοση PDF, ποιότητα εικόνας ή επίπεδο συμμόρφωσης. Το Aspose.Words σας επιτρέπει να ρυθμίσετε το αντικείμενο `PdfSaveOptions` πριν καλέσετε το `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Γιατί είναι σημαντικό:** Αν δημιουργείτε PDF για νομικά αρχεία, η ρύθμιση `PdfA1b` εξασφαλίζει ότι το αρχείο πληροί αυστηρά πρότυπα. Η ίδια μετατροπή εξακολουθεί να σέβεται το callback προειδοποίησης, οπότε θα συνεχίσετε να **ανιχνεύετε ελλιπείς γραμματοσειρές**. + +## Αντικατάσταση Γραμματοσειρών Aspose Words – Διαχείριση Ακραίων Περιπτώσεων + +### Σενάριο 1: Πολλές Ελλιπείς Γραμματοσειρές + +Αν το πηγαίο έγγραφό σας χρησιμοποιεί πολλές προσαρμοσμένες γραμματοσειρές, ο συλλέκτης προειδοποιήσεων θα περιέχει μία καταχώρηση ανά γραμματοσειρά. Μπορείτε να τις συγκεντρώσετε: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Σενάριο 2: Παροχή Καταλόγου Εναλλακτικών Γραμματοσειρών + +Το Aspose.Words μπορεί να ψάξει σε πρόσθετους φακέλους για γραμματοσειρές. Ορίστε την ιδιότητα `FontsFolder` στο `FontSettings` πριν φορτώσετε το έγγραφο: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Τώρα η βιβλιοθήκη θα δοκιμάσει πρώτα τον προσαρμοσμένο φάκελό σας, μειώνοντας την πιθανότητα ανεπιθύμητης αντικατάστασης. + +### Σενάριο 3: Παράβλεψη Αντικαταστάσεων + +Αν προτιμάτε η μετατροπή να αποτυγχάνει όταν λείπει μια γραμματοσειρά (αντί να αντικαθίσταται σιωπηλά), ρίξτε μια εξαίρεση μέσα στο callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Αυτό σας αναγκάζει να αντιμετωπίσετε την ελλιπή γραμματοσειρά πριν προχωρήσετε—χρήσιμο σε CI pipelines όπου οι σιωπηλές αποτυχίες είναι απαράδεκτες. + +## Πλήρες Παράδειγμα Από Αρχή έως Τέλος + +Συνδυάζοντας όλα, εδώ είναι μια συμπαγής έκδοση που δείχνει **πώς να μετατρέψετε Word σε PDF**, ορίζει προσαρμοσμένες επιλογές PDF και καταγράφει τυχόν προβλήματα γραμματοσειρών: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Αναμενόμενη έξοδος κονσόλας** (αν λείπει το Calibri): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Αν δεν εμφανιστούν προειδοποιήσεις, η λειτουργία **save word as pdf** χρησιμοποίησε τις ακριβώς ίδιες γραμματοσειρές με το πηγαίο DOCX. + +## Οπτική Σύνοψη + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Κείμενο εναλλακτικής εικόνας:* **save word as pdf** ροή εργασίας που δείχνει τη φόρτωση, τη συλλογή προειδοποιήσεων και την έξοδο PDF. + +## Συχνές Ερωτήσεις & Απαντήσεις + +| Ερώτηση | Απάντηση | +|----------|--------| +| **Χρειάζομαι άδεια για το Aspose.Words;** | Μια δωρεάν άδεια αξιολόγησης λειτουργεί για δοκιμές, αλλά η παραγωγική χρήση απαιτεί πληρωμένη άδεια για την αφαίρεση του υδατογραφήματος αξιολόγησης. | +| **Θα λειτουργήσει αυτό σε .NET Core / .NET 6+;** | Απολύτως—το Aspose.Words στοχεύει στο .NET Standard 2.0, οπότε οποιοδήποτε πρόσφατο .NET runtime είναι συμβατό. | +| **Μπορώ να μετατρέψω πολλά αρχεία DOCX σε βρόχο;** | Ναι, απλώς δημιουργήστε ένα νέο `Document` για κάθε αρχείο και επαναχρησιμοποιήστε το ίδιο `WarningInfoCollector` αν θέλετε συγκεντρωτικά αποτελέσματα. | +| **Τι γίνεται αν ο φάκελος εξόδου δεν υπάρχει;** | `Document.Save` θα ρίξει `DirectoryNotFoundException`. Δημιουργήστε πρώτα το φάκελο ή χρησιμοποιήστε `Directory.CreateDirectory`. | +| **Υπάρχει τρόπος να ενσωματώσω τις ελλιπείς γραμματοσειρές στο PDF;** | Το Aspose.Words μπορεί να ενσωματώσει τις γραμματοσειρές αυτόματα αν είναι διαθέσιμες στο μηχάνημα· ορίστε `PdfSaveOptions.EmbedFullFonts = true`. | + +## Συμπέρασμα + +Τώρα έχετε ένα σταθερό, έτοιμο για παραγωγή πρότυπο για **αποθήκευση Word ως PDF** ενώ **ανιχνεύετε ελλιπείς γραμματοσειρές** και διαχειρίζεστε σενάρια **αντικατάστασης γραμματοσειρών Aspose.Words**. Συνδέοντας ένα callback προειδοποίησης, προσαρμόζοντας φακέλους γραμματοσειρών και προαιρετικά τροποποιώντας το `PdfSaveOptions`, μπορείτε αξιόπιστα να **μετατρέψετε docx σε pdf** και να κρατάτε τους χρήστες σας ενήμερους για τυχόν προβλήματα γραμματοσειρών που μπορεί να επηρεάσουν την ακρίβεια της διάταξης. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε τη δημιουργία PDF από πολλά έγγραφα παράλληλα, ή εξερευνήστε την προσθήκη υδατογραφιών και ψηφιακών υπογραφών—και τα δύο είναι απλές επεκτάσεις του κώδικα που μόλις μάθατε. Καλή προγραμματιστική δουλειά, και εύχομαι τα PDF σας να φαίνονται πάντα ακριβώς όπως προορίζονται! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-loadoptions/_index.md b/words/greek/net/programming-with-loadoptions/_index.md index 9c8111679d..411ae3d573 100644 --- a/words/greek/net/programming-with-loadoptions/_index.md +++ b/words/greek/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ | [Πώς να ανακτήσετε docx – ορίστε λειτουργία ανάκτησης & ανοίξτε κατεστραμμένα αρχεία Word](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) Μάθετε πώς να ενεργοποιήσετε τη λειτουργία ανάκτησης και να ανοίξετε κατεστραμμένα αρχεία Word με το Aspose.Words για .NET. | | [Πώς να χρησιμοποιήσετε το LoadOptions στο Aspose.Words – Πλήρης Οδηγός](./how-to-use-loadoptions-in-aspose-words-complete-guide/) Μάθετε πώς να χρησιμοποιείτε το LoadOptions στο Aspose.Words με πλήρη οδηγό βήμα προς βήμα. | | [Ανάκτηση Κατεστραμμένου Εγγράφου σε C# – Ορισμός Λειτουργίας Ανάκτησης & Ειδοποίηση Χρήστη](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Μάθετε πώς να ανακτήσετε κατεστραμμένα έγγραφα Word σε C# ορίζοντας λειτουργία ανάκτησης και εμφανίζοντας προτροπή στον χρήστη. | +| [Ανάκτηση κατεστραμμένου docx – Πλήρης Οδηγός Φόρτωσης Κατεστραμμένων Αρχείων Word σε C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Μάθετε πώς να ανοίγετε και να επαναφέρετε κατεστραμμένα αρχεία docx σε C# χρησιμοποιώντας Aspose.Words, βήμα προς βήμα οδηγός. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/greek/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..8efba99810 --- /dev/null +++ b/words/greek/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Ανακτήστε γρήγορα κατεστραμμένα αρχεία docx χρησιμοποιώντας το Aspose.Words. + Μάθετε πώς να ορίσετε τη λειτουργία ανάκτησης, να φορτώσετε το docx με ασφάλεια + και να διαβάσετε κατεστραμμένα αρχεία Word σε λίγα μόνο βήματα. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: el +og_description: Ανακτήστε κατεστραμμένα αρχεία docx σε C#. Ορίστε τη λειτουργία ανάκτησης, + φορτώστε το docx με ασφάλεια και διαβάστε τα κατεστραμμένα αρχεία Word με το Aspose.Words. +og_title: Ανάκτηση κατεστραμμένου docx – Γρήγορος οδηγός C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Ανάκτηση κατεστραμμένου docx – Πλήρης οδηγός για τη φόρτωση κατεστραμμένων + αρχείων Word σε C# +url: /el/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ανάκτηση κατεστραμμένου docx – Σύντομος οδηγός C# + +Ποτέ προσπαθήσατε να ανοίξετε ένα αρχείο Word που απλώς δεν φορτώνει και αναρωτηθήκατε αν το περιεχόμενο χάθηκε για πάντα; Σε πολλά πραγματικά έργα θα **ανακτήσετε κατεστραμμένα docx** αρχεία χωρίς να ζητήσετε από τον χρήστη να στείλει ξανά το συνημμένο. Τα καλά νέα είναι ότι το Aspose.Words το κάνει παιχνιδάκι: απλώς ορίζετε τη λειτουργία ανάκτησης και αφήνετε τη βιβλιοθήκη να κάνει το σκληρό έργο. + +Σε αυτό το tutorial θα περάσουμε βήμα-βήμα τις ακριβείς ενέργειες για **ανακτήσετε κατεστραμμένα docx** αρχεία, θα εξηγήσουμε γιατί η επιλογή `RecoveryMode.AutoRecover` είναι η πιο ασφαλής, και θα σας δείξουμε πώς να **φορτώσετε docx** αρχεία που μπορεί να είναι μερικώς κατεστραμμένα. Στο τέλος θα μπορείτε να διαβάσετε ένα κατεστραμμένο αρχείο Word, να εξάγετε όλο το κείμενο που επέζησε, και ακόμη να καταγράψετε την αρχική μορφή για μελλοντικούς ελέγχους. Χωρίς εξωτερικά εργαλεία, μόνο καθαρός κώδικας C#. + +## Τι θα χρειαστείτε + +- **Aspose.Words for .NET** (οποιαδήποτε πρόσφατη έκδοση· το API που χρησιμοποιούμε λειτουργεί με 23.5 και νεότερες). +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio, VS Code ή Rider). +- Το κατεστραμμένο ή μερικώς κατεστραμμένο `.docx` που θέλετε να διασώσετε. + +Δεν απαιτούνται ειδικά δικαιώματα, δεν χρειάζεται COM interop και δεν χρειάζεται να εγκαταστήσετε το Microsoft Office στον διακομιστή. Απλό, έτσι δεν είναι; + +## Βήμα 1: Ορίστε τη λειτουργία ανάκτησης σε Auto‑Recover + +Όταν ένα αρχείο Word είναι κατεστραμμένο, η προεπιλεγμένη συμπεριφορά φόρτωσης ρίχνει εξαίρεση και διακόπτει. Με τη διαμόρφωση ενός αντικειμένου `LoadOptions` λέτε στο Aspose.Words να **ορίσει τη λειτουργία ανάκτησης** σε `AutoRecover`, η οποία σαρώει το πακέτο zip, παραλείπει τα μη αναγνώσιμα τμήματα και επιστρέφει ό,τι μπορεί να συναρμολογήσει. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Γιατί AutoRecover;** +> Προσπαθεί να διαβάσει όσο το δυνατόν περισσότερο διατηρώντας το αντικείμενο του εγγράφου χρησιμοποιήσιμο. Αν επιλέξετε `RecoveryMode.NoRecovery`, η φόρτωση θα αποτύχει στην πρώτη αλλοίωση, κάτι που αναιρεί το σκοπό των σεναρίων **ανακτήστε κατεστραμμένα docx**. + +## Βήμα 2: Φορτώστε το έγγραφο με τις διαμορφωμένες επιλογές + +Τώρα που η λειτουργία ανάκτησης έχει οριστεί, μπορείτε με ασφάλεια να προσπαθήσετε να ανοίξετε το αρχείο. Αντικαταστήστε `"YOUR_DIRECTORY/input.docx"` με την πραγματική διαδρομή του κατεστραμμένου αρχείου σας. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Αν το αρχείο είναι μόνο μερικώς κατεστραμμένο, η παρουσία `Document` θα δημιουργηθεί παρόλα αυτά. Μπορείτε να ελέγξετε `document.IsStructureValid` αργότερα αν χρειάζεστε επιπλέον επικύρωση. + +## Βήμα 3: Επαληθεύστε τη ανιχνευμένη μορφή + +Το Aspose.Words ανιχνεύει αυτόματα την αρχική μορφή (DOC, DOCX, ODT, κλπ.). Η εκτύπωση αυτής της τιμής σας βοηθά να επιβεβαιώσετε ότι η βιβλιοθήκη αναγνώρισε σωστά το αρχείο, κάτι που αποτελεί γρήγορο έλεγχο λογικής μετά από μια λειτουργία **ανακτήστε κατεστραμμένα docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Τυπική έξοδος: + +``` +Loaded with Docx format. +``` + +Ακόμη και αν λείπουν κάποια τμήματα, η ανίχνευση μορφής εξακολουθεί να επιτυγχάνει — ένα ακόμη πλεονέκτημα για τις ροές εργασίας **ανακτήστε κατεστραμμένα docx**. + +## Βήμα 4: Εξάγετε ό,τι μπορείτε + +Μόλις φορτωθεί το έγγραφο, μπορείτε να το χειριστείτε όπως οποιοδήποτε υγιές αρχείο Word. Παρακάτω υπάρχει ένα σύντομο παράδειγμα που εξάγει απλό κείμενο και το γράφει στην κονσόλα. Αυτό δείχνει ότι μπορείτε να **διαβάσετε κατεστραμμένο αρχείο word** χωρίς καταρρεύσεις. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Αν το αρχικό αρχείο είχε πίνακες ή εικόνες που ήταν κατεστραμμένα, θα παραλειφθούν απλώς από την έξοδο κειμένου. Το υπόλοιπο του εγγράφου παραμένει αμετάβλητο. + +## Βήμα 5: Αποθηκεύστε ένα καθαρό αντίγραφο (Προαιρετικό) + +Συχνά θα θέλετε να δώσετε στον χρήστη μια νέα, καθαρή έκδοση του αρχείου μετά την ανάκτηση. Η αποθήκευση με την ίδια μορφή εξασφαλίζει συμβατότητα με τυχόν επόμενες διαδικασίες. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Τώρα έχετε ένα **ανακτήστε κατεστραμμένο docx** αρχείο που μπορείτε με ασφάλεια να επισυνάψετε σε email ή να το περάσετε σε άλλη υπηρεσία. + +## Πλήρες λειτουργικό παράδειγμα + +Συνδυάζοντας όλα, εδώ είναι το πλήρες, έτοιμο‑να‑τρέξει πρόγραμμα. Επικολλήστε το σε ένα νέο έργο κονσόλας, προσαρμόστε τις διαδρομές αρχείων και πατήστε F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Αναμενόμενη έξοδος** (υποθέτοντας ότι το αρχείο περιέχει μια παράγραφο “Hello world!” και κάποιο κατεστραμμένο XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Παρατηρήστε πώς το πρόγραμμα δεν καταρρέει ποτέ — ακόμη και αν το αρχικό αρχείο ήταν μερικώς σπασμένο. Αυτή είναι η ουσία του **ανακτήστε κατεστραμμένα docx** χρησιμοποιώντας το Aspose.Words. + +## Συχνές ερωτήσεις & Ακραίες περιπτώσεις + +### Τι γίνεται αν το αρχείο είναι εντελώς μη αναγνώσιμο; + +Ακόμη και το `AutoRecover` έχει όρια. Αν το ίδιο το κοντέινερ zip είναι κατεστραμμένο πέρα από την επισκευή, το Aspose.Words θα ρίξει ένα `CorruptedFileException`. Σε αυτή την περίπτωση ίσως χρειαστείτε ένα εξωτερικό εργαλείο επισκευής zip πριν προσπαθήσετε ξανά να **ανακτήσετε κατεστραμμένα docx**. + +### Μπορώ να ανακτήσω άλλες μορφές (π.χ., `.doc`, `.odt`) ; + +Απολύτως. Το ίδιο `LoadOptions` λειτουργεί για οποιαδήποτε μορφή υποστηρίζει το Aspose.Words. Απλώς αλλάξτε την επέκταση του αρχείου και η βιβλιοθήκη θα ανιχνεύσει αυτόματα την αρχική μορφή. Αυτό σημαίνει ότι μπορείτε επίσης να **ανακτήσετε κατεστραμμένα docx**‑συγκεκριμένα αρχεία όπως `.doc` ή `.rtf` με τον ίδιο κώδικα. + +### Πώς να διαχειριστώ μεγάλα έγγραφα χωρίς να φορτώνω τα πάντα στη μνήμη; + +Για αρχεία μεγέθους gigabyte μπορείτε να ενεργοποιήσετε **load options** όπως `LoadOptions.LoadFormat` ή να κάνετε streaming του εγγράφου σελίδα‑με‑σελίδα. Ωστόσο, ο αλγόριθμος ανάκτησης χρειάζεται ακόμα να διαβάσει ολόκληρο το πακέτο, οπότε περιμένετε μεγαλύτερη χρήση μνήμης για πολύ μεγάλα κατεστραμμένα αρχεία. + +### Υπάρχει τρόπος να γνωρίζετε ποια τμήματα χάθηκαν; + +Μετά τη φόρτωση, μπορείτε να ελέγξετε το `document.GetChildNodes(NodeType.Any, true)` και να συγκρίνετε τον αριθμό με μια αναμενόμενη βάση. Οι ελλιπείς πίνακες, εικόνες ή κεφαλίδες θα λείπουν απλώς από τη συλλογή κόμβων. Αυτό σας επιτρέπει να καταγράψετε ακριβώς τι **ανακτήθηκε κατεστραμμένο docx** και να ενημερώσετε τον χρήστη. + +## Επαγγελματικές συμβουλές για αξιόπιστη ανάκτηση + +- **Επικυρώστε το μέγεθος του αρχείου εισόδου** πριν τη φόρτωση· ένα αρχείο μηδενικού μεγέθους θα αποτύχει πάντα. +- **Καταγράψτε το αποτέλεσμα του `RecoveryMode`** πιάνοντας το `DocumentLoadingException` και αποθηκεύοντας το μήνυμα εξαίρεσης· συχνά περιέχει ενδείξεις για τα τμήματα που παραλείφθηκαν. +- **Εκτελέστε την ανάκτηση σε νήμα παρασκηνίου** εάν επεξεργάζεστε μεταφορτώσεις σε μια υπηρεσία web—αυτό διατηρεί το αίτημα ανταποκρινόμενο. +- **Συνδυάστε με άθροισμα ελέγχου** (π.χ., MD5) για να εντοπίσετε αν το ανακτημένο αρχείο διαφέρει από το αρχικό· έτσι μπορείτε να αποφασίσετε αν θα διατηρήσετε και τις δύο εκδόσεις. + +## Συμπέρασμα + +Μόλις δείξαμε πώς να **ανακτήσετε κατεστραμμένα docx** αρχεία σε C# ορίζοντας τη **λειτουργία ανάκτησης** σε `AutoRecover`, φορτώνοντας το έγγραφο με ασφάλεια, εξάγοντας ό,τι κείμενο παραμένει και προαιρετικά αποθηκεύοντας ένα καθαρό αντίγραφο. Αυτή η προσέγγιση σας επιτρέπει να **φορτώσετε docx** αρχεία που διαφορετικά θα έριχναν εξαιρέσεις, και σας παρέχει έναν αξιόπιστο τρόπο να **διαβάσετε κατεστραμμένο αρχείο word** χωρίς εξωτερικά εργαλεία. + +Επόμενα βήματα; Δοκιμάστε να αντικαταστήσετε το `RecoveryMode.AutoRecover` με `RecoveryMode.NoRecovery` για να δείτε τη διαφορά, ή πειραματιστείτε με τις ιδιότητες του `LoadOptions` που ελέγχουν τη διαχείριση κωδικών πρόσβασης και την αντικατάσταση γραμματοσειρών. Μπορείτε επίσης να ενσωματώσετε τη διαδικασία ανάκτησης σε ένα ASP.NET Core API που δέχεται μεταφορτώσεις και επιστρέφει ένα διορθωμένο αρχείο — ιδανικό για επιχειρηματικές ροές διαχείρισης εγγράφων. + +Έχετε περισσότερες ερωτήσεις σχετικά με την ανάκτηση εγγράφων Word, ή θέλετε να δείτε πώς να **ανακτήσετε κατεστραμμένα docx** αρχεία με προσαρμοσμένες κλήσεις; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +![Εικόνα ενός ανακτημένου εγγράφου – ανακτήστε κατεστραμμένα docx](https://example.com/images/recover-corrupted-docx.png "ανακτήστε κατεστραμμένα docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-markdownsaveoptions/_index.md b/words/greek/net/programming-with-markdownsaveoptions/_index.md index 86265e28a6..d7d19b70bb 100644 --- a/words/greek/net/programming-with-markdownsaveoptions/_index.md +++ b/words/greek/net/programming-with-markdownsaveoptions/_index.md @@ -43,6 +43,7 @@ | [Πώς να μετονομάσετε εικόνες κατά τη μετατροπή DOCX σε Markdown](./how-to-rename-images-when-converting-docx-to-markdown/) | Μάθετε πώς να μετονομάσετε εικόνες κατά τη μετατροπή DOCX σε Markdown χρησιμοποιώντας Aspose.Words για .NET. | | [Αποθήκευση docx ως markdown με Aspose.Words – Πλήρης Οδηγός C#](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Μάθετε πώς να μετατρέψετε αρχεία docx σε markdown χρησιμοποιώντας Aspose.Words με πλήρη οδηγό C#. | | [Αποθήκευση εικόνων Word – Μετατροπή Word σε Markdown με Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) | Μάθετε πώς να αποθηκεύσετε εικόνες από έγγραφα Word και να τα μετατρέψετε σε Markdown με Aspose.Words. | +| [Αποθήκευση docx ως markdown – Εξαγωγή μαθηματικών Word σε LaTeX με Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Μάθετε πώς να εξάγετε εξισώσεις Word σε LaTeX κατά τη μετατροπή σε markdown με Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/greek/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..be1da1f4b9 --- /dev/null +++ b/words/greek/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Αποθηκεύστε το docx ως markdown χρησιμοποιώντας το Aspose.Words – μάθετε + πώς να μετατρέπετε το Word σε markdown, να εξάγετε εξισώσεις σε LaTeX και να ορίσετε + την ανάλυση των εικόνων στο markdown σε μια ομαλή ροή εργασίας. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: el +og_description: Αποθήκευση του docx ως markdown με το Aspose.Words. Αυτό το σεμινάριο + δείχνει πώς να μετατρέψετε το Word σε markdown, να εξάγετε εξισώσεις σε LaTeX και + να ορίσετε την ανάλυση των εικόνων στο markdown. +og_title: Αποθήκευση docx ως markdown – Πλήρης οδηγός για την εξαγωγή μαθηματικών + Word σε LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Αποθήκευση docx ως markdown – Εξαγωγή μαθηματικών Word σε LaTeX με το Aspose.Words +url: /el/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# αποθήκευση docx ως markdown – Εξαγωγή Word Math σε LaTeX με Aspose.Words + +Έχετε ποτέ χρειαστεί να **αποθηκεύσετε docx ως markdown** αλλά να μπλέψατε πώς να διατηρήσετε τις εξισώσεις Office Math καθαρές; Δεν είστε μόνοι. Οι περισσότεροι προγραμματιστές συναντούν πρόβλημα όταν η προεπιλεγμένη μετατροπή μετατρέπει τις εξισώσεις σε θολές εικόνες, αναγκάζοντάς τους να τις ξαναγράψουν χειροκίνητα σε LaTeX. + +Καλά νέα: το Aspose.Words μπορεί να κάνει τη σκληρή δουλειά για εσάς. Σε αυτό το tutorial θα **μετατρέψουμε word σε markdown**, θα πούμε στη μηχανή να **εξάγει εξισώσεις σε latex**, και ακόμη να **ορίσουμε την ανάλυση εικόνας markdown** για το υπόλοιπο του εγγράφου. Στο τέλος θα έχετε μια εντολή που δημιουργεί ένα καθαρό αρχείο `.md` με μαθηματικά έτοιμα για LaTeX και εικόνες υψηλής ανάλυσης. + +## Τι Θα Μάθετε + +- Πώς να φορτώσετε ένα `.docx` που περιέχει αντικείμενα Office Math. +- Ποιες ιδιότητες του `MarkdownSaveOptions` ελέγχουν την **εξαγωγή εξισώσεων σε latex** και την **ρύθμιση ανάλυσης εικόνας markdown**. +- Ένα πλήρες, εκτελέσιμο απόσπασμα C# που μπορείτε να επικολλήσετε σε οποιοδήποτε έργο .NET. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων, όπως ελλιπείς γραμματοσειρές ή μη υποστηριζόμενα χαρακτηριστικά εξισώσεων. + +**Προαπαιτούμενα**: .NET 6+ (ή .NET Framework 4.6+), άδεια για Aspose.Words for .NET, και βασική εξοικείωση με C#. Αν είστε άνετοι με τη δημιουργία μιας εφαρμογής κονσόλας, είστε έτοιμοι. + +--- + +## Βήμα 1 – Αποθήκευση docx ως markdown: Φόρτωση του Αρχείου Word + +Το πρώτο που χρειαζόμαστε είναι ένα αντικείμενο `Document` που δείχνει στο πηγαίο `.docx`. Σκεφτείτε το σαν να ανοίγετε το βιβλίο πριν αρχίσετε να αντιγράφετε κεφάλαια. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Γιατί είναι σημαντικό*: Αν το έγγραφο δεν περιέχει μαθηματικά, το βήμα **εξαγωγή εξισώσεων σε latex** θα είναι άσκοπο, αλλά η υπόλοιπη μετατροπή θα εκτελεστεί. Ο έλεγχος σας σώζει από το να αναρωτιέστε γιατί το παραγόμενο Markdown λείπουν τα μπλοκ LaTeX. + +--- + +## Βήμα 2 – Διαμόρφωση Εξαγωγής Εξισώσεων σε LaTeX + +Το Aspose.Words σας επιτρέπει να αποφασίσετε πώς θα αποτυπώνονται τα Office Math. Από προεπιλογή τα μετατρέπει σε εικόνες PNG, γι' αυτό πολλά tutorials καταλήγουν με ένα σπασμένο αρχείο markdown. Η αλλαγή του `OfficeMathExportMode` σε `LaTeX` σας δίνει καθαρές εξισώσεις έτοιμες για αντιγραφή‑επικόλληση. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Γιατί `OfficeMathExportMode.LaTeX`?* Το LaTeX είναι η κοινή γλώσσα της επιστημονικής δημοσίευσης. Όταν αργότερα αποδώσετε το markdown με έναν static‑site generator ή ένα Jupyter notebook, οι εξισώσεις θα εμφανίζονται καθαρές σε οποιοδήποτε επίπεδο ζουμ. + +--- + +## Βήμα 3 – Ορισμός Ανάλυσης Εικόνας Markdown (για Περιεχόμενο χωρίς Μαθηματικά) + +Αν και εστιάζουμε στα μαθηματικά, τα περισσότερα έγγραφα Word περιέχουν επίσης εικόνες, διαγράμματα ή ενσωματωμένα SVG. Η ιδιότητα `ImageResolution` ελέγχει πώς το Aspose.Words rasterizes αυτά τα στοιχεία. Μια τιμή **300 DPI** είναι η ιδανική για οθόνη και εκτύπωση. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Συμβουλή*: Αν το markdown θα εμφανίζεται μόνο στο web, μπορείτε να μειώσετε σε 150 DPI για μικρότερο μέγεθος αρχείου. Αντίστροφα, για PDF έτοιμα για εκτύπωση, αυξήστε σε 600 DPI. + +--- + +## Βήμα 4 – Εκτέλεση της Μετατροπής – Μετατροπή Word Math σε LaTeX + +Τώρα που όλα είναι ρυθμισμένα, η πραγματική μετατροπή είναι μια μόνο γραμμή. Το Aspose.Words κάνει τη σκληρή δουλειά στο παρασκήνιο. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Αναμενόμενο αποτέλεσμα**: Ανοίξτε το παραγόμενο αρχείο `.md` και θα δείτε κάτι όπως: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Παρατηρήστε τα μπλοκ LaTeX (`$...$` και `$$...$$`) που αντικαθιστούν τα προηγούμενα αποσπάσματα PNG. Η εικόνα στο κάτω μέρος παραμένει PNG, αποδομένη σε 300 DPI όπως ζητήσαμε. + +--- + +## Βήμα 5 – Συνηθισμένες Ακραίες Περιπτώσεις & Πώς να τις Διαχειριστείτε + +| Κατάσταση | Τι Συμβαίνει | Πώς να Διορθώσετε | +|-----------|--------------|-------------------| +| **Missing fonts** (π.χ., Cambria Math δεν είναι εγκατεστημένο) | Η έξοδος LaTeX μπορεί να περιέχει άγνωστα σύμβολα. | Εγκαταστήστε τη λείπουσα γραμματοσειρά στον διακομιστή ή ενσωματώστε την στο έγγραφο πριν από τη μετατροπή. | +| **Complex equations** (πίνακας με προσαρμοσμένους οριοθέτες) | Το Aspose.Words μπορεί να επιστρέψει σε εικόνα παρόλο που είναι σε λειτουργία `LaTeX`. | Αναβαθμίστε στην πιο πρόσφατη έκδοση του Aspose.Words· η βιβλιοθήκη βελτιώνει συνεχώς την κάλυψη εξισώσεων. | +| **Large documents** ( > 50 MB ) | Η πίεση μνήμης μπορεί να προκαλέσει `OutOfMemoryException`. | Χρησιμοποιήστε `LoadOptions` με `LoadFormat.Docx` και ροή (stream) του αρχείου, ή χωρίστε το έγγραφο σε ενότητες πριν από τη μετατροπή. | +| **Image size too big** | Το αρχείο Markdown γίνεται τεράστιο, επιβραδύνοντας τις δημιουργίες static‑site. | Μειώστε το `ImageResolution` σε 150 DPI για σενάρια μόνο web (δείτε το Βήμα 3). | + +--- + +## Βήμα 6 – Συνδυάστε Όλα Μαζί: Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω είναι το *πλήρες* πρόγραμμα console‑app που μπορείτε να αντιγράψετε‑επικολλήσετε στο `Program.cs`. Περιλαμβάνει όλα όσα συζητήσαμε, καθώς και λίγη επιπλέον διαχείριση σφαλμάτων. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Εκτελέστε το πρόγραμμα (`dotnet run`) και θα λάβετε ένα αρχείο markdown που **αποθηκεύει docx ως markdown** διατηρώντας κάθε εξίσωση ως LaTeX. Χωρίς χειροκίνητη αντιγραφή‑επικόλληση, χωρίς άσχημες raster εικόνες για μαθηματικά. + +--- + +## Συμπέρασμα + +Διασχίσαμε όλη τη διαδικασία **αποθήκευσης docx ως markdown** με το Aspose.Words, από τη φόρτωση του αρχείου Word μέχρι τη διαμόρφωση **εξαγωγής εξισώσεων σε latex** και **ορισμού ανάλυσης εικόνας markdown**. Το τελικό απόσπασμα είναι έτοιμο για παραγωγή, και μπορείτε να το ενσωματώσετε σε οποιοδήποτε έργο .NET που χρειάζεται **μετατροπή word σε markdown** σε πραγματικό χρόνο. + +Τι ακολουθεί; Δοκιμάστε να τροφοδοτήσετε το παραγόμενο `.md` σε έναν static‑site generator όπως Hugo ή Jekyll και θα δείτε τις εξισώσεις σας να αποδίδονται όμορφα. Αν χρειάζεστε να **μετατρέψετε word math latex** σε άλλες μορφές (PDF, HTML), απλώς αντικαταστήστε το `MarkdownSaveOptions` με `PdfSaveOptions` ή `HtmlSaveOptions`—η ίδια σημαία `OfficeMathExportMode` λειτουργεί και σε αυτές. + +Έχετε μια παραλλαγή στη ροή εργασίας σας, όπως λήψη αρχείων Word από Azure Blob storage ή ροή τους από ένα API; Το ίδιο μοτίβο ισχύει· απλώς αντικαταστήστε τον κατασκευαστή `Document` του συστήματος αρχείων με έναν βασισμένο σε ροή. + +Νιώστε ελεύθεροι να πειραματιστείτε, και ενημερώστε μας στα σχόλια πώς αυτή η προσέγγιση έλυσε τα προβλήματα μετατροπής σας. Καλή κωδικοποίηση! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-pdfsaveoptions/_index.md b/words/greek/net/programming-with-pdfsaveoptions/_index.md index 646baba5ff..6896f5b733 100644 --- a/words/greek/net/programming-with-pdfsaveoptions/_index.md +++ b/words/greek/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ | [Απόδοση 3D DML 3DEffects σε έγγραφο PDF](./dml-3deffects-rendering/) | Μάθετε πώς να αποδίδετε εκπληκτικά εφέ 3D DML σε έγγραφα PDF χρησιμοποιώντας το Aspose.Words για .NET με αυτόν τον ολοκληρωμένο οδηγό βήμα προς βήμα. | | [Παρεμβολή εικόνων σε ένα έγγραφο PDF](./interpolate-images/) | Μάθετε πώς να παρεμβάλλετε εικόνες σε ένα έγγραφο PDF χρησιμοποιώντας το Aspose.Words για .NET με τον αναλυτικό μας οδηγό. Βελτιώστε εύκολα την ποιότητα εικόνας του PDF σας. | | [Αποθήκευση docx ως pdf με Aspose.Words – Πλήρης Οδηγός C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Μάθετε βήμα προς βήμα πώς να μετατρέψετε αρχεία docx σε pdf χρησιμοποιώντας Aspose.Words με C#. | +| [Αποθήκευση εγγράφου ως PDF με Aspose.Words – Πλήρης οδηγός C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Μάθετε βήμα προς βήμα πώς να αποθηκεύσετε ένα έγγραφο ως PDF χρησιμοποιώντας Aspose.Words με C#. | | [Δημιουργία προσβάσιμου PDF από Word με C# – Οδηγός βήμα προς βήμα](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Μάθετε πώς να δημιουργήσετε προσβάσιμα PDF από έγγραφα Word χρησιμοποιώντας C# με αναλυτικές οδηγίες βήμα‑βήμα. | | [Δημιουργία προσβάσιμου PDF σε C# – Εγχειρίδιο προσβασιμότητας PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Μάθετε πώς να δημιουργήσετε προσβάσιμα αρχεία PDF με το Aspose.Words για .NET, ακολουθώντας βήμα-βήμα οδηγίες. | | [Δημιουργία Προσβάσιμου PDF από Word – Πλήρης Οδηγός](./create-accessible-pdf-from-word-complete-guide/) | Μάθετε πώς να δημιουργήσετε προσβάσιμο PDF από Word, ακολουθώντας τα πρότυπα προσβασιμότητας, με πλήρη βήμα-βήμα οδηγό. | diff --git a/words/greek/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/greek/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..bb5137cfbd --- /dev/null +++ b/words/greek/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: Μάθετε πώς να αποθηκεύσετε το έγγραφο ως PDF χρησιμοποιώντας το Aspose.Words + σε C#. Το σεμινάριο καλύπτει επίσης τη μετατροπή Word σε PDF, την εξαγωγή μαθηματικών + σε LaTeX και τη διαχείριση ελλιπών γραμματοσειρών. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: el +og_description: Αποθηκεύστε το έγγραφο ως PDF χωρίς κόπο με το Aspose.Words. Αυτός + ο οδηγός δείχνει επίσης πώς να μετατρέψετε το Word σε PDF, να εξάγετε μαθηματικό + LaTeX και να διαχειριστείτε τις ελλιπείς γραμματοσειρές. +og_title: Αποθήκευση εγγράφου ως PDF με το Aspose.Words – Πλήρης οδηγός C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Αποθήκευση εγγράφου ως PDF με το Aspose.Words – Πλήρης οδηγός C# +url: /el/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αποθήκευση Εγγράφου ως PDF με Aspose.Words – Πλήρης Οδηγός C# + +Έχετε αναρωτηθεί ποτέ **πώς να αποθηκεύσετε το έγγραφο ως pdf** απευθείας από ένα αρχείο Word χωρίς να χάσετε τα χαρακτηριστικά προσβασιμότητας; Δεν είστε μόνοι—οι προγραμματιστές ζητούν συνεχώς έναν αξιόπιστο τρόπο για να μετατρέψουν το Word σε PDF διατηρώντας τις μαθηματικές εξισώσεις και αντιμετωπίζοντας με χάρη τις ελλιπείς γραμματοσειρές. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από μια λύση που όχι μόνο **αποθηκεύει το έγγραφο ως pdf** αλλά επίσης δείχνει **convert word to pdf**, **export math latex**, και **handle missing fonts** χρησιμοποιώντας την πιο πρόσφατη έκδοση του Aspose.Words για .NET. Στο τέλος θα έχετε ένα έτοιμο προς εκτέλεση πρόγραμμα C# που παράγει αρχεία συμβατά με PDF/UA‑2, ιδανικά για ελέγχους προσβασιμότητας. + +## Τι Θα Χρειαστείτε + +- .NET 6 ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Core και .NET Framework) +- Aspose.Words for .NET 25.10 ή νεότερο – μπορείτε να κατεβάσετε μια δωρεάν δοκιμή από την ιστοσελίδα Aspose +- Ένα απλό έγγραφο Word (`input.docx`) που περιέχει τουλάχιστον ένα αιωρούμενο σχήμα και μια μαθηματική εξίσωση (για να δείτε τη λειτουργία export‑math‑latex σε δράση) +- Visual Studio 2022 (ή οποιοδήποτε IDE προτιμάτε) + +> **Συμβουλή επαγγελματία:** Αν βρίσκεστε σε CI/CD pipeline, προσθέστε το πακέτο NuGet Aspose.Words στο αρχείο του έργου σας: + +```xml + +``` + +Τώρα ας βουτήξουμε στον κώδικα. + +## Βήμα 1: Φόρτωση του Πηγαίου Εγγράφου με Αυτόματη Ανάκτηση + +Κατά την επεξεργασία πραγματικών αρχείων Word μπορεί να συναντήσετε κατεστραμμένα τμήματα ή ελλιπείς πόρους. Η ενεργοποίηση της αυτόματης ανάκτησης εξασφαλίζει ότι η διαδικασία φόρτωσης δεν θα πετάξει ποτέ εξαίρεση. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Γιατί είναι σημαντικό:** +`RecoveryMode.AutoRecover` προστατεύει το pipeline σας από κατάρρευση σε εσφαλμένα δεδομένα, κάτι που είναι ιδιαίτερα χρήσιμο όταν **convert word to pdf** μαζικά. + +## Βήμα 2: Ρύθμιση Επιλογών Αποθήκευσης PDF για Πλήρη Προσβασιμότητα + +Το PDF/UA‑2 είναι το πρότυπο ISO για προσβάσιμα PDF. Με τη ρύθμιση μερικών σημάνσεων (flags) λαμβάνουμε ένα αρχείο που οι αναγνώστες οθόνης μπορούν να περιηγηθούν, και επίσης διασφαλίζουμε ότι οι μαθηματικές εξισώσεις εξάγονται ως κρυφό LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Κύρια σημεία:** + +- **ExportFloatingShapesAsInlineTag** – εξασφαλίζει ότι το παραγόμενο PDF σέβεται την αρχική διάταξη ενώ παραμένει σημασιολογικά σωστό. +- **OfficeMathExportMode.LaTeX** – ικανοποιεί την απαίτηση **export math latex**, επιτρέποντας στα επόμενα εργαλεία να εξάγουν τις εξισώσεις αν χρειαστεί. + +## Βήμα 3: Συλλογή Προειδοποιήσεων (π.χ., Ελλιπείς Γραμματοσειρές) + +Οι ελλιπείς γραμματοσειρές είναι ένα κοινό πρόβλημα κατά τη μετατροπή εγγράφων. Το Aspose.Words μπορεί να αναφέρει αυτά τα ζητήματα μέσω ενός `WarningCallback`. Θα τα συλλέξουμε ώστε να μπορείτε να τα καταγράψετε ή να δράσετε αργότερα. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Γιατί σας ενδιαφέρει:** +Αν η πηγή χρησιμοποιεί γραμματοσειρά που δεν είναι εγκατεστημένη στον διακομιστή, το PDF θα επιστρέψει σε προεπιλεγμένη γραμματοσειρά, ενδεχομένως να σπάσει τη διάταξη. Με το **handle missing fonts** μπορούμε να ειδοποιήσουμε τον χρήστη ή να ενσωματώσουμε μια εναλλακτική. + +## Βήμα 4: Αποθήκευση του Εγγράφου ως Προσβάσιμο PDF + +Τώρα η στιγμή της αλήθειας—να εκτελέσουμε πραγματικά τη μετατροπή. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Αν όλα πάνε ομαλά, θα έχετε ένα αρχείο PDF/UA‑2 που περιέχει κρυφό LaTeX για κάθε εξίσωση και σωστή σήμανση για τα αιωρούμενα σχήματα. + +## Βήμα 5: Ανασκόπηση Συλλεγμένων Προειδοποιήσεων (Προαιρετικό αλλά Συνιστάται) + +Μετά τη λειτουργία αποθήκευσης, μπορείτε να επαναλάβετε τις συλλεγμένες προειδοποιήσεις και να τις καταγράψετε. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Η τυπική έξοδος μπορεί να μοιάζει με: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Η έγκαιρη εμφάνιση αυτών των μηνυμάτων σας βοηθά να **handle missing fonts** πριν επηρεάσουν τους τελικούς χρήστες. + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα, εδώ είναι το πλήρες, έτοιμο‑για‑εκτέλεση πρόγραμμα. Αντικαταστήστε τις διαδρομές placeholder με τις δικές σας. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Αναμενόμενο αποτέλεσμα:** +- `output.pdf` συμμορφώνεται με PDF/UA‑2. +- Όλα τα αιωρούμενα σχήματα είναι σημειωμένα ως ενσωματωμένες εικόνες. +- Κάθε αντικείμενο Office Math εμφανίζεται ως κρυφό LaTeX (ορατό όταν ελέγχετε τη δομή του PDF). +- Οποιοδήποτε πρόβλημα σχετικό με γραμματοσειρές εκτυπώνεται στην κονσόλα, δίνοντάς σας την ευκαιρία να **handle missing fonts** πριν τη διανομή του αρχείου. + +![Διάγραμμα που δείχνει τη ροή από Word → Aspose.Words → Προσβάσιμο PDF (save document as pdf)](conversion-diagram.png "Διάγραμμα ροής για την αποθήκευση εγγράφου ως pdf") + +*Κείμενο alt εικόνας:* **Διάγραμμα του πώς να αποθηκεύσετε το έγγραφο ως pdf χρησιμοποιώντας το Aspose.Words** + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### Τι γίνεται αν χρησιμοποιώ παλαιότερη έκδοση του Aspose.Words; + +Η σημαία `OfficeMathExportMode.LaTeX` εισήχθη στην έκδοση 25.10. Για παλαιότερες εκδόσεις μπορείτε ακόμη να **convert word to pdf**, αλλά τα μαθηματικά θα είναι rasterized αντί να εξαχθούν ως LaTeX. Αναβαθμίστε για τη βέλτιστη προσβασιμότητα. + +### Μπορώ να ενσωματώσω προσαρμοσμένες γραμματοσειρές για να αποφύγω την εναλλακτική; + +Ναι. Ορίστε `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` πριν καλέσετε το `Save`. Αυτό επίσης βοηθά το **handle missing fonts** εξαναγκάζοντας το PDF να περιέχει τα απαιτούμενα γλύφους. + +### Πώς μπορώ να επαληθεύσω τη συμμόρφωση PDF/UA‑2; + +Ανοίξτε το αρχείο στο Adobe Acrobat Pro → “Print Production” → “Preflight”. Επιλέξτε το προφίλ “PDF/A‑2b” ή “PDF/UA‑2”; το Acrobat θα αναφέρει τυχόν παραβάσεις. + +### Τι γίνεται με αρχεία Word προστατευμένα με κωδικό; + +Φορτώστε το έγγραφο με ένα `LoadOptions` που περιλαμβάνει `Password`. Παράδειγμα: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +## Συμπέρασμα + +Καλύψαμε όλα όσα χρειάζεστε για να **save document as pdf** χρησιμοποιώντας το Aspose.Words σε C#. Το tutorial επίσης έδειξε πώς να **convert word to pdf**, **export math latex**, και **handle missing fonts**—όλα ενώ παράγουμε ένα προσβάσιμο αρχείο PDF/UA‑2. + +Δοκιμάστε τον κώδικα, πειραματιστείτε με διαφορετικές `PdfSaveOptions` (π.χ., συμπίεση εικόνας, PDF/A‑2b), και ενσωματώστε το στην υπηρεσία επεξεργασίας εγγράφων σας. Αν χρειάζεστε περισσότερα, εξετάστε τη βιβλιοθήκη PDF‑specific της Aspose για μετα-επεξεργασία ή ψηφιακές υπογραφές. + +Έχετε περισσότερα σενάρια που θέλετε να αντιμετωπίσετε; Μη διστάσετε να αφήσετε ένα σχόλιο ή να δείτε τις άλλες οδηγίες μας για **PDF manipulation**, **image extraction**, και **batch conversion**. Καλή προγραμματιστική! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-shapes/_index.md b/words/greek/net/programming-with-shapes/_index.md index 72cdf30a1a..ff6d2e469a 100644 --- a/words/greek/net/programming-with-shapes/_index.md +++ b/words/greek/net/programming-with-shapes/_index.md @@ -36,7 +36,8 @@ | [Δημιουργία σχήματος ορθογωνίου στο Word με Aspose.Words – Οδηγός βήμα προς βήμα](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Μάθετε πώς να δημιουργήσετε σχήμα ορθογωνίου σε έγγραφο Word χρησιμοποιώντας το Aspose.Words με αναλυτικές οδηγίες. | | [Δημιουργία ορθογωνίου σχήματος στο Word με C# – Οδηγός βήμα‑βήμα](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Μάθετε πώς να δημιουργήσετε ένα ορθογώνιο σχήμα σε έγγραφο Word χρησιμοποιώντας C# με αυτόν τον αναλυτικό οδηγό. | | [Aspose.Words Tutorial Σκιά Σχήματος – Προσθήκη Σκιάς σε Σχήμα Word σε C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Μάθετε πώς να προσθέσετε σκιά σε σχήμα Word χρησιμοποιώντας το Aspose.Words για .NET με C#. | -| [Δημιουργία κενής εγγράφου Word με σχήμα ορθογωνίου με σκιά – Οδηγός βήμα‑προς‑βήμα](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Μάθετε πώς να δημιουργήσετε ένα κενό έγγραφο Word με σχήμα ορθογωνίου με σκιά χρησιμοποιώντας το Aspose.Words για .NET, βήμα‑προς‑βήμα. | +| [Δημιουργία κενής εγγράφου Word με σχήμα ορθογωνίου με σκιά – Οδηγός βήμα‑προς‑βήμα](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Μάθετε πώς να δημιουργήσετε ένα κενό έγγραφο Word με σχήμα ορθογωνίου με σκιά χρησιμοποιώντας Aspose.Words για .NET, βήμα‑προς‑βήμα. | +| [Πώς να μετακινήσετε τη σκιά στο Aspose.Words – Πλήρης οδηγός C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Μάθετε πώς να μετακινήσετε τη σκιά ενός σχήματος σε έγγραφο Word χρησιμοποιώντας Aspose.Words με C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/greek/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..4b347c451d --- /dev/null +++ b/words/greek/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Πώς να μετακινήσετε τη σκιά σε ένα σχήμα στο Aspose.Words χρησιμοποιώντας + C#. Μάθετε πώς να προσθέσετε σκιά σε σχήμα, να αλλάξετε το θολό, να ορίσετε τη διαφάνεια + και να περιστρέψετε τη σκιά σε λίγα λεπτά. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: el +og_description: Πώς να μετακινήσετε τη σκιά σε ένα σχήμα στο Aspose.Words χρησιμοποιώντας + C#. Αυτό το σεμινάριο σας δείχνει πώς να προσθέσετε σκιά σε σχήμα, να αλλάξετε τη + θόλωση, να ορίσετε τη διαφάνεια και να περιστρέψετε τη σκιά. +og_title: Πώς να μετακινήσετε τη σκιά στο Aspose.Words – Πλήρης οδηγός C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Πώς να μετακινήσετε τη σκιά στο Aspose.Words – Πλήρης οδηγός C# +url: /el/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Μετακινήσετε τη Σκιά στο Aspose.Words – Πλήρης Οδηγός C# + +Έχετε αναρωτηθεί ποτέ **πώς να μετακινήσετε τη σκιά** σε ένα σχήμα μέσα σε ένα έγγραφο Word χωρίς να ανοίξετε το Word χειροκίνητα; Στην καθημερινή μου εργασία, χρειάστηκε συχνά να ρυθμίζω τη σκιά ενός σχήματος προγραμματιστικά—είτε για μια επαγγελματική αναφορά είτε για ένα δυναμικό πρότυπο. Τα καλά νέα; Με το Aspose.Words μπορείτε να το κάνετε σε λίγες γραμμές, και θα μάθετε επίσης **add shadow to shape**, **how to change blur**, **how to set transparency**, και **how to rotate shadow** στην ίδια διαδικασία. + +Σε αυτό το tutorial θα περάσουμε από ένα πραγματικό σενάριο: φόρτωση ενός υπάρχοντος DOCX που ήδη περιέχει σχήμα, ρύθμιση της θέσης, της απαλότητας, της διαφάνειας και της κατεύθυνσης της σκιάς, και τέλος αποθήκευση του αποτελέσματος. Στο τέλος θα έχετε ένα επαναχρησιμοποιήσιμο snippet που μπορείτε να ενσωματώσετε σε οποιοδήποτε .NET project, και θα καταλάβετε γιατί κάθε ιδιότητα είναι σημαντική. + +## Προαπαιτούμενα – Τι Χρειάζεστε Πριν Ξεκινήσετε + +- **Aspose.Words for .NET** (έκδοση 23.12 ή νεότερη). Μπορείτε να το αποκτήσετε από το NuGet με `Install-Package Aspose.Words`. +- Ένα περιβάλλον ανάπτυξης .NET 6+ (Visual Studio, VS Code, Rider—ό,τι προτιμάτε). +- Ένα αρχείο Word εισόδου (`input.docx`) που ήδη περιέχει τουλάχιστον ένα σχήμα (ένα ορθογώνιο, κύκλο ή εικόνα αρκεί). +- Βασική εξοικείωση με τη σύνταξη C#—τίποτα περίπλοκο. + +Αν σας λείπει κάτι από αυτά, κάντε μια παύση και εγκαταστήστε τη βιβλιοθήκη· το υπόλοιπο του οδηγού υποθέτει ότι το πακέτο έχει ήδη αναφερθεί. + +## Βήμα 1: Φόρτωση του Εγγράφου και Λήψη του Στόχου Σχήματος – **How to Move Shadow** Ξεκινά Εδώ + +Το πρώτο που κάνουμε είναι να φορτώσουμε το πηγαίο έγγραφο και να εντοπίσουμε το σχήμα που θέλουμε να τροποποιήσουμε. Το Aspose.Words αντιμετωπίζει κάθε αντικείμενο (παράγραφοι, πίνακες, σχήματα) ως κόμβο σε ένα δέντρο, ώστε να μπορούμε να το ερωτήσουμε άμεσα. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Γιατί είναι σημαντικό:** Η φόρτωση του εγγράφου μία φορά και η επαναχρησιμοποίηση της ίδιας παρουσίας `Document` είναι αποδοτική. Η κλήση `GetChild` είναι ασφαλής επειδή επιστρέφει `null` αν το ευρετήριο είναι εκτός εύρους, επιτρέποντάς μας να διαχειριστούμε τις ελλιπείς σκιές με χάρη. + +## Βήμα 2: Ρύθμιση της Ακτίνας Θολώματος – Master **How to Change Blur** + +Μια απαλή σκιά φαίνεται επαγγελματική, ενώ μια σκληρή άκρη μπορεί να φαίνεται φθηνή. Η ιδιότητα `BlurRadius` ελέγχει την απαλότητα σε points (1 pt ≈ 1/72 inch). Ας την αυξήσουμε στα 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** Η προεπιλεγμένη τιμή θολώματος είναι 0.5 pt. Οτιδήποτε πάνω από 5 pt είναι συνήθως ορατό, αλλά προσέξτε να μην το κάνετε πολύ μεγάλο—μπορεί να κάνει το σχήμα να φαίνεται αποσπασμένο από τη σελίδα. + +## Βήμα 3: Ορισμός Διαφάνειας – Η Απάντηση στο **How to Set Transparency** + +Η διαφάνεια καθορίζει πόσο διαυγής είναι η σκιά. Μια τιμή `0` σημαίνει πλήρως αδιαφανής· `1` σημαίνει εντελώς αόρατη. Για ένα διακριτικό αποτέλεσμα θα χρησιμοποιήσουμε `0.3` (30 % διαφάνεια). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Γιατί μπορεί να σας ενδιαφέρει:** Αν το σχήμα είναι σκούρο, μια πλήρως αδιαφανής σκιά μπορεί να καταπνίξει το κείμενο που βρίσκεται από κάτω. Η ρύθμιση της διαφάνειας διατηρεί το έγγραφο ευανάγνωστο ενώ προσθέτει βάθος. + +## Βήμα 4: Μετακίνηση της Σκιάς – Ο Πυρήνας του **How to Move Shadow** + +Η ιδιότητα `Distance` ορίζει πόσο μακριά είναι η σκιά από το σχήμα, μετρημένη σε points. Μεγαλύτερη απόσταση σπρώχνει τη σκιά πιο μακριά, δημιουργώντας πιο δραματικό εφέ. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Τι γίνεται αν χρειάζεστε μικρή μετατόπιση;** Ορίζοντας το `Distance` σε `0` η σκιά θα βρίσκεται ακριβώς πίσω από το σχήμα, κάτι που μπορεί να είναι χρήσιμο για εφέ ανάγλυφου. + +## Βήμα 5: Περιστροφή της Πηγής Φωτός – Λύση στο **How to Rotate Shadow** + +Οι σκιές δεν είναι μόνο κάθετες· ακολουθούν τη γωνία της πηγής φωτός. Η ιδιότητα `Angle` (σε μοίρες) περιστρέφει τη σκιά γύρω από το σχήμα. Ας την κλίνουμε κατά 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Γρήγορο πείραμα:** Δοκιμάστε `90` για σκιά δεξιά ή `-30` για σκιά αριστερά. Η οπτική αλλαγή είναι άμεση. + +## Βήμα 6: Αποθήκευση του Εγγράφου – Δες το Αποτέλεσμα του **Add Shadow to Shape** + +Τώρα που έχουμε ρυθμίσει τη σκιά, θα γράψουμε το έγγραφο ξανά στο δίσκο. Μπορείτε να αντικαταστήσετε το αρχικό ή να δημιουργήσετε νέο αρχείο· το παράδειγμα χρησιμοποιεί νέο αρχείο εξόδου. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Αναμενόμενο αποτέλεσμα:** Ανοίξτε το `output.docx`. Η σκιά του σχήματος θα εμφανίζεται πιο απαλή, ελαφρώς μετατοπισμένη, ημιδιαφανής και με γωνία 45°. Αν το συγκρίνετε πλάι‑πλάι με το `input.docx`, η διαφορά είναι αδιαμφισβήτητη. + +### Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή) + +Παρακάτω βρίσκεται ολόκληρο το πρόγραμμα σε ένα μπλοκ. Επικολλήστε το σε ένα νέο κονσόλα project, αντικαταστήστε το `YOUR_DIRECTORY` με πραγματική διαδρομή φακέλου και τρέξτε. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### Τι γίνεται αν το έγγραφο έχει πολλά σχήματα; + +Μπορείτε να κάνετε βρόχο σε όλα τα σχήματα: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Μπορώ να προσθέσω σκιά σε σχήμα που δεν έχει καμία; + +Απολύτως. Το αντικείμενο `ShadowFormat` υπάρχει πάντα· χρειάζεται μόνο να το ενεργοποιήσετε: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Λειτουργεί αυτό με εικόνες και SmartArt; + +Ναι. Οποιοσδήποτε κόμβος κληρονομεί από το `Shape`—συμπεριλαμβανομένων εικόνων, διαγραμμάτων και SmartArt—εκθέτει το `ShadowFormat`. Οι ίδιες ιδιότητες ισχύουν. + +### Πώς ελέγχω το χρώμα της σκιάς; + +Χρησιμοποιήστε την ιδιότητα `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Ανησυχίες συμβατότητας; + +Το Aspose.Words 23.12+ υποστηρίζει .NET 6, .NET Core 3.1 και .NET Framework 4.6.2+. Το API που παρουσιάζεται είναι σταθερό σε αυτές τις εκδόσεις. + +## Συμπέρασμα + +Μόλις καλύψαμε **πώς να μετακινήσετε τη σκιά** σε ένα σχήμα χρησιμοποιώντας το Aspose.Words, και παράλληλα δείξαμε **add shadow to shape**, **how to change blur**, **how to set transparency**, και **how to rotate shadow**. Το πλήρες, εκτελέσιμο παράδειγμα σας επιτρέπει να ρυθμίσετε τη σκιά οποιουδήποτε σχήματος σε δευτερόλεπτα, δίνοντας στα έγγραφά σας μια γυαλιστερή, επαγγελματική εμφάνιση χωρίς ποτέ να ανοίξετε το Word. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να συνδυάσετε αυτές τις ρυθμίσεις σκιάς με **conditional formatting**—για παράδειγμα, εφαρμόζοντας πιο έντονη σκιά μόνο σε επικεφαλίδες ή σε διαγράμματα που υπερβαίνουν κάποιο μέγεθος. Ή εξερευνήστε **gradient fills** για το ίδιο το σχήμα ώστε να δημιουργήσετε ένα πραγματικά εντυπωσιακό σχέδιο. + +Αν αντιμετωπίσετε δυσκολίες, αφήστε ένα σχόλιο παρακάτω. Καλή προγραμματιστική δουλειά, και οι σκιές σας να πέφτουν πάντα εκεί που θέλετε! + +![Διάγραμμα που δείχνει το αποτέλεσμα της μετακίνησης μιας σκιάς σε ένα σχήμα – παράδειγμα πώς να μετακινήσετε τη σκιά](https://example.com/images/shadow-demo.png "παράδειγμα πώς να μετακινήσετε τη σκιά") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/basic-conversions/_index.md b/words/hindi/net/basic-conversions/_index.md index 3360b70d7c..e1637382a0 100644 --- a/words/hindi/net/basic-conversions/_index.md +++ b/words/hindi/net/basic-conversions/_index.md @@ -22,20 +22,21 @@ | शीर्षक | विवरण | | --- | --- | | [Docx को Docx में बदलें](./doc-to-docx/) | .NET के लिए Aspose.Words का उपयोग करके DOC को DOCX में बदलने का तरीका जानें। कोड उदाहरणों के साथ चरण-दर-चरण मार्गदर्शिका। डेवलपर्स के लिए बिल्कुल सही। | -| [Docx को Rtf में बदलें](./docx-to-rtf/) | हमारे चरण-दर-चरण गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को RTF में परिवर्तित करना सीखें। सहज दस्तावेज़ प्रसंस्करण के लिए आसान रूपांतरण। | +| [Docx को Rtf में बदलें](./docx-to-rtf/) | हमारे चरण-दर-स्टेप गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को RTF में परिवर्तित करना सीखें। सहज दस्तावेज़ प्रसंस्करण के लिए आसान रूपांतरण। | | [वर्ड फ़ाइल को पीडीएफ में बदलें](./docx-to-pdf/) हमारे गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके आसानी से Word फ़ाइलों को PDF में कनवर्ट करना सीखें। त्वरित और विश्वसनीय दस्तावेज़ रूपांतरण चाहने वाले डेवलपर्स के लिए बिल्कुल सही। | -| [Docx को बाइट में बदलें](./docx-to-byte/) | कुशल दस्तावेज़ प्रसंस्करण के लिए Aspose.Words का उपयोग करके .NET में Docx को बाइट सरणी में परिवर्तित करना सीखें। चरण-दर-चरण मार्गदर्शिका शामिल है। | +| [Docx को बाइट में बदलें](./docx-to-byte/) | कुशल दस्तावेज़ प्रसंस्करण के लिए Aspose.Words का उपयोग करके .NET में Docx को बाइट सरणी में परिवर्तित करना सीखें। चरण-दर-स्टेप मार्गदर्शिका शामिल है। | | [Docx को Epub में बदलें](./docx-to-epub/) | .NET के लिए Aspose.Words के साथ आसानी से DOCX को EPUB में बदलें। अपने .NET अनुप्रयोगों में सहज एकीकरण के लिए हमारे ट्यूटोरियल का पालन करें। | -| [Docx को Mhtml में बदलें और ईमेल भेजें](./docx-to-mhtml-and-sending-email/) | इस चरण-दर-चरण मार्गदर्शिका में जानें कि DOCX को MHTML में कैसे बदलें और .NET के लिए Aspose.Words का उपयोग करके ईमेल कैसे भेजें। आसान स्वचालन के साथ अपनी उत्पादकता बढ़ाएँ। | +| [Docx को Mhtml में बदलें और ईमेल भेजें](./docx-to-mhtml-and-sending-email/) | इस चरण-दर-स्टेप मार्गदर्शिका में जानें कि DOCX को MHTML में कैसे बदलें और .NET के लिए Aspose.Words का उपयोग करके ईमेल कैसे भेजें। आसान स्वचालन के साथ अपनी उत्पादकता बढ़ाएँ। | | [Docx फ़ाइल को Markdown में बदलें](./docx-to-markdown/) | .NET के लिए Aspose.Words का उपयोग करके DOCX फ़ाइलों को Markdown में परिवर्तित करना सीखें। अपने .NET अनुप्रयोगों में सहज एकीकरण के लिए हमारी विस्तृत मार्गदर्शिका का पालन करें। | -| [Docx को Txt में बदलें](./docx-to-txt/) हमारे चरण-दर-चरण गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को TXT में बदलें। दस्तावेज़ों को कुशलतापूर्वक और आसानी से बदलना सीखें। | +| [Docx को Txt में बदलें](./docx-to-txt/) हमारे चरण-दर-स्टेप गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को TXT में बदलें। दस्तावेज़ों को कुशलतापूर्वक और आसानी से बदलना सीखें। | | [टेक्स्ट फ़ाइल को वर्ड डॉक्यूमेंट में बदलें](./txt-to-docx/) | .NET के लिए Aspose.Words का उपयोग करके टेक्स्ट फ़ाइलों को Word दस्तावेज़ों में परिवर्तित करना सीखें। हमारे व्यापक गाइड के साथ दस्तावेज़ रूपांतरणों को कुशलतापूर्वक प्रबंधित करें। | | [पीडीएफ को जेपीईजी के रूप में सहेजें](./pdf-to-jpeg/) | .NET के लिए Aspose.Words का उपयोग करके PDF को JPEG में आसानी से बदलें। उदाहरणों और FAQ के साथ हमारी विस्तृत मार्गदर्शिका का पालन करें। डेवलपर्स और उत्साही लोगों के लिए बिल्कुल सही। | -| [पीडीएफ को वर्ड फॉर्मेट में सहेजें (Docx)](./pdf-to-docx/) | इस विस्तृत, चरण-दर-चरण मार्गदर्शिका में जानें कि .NET के लिए Aspose.Words का उपयोग करके PDF को Word दस्तावेज़ (Docx) में कैसे परिवर्तित किया जाए। डेवलपर्स के लिए बिल्कुल सही। | +| [पीडीएफ को वर्ड फॉर्मेट में सहेजें (Docx)](./pdf-to-docx/) | इस विस्तृत, चरण-दर-स्टेप मार्गदर्शिका में जानें कि .NET के लिए Aspose.Words का उपयोग करके PDF को Word दस्तावेज़ (Docx) में कैसे परिवर्तित किया जाए। डेवलपर्स के लिए बिल्कुल सही। | | [Word से LaTeX निर्यात कैसे करें – चरण‑दर‑चरण मार्गदर्शिका](./how-to-export-latex-from-word-step-by-step-guide/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ से LaTeX फ़ॉर्मेट में निर्यात करने का चरण‑दर‑चरण मार्गदर्शन। | | [C# में Aspose.Words का उपयोग करके वर्ड को PDF में बदलें – गाइड](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | C# में Aspose.Words से Word फ़ाइल को PDF में बदलने की चरण‑दर‑स्टेप गाइड। | | [Aspose.Words के साथ Word को PDF के रूप में सहेजें – पूर्ण C# गाइड](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words का उपयोग करके C# में Word फ़ाइल को PDF में सहेजने की पूरी गाइड। | | [Aspose.Words के साथ docx को pdf के रूप में सहेजें – पूर्ण C# गाइड](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | .NET के लिए Aspose.Words का उपयोग करके Docx को PDF में बदलने की पूरी C# गाइड। चरण‑दर‑स्टेप मार्गदर्शन। | +| [Aspose.Words के साथ Word को PDF के रूप में सहेजें – पूर्ण गाइड](./save-word-as-pdf-with-aspose-words-complete-guide/) | Aspose.Words का उपयोग करके .NET में Word फ़ाइल को PDF में बदलने की पूरी गाइड। चरण‑दर‑स्टेप उदाहरण और कोड सहित। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/hindi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index a3ef5e9aef..348dba585b 100644 --- a/words/hindi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/hindi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Aspose.Words का उपयोग करके Word से LaTeX निर्यात कैसे करें – Word को - LaTeX में बदलना सीखें, docx को txt के रूप में सहेजें, और साधारण पाठ में समीकरणों - को संभालें। +date: 2026-05-01 +description: C# में Aspose.Words का उपयोग करके Word फ़ाइल से LaTeX निर्यात करना, Word + को txt में बदलना, और तालिकाओं को संरक्षित करना सीखें। draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: hi -og_description: Aspose.Words के साथ Word से LaTeX निर्यात कैसे करें। यह गाइड आपको - दिखाता है कि Word को LaTeX में कैसे बदलें, docx को txt के रूप में सहेजें, और समीकरणों - को अपरिवर्तित रखें। -og_title: Word से LaTeX कैसे निर्यात करें – त्वरित C# ट्यूटोरियल +og_description: Aspose.Words के साथ Word से LaTeX निर्यात करना, Word को साधारण टेक्स्ट + में बदलना और तालिका लेआउट को अपरिवर्तित रखना कैसे खोजें। +og_title: Word से LaTeX निर्यात कैसे करें – पूर्ण C# ट्यूटोरियल tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: वर्ड से LaTeX निर्यात कैसे करें – चरण‑दर‑चरण मार्गदर्शिका url: /hi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,162 +26,215 @@ url: /hi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Word से LaTeX निर्यात कैसे करें – चरण‑दर‑चरण गाइड +# Word से LaTeX निर्यात कैसे करें – पूर्ण C# ट्यूटोरियल -क्या आपने कभी सोचा है **Word से LaTeX कैसे निर्यात करें** बिना उन जटिल Office Math समीकरणों को खोए? आप अकेले नहीं हैं। कई डेवलपर्स को अकादमिक पेपर, वैज्ञानिक रिपोर्ट, या स्वचालित प्रकाशन पाइपलाइन के लिए *Word को LaTeX में बदलने* की कोशिश में बाधा आती है। +क्या आपने कभी सोचा है **LaTeX को कैसे निर्यात करें** एक Word दस्तावेज़ से बिना किसी गणितीय समीकरण को खोए? आप अकेले नहीं हैं। कई डेवलपर्स को .docx जिसमें Office Math हो, उसे साफ़ LaTeX में बदलना पड़ता है और साथ ही **Word को txt में बदलें** आगे की प्रोसेसिंग के लिए। इस गाइड में हम एक व्यावहारिक, तैयार‑चलाने‑योग्य समाधान दिखाएंगे जो **टेबल्स को संरक्षित** रखता है, आपको एक साधारण‑पाठ फ़ाइल देता है, और LaTeX मार्कअप को ठीक उसी जगह रखता है जहाँ आपको चाहिए। -इस ट्यूटोरियल में हम एक पूर्ण, तैयार‑चलाने योग्य C# उदाहरण के माध्यम से चलेंगे जो Aspose.Words का उपयोग करके **LaTeX निर्यात कैसे करें** दिखाता है, **txt फ़ाइलें कैसे सहेजें** LaTeX मार्कअप के साथ, और यहाँ तक कि **Word समीकरणों को LaTeX में बदलने** की बारीकियों को कवर करता है ताकि अनुवाद में कुछ भी न खोए। - -> **Pro tip:** यही तरीका आपके किसी भी .docx के लिए काम करता है—सिर्फ कोड को किसी अलग फ़ाइल पथ पर इंगित करें। - ---- +हम फ़ाइल लोड करने से लेकर `TxtSaveOptions` को इस तरह ट्यून करने तक सब कुछ कवर करेंगे कि आउटपुट मानव‑पठनीय और मशीन‑अनुकूल दोनों हो। अंत तक आप **docx को txt के रूप में सहेजें**, **Word को साधारण पाठ में बदलें**, और **टेबल्स को कैसे संरक्षित रखें** जान पाएँगे। कोई बाहरी स्क्रिप्ट नहीं, कोई मैन्युअल कॉपी‑पेस्ट नहीं—सिर्फ शुद्ध C# कोड जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। ## आपको क्या चाहिए -शुरू करने से पहले, सुनिश्चित करें कि आपके पास निम्नलिखित आवश्यकताएँ हैं: - -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words आधुनिक .NET रनटाइम्स को लक्षित करता है। | - **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | यह लाइब्रेरी Word को पार्स करने और LaTeX उत्पन्न करने का भारी काम करती है। | -| **A sample .docx** containing at least one Office Math equation | LaTeX रूपांतरण को क्रिया में देखने के लिए। | -| **Visual Studio 2022** (or any IDE you like) | डिबगिंग और नमूना चलाने को सरल बनाता है। | - -यदि आपने अभी तक NuGet पैकेज स्थापित नहीं किया है, तो चलाएँ: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (नवीनतम संस्करण, 2024.x या उससे नया)। NuGet पैकेज `Aspose.Words` है। +- एक .NET विकास वातावरण (Visual Studio, VS Code, Rider—जो भी हो)। +- एक Word फ़ाइल (`.docx`) जिसमें Office Math समीकरण और कम से कम एक टेबल हो (ताकि हम टेबल‑संरक्षण जादू देख सकें)। -बस इतना ही—कोई अतिरिक्त DLLs नहीं, कोई COM इंटरऑप नहीं, सिर्फ एक साफ़ मैनेज्ड लाइब्रेरी। +बस इतना ही। अगर आपके पास ये सब है, तो पढ़ते रहें; अन्यथा NuGet पैकेज और एक नमूना DOCX प्राप्त करें और आगे बढ़ें। -## Word से LaTeX निर्यात – अवलोकन - -नीचे वह बड़ी तस्वीर है जो हम हासिल करेंगे: +--- -1. **Load** स्रोत Word दस्तावेज़ (`.docx`). -2. **Configure** `TxtSaveOptions` ताकि कोई भी Office Math ऑब्जेक्ट LaTeX कोड के रूप में निकाले जाएँ। -3. **Save** दस्तावेज़ को plain‑text (`.txt`) फ़ाइल के रूप में सहेजें जिसे आप सीधे किसी भी LaTeX कंपाइल में फीड कर सकते हैं। +## Word दस्तावेज़ से LaTeX निर्यात करने का तरीका -![Word से LaTeX निर्यात का उदाहरण](image.png "Word से LaTeX निर्यात") +नीचे ट्यूटोरियल का मुख्य भाग है—तीन संक्षिप्त कदम जो प्रश्न **LaTeX को कैसे निर्यात करें** का उत्तर देते हैं और साथ ही **Word को txt में बदलें**, **Word को साधारण पाठ में बदलें**, **docx को txt के रूप में सहेजें**, और **टेबल्स को कैसे संरक्षित रखें** को भी संभालते हैं। -## चरण 1: Word दस्तावेज़ लोड करें +### चरण 1: DOCX फ़ाइल लोड करें -सबसे पहले—उस .docx को खोलें जिसे आप बदलना चाहते हैं। `Document` क्लास सभी अंतर्निहित XML को अमूर्त बनाकर आपको एक उपयोगकर्ता‑मित्र ऑब्जेक्ट मॉडल देती है। +सबसे पहले हमें Word दस्तावेज़ को `Aspose.Words.Document` ऑब्जेक्ट में पढ़ना होगा। यह कदम वही रहता है चाहे आप बाद में **Word को txt में बदलें** या **docx को txt के रूप में सहेजें**। ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**यह क्यों महत्वपूर्ण है:** -फ़ाइल को पहले लोड करने से हमें उसकी सामग्री (जैसे, समीकरणों की गिनती) का निरीक्षण करने मिलता है इससे पहले कि हम तय करें कि इसे कैसे सीरियलाइज़ करें। यदि फ़ाइल भ्रष्ट है, तो `Document` एक स्पष्ट अपवाद फेंकेगा, जिससे बाद में रहस्यमय आउटपुट से बचा जा सके। +> **यह क्यों महत्वपूर्ण है:** फ़ाइल को लोड करने से सभी Word तत्वों—पैराग्राफ, टेबल, और Office Math ऑब्जेक्ट्स—की इन‑मेमोरी प्रतिनिधित्व बनती है। इस ऑब्जेक्ट के बिना आप निर्यात विकल्पों को नहीं बदल सकते। + +### चरण 2: LaTeX और टेबल लेआउट के लिए `TxtSaveOptions` कॉन्फ़िगर करें -## चरण 2: LaTeX निर्यात के लिए TxtSaveOptions कॉन्फ़िगर करें +`TxtSaveOptions` क्लास आपको यह नियंत्रित करने देती है कि साधारण‑पाठ फ़ाइल कैसे जेनरेट होगी। हमारे परिदृश्य के लिए दो प्रॉपर्टी मुख्य हैं: -`TxtSaveOptions` में जादू होता है। `OfficeMathExportMode` को `LaTeX` सेट करके, प्रत्येक Office Math ऑब्जेक्ट को उसके संबंधित LaTeX प्रतिनिधित्व में बदल दिया जाता है। +| Property | क्या करता है | आपको इसकी आवश्यकता क्यों है | +|----------|--------------|-----------------------------| +| `OfficeMathExportMode` | Office Math को कैसे रेंडर किया जाए, निर्धारित करता है। इसे `LaTeX` पर सेट करने से समीकरण LaTeX सिंटैक्स में बदल जाते हैं। | यह **LaTeX को कैसे निर्यात करें** का मूल है। | +| `PreserveTableLayout` | जब `true` हो, Aspose व्हाइटस्पेस जोड़ता है ताकि टेबल्स ग्रिड‑जैसा दिखें। | यह **टेबल्स को कैसे संरक्षित रखें** को पूरा करता है जबकि आप **Word को txt में बदलें**। | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**हम इन सेटिंग्स को क्यों चुनते हैं:** +> **प्रो टिप:** यदि आपको केवल कच्चा LaTeX चाहिए बिना किसी टेबल फ़ॉर्मेटिंग के, तो `PreserveTableLayout` को `false` सेट करें। फ़ाइल छोटी होगी, पर आप दृश्य टेबल संकेत खो देंगे। + +### चरण 3: दस्तावेज़ को साधारण पाठ में सहेजें + +अब हम दस्तावेज़ को `.txt` फ़ाइल में लिखते हैं, वह विकल्प उपयोग करके जो हमने अभी परिभाषित किए हैं। यह एक ही पंक्ति **Word को साधारण पाठ में बदलें**, **docx को txt के रूप में सहेजें**, और बेशक **LaTeX को कैसे निर्यात करें** को एक साथ पूरा करती है। -- `OfficeMathExportMode.LaTeX` एकमात्र मोड है जो सटीक गणितीय अनुवाद की गारंटी देता है। -- `PreserveTableLayout` तालिकाओं को Word में जैसे दिखते हैं वैसे ही रखता है, जो बाद में आउटपुट को LaTeX `tabular` वातावरण में एम्बेड करने पर उपयोगी होता है। -- UTF‑8 सुनिश्चित करता है कि “α”, “β”, या “∑” जैसे अक्षर राउंड‑ट्रिप में बचें। +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` -यदि आपको कभी **Word को LaTeX में बदलने** की आवश्यकता पड़े बिना plain‑text रैपर के, तो आप `SaveFormat.LaTeX` पर स्विच कर सकते हैं—उन्नत परिदृश्यों के लिए एक त्वरित टिप। +कॉल समाप्त होने के बाद, `output.txt` खोलें। आपको दिखेगा: -## चरण 3: दस्तावेज़ को टेक्स्ट फ़ाइल के रूप में सहेजें +- प्रत्येक Office Math समीकरण के लिए `\frac{a}{b}` जैसे LaTeX स्निपेट। +- `|` और `-` अक्षरों से रेंडर की गई टेबल्स, कॉलम संरेखण बनाए रखती हैं। +- साधारण पैराग्राफ़ साधारण पाठ में, जो किसी भी डाउनस्ट्रीम पार्सर के लिए तैयार हैं। -अब हम LaTeX‑समृद्ध टेक्स्ट को डिस्क पर लिखते हैं। परिणामी `.txt` को बाद में `.tex` में नाम बदल सकते हैं, या सीधे LaTeX कंपाइलर में पाइप कर सकते हैं। +### पूर्ण कार्यशील उदाहरण -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +सब कुछ एक साथ मिलाकर, यहाँ एक स्व-निहित प्रोग्राम है जिसे आप आज ही कंपाइल और रन कर सकते हैं: -// Save using the configured options -doc.Save(outputPath, txtOptions); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**आप `output.txt` में क्या देखेंगे:** +**अपेक्षित आउटपुट** (एक अंश): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -सभी अन्य पैराग्राफ़ प्लेन टेक्स्ट के रूप में दिखेंगे, जबकि कोई भी Office Math समीकरण LaTeX `equation` वातावरण में लिपटा होगा (या `inline` यदि वह Word में इनलाइन था)। यह **Word समीकरणों को LaTeX में बदलने** की आवश्यकता को पूरी तरह पूरा करता है। +ध्यान दें कि टेबल अपना ग्रिड रखता है और समीकरण साफ़ LaTeX के रूप में दिखता है। यही वह संतुलन है जब आप **Word को txt में बदलें** और साथ ही संरचना व गणित दोनों का सटीक प्रतिनिधित्व चाहते हैं। + +--- - किनारे के मामलों और सामान्य प्रश्न +## Word को TXT में बदलने और टेबल्स को संरक्षित रखने के टिप्स -| Situation | What to do | -|-----------|------------| -| **No equations in the source** | रूपांतरण अभी भी काम करता है; आपको केवल प्लेन टेक्स्ट मिलेगा। कोई अतिरिक्त LaTeX कोड नहीं जोड़ा जाता। | -| **Very large documents (>100 MB)** | `MemoryStream` का उपयोग करके आउटपुट को स्ट्रीम करने पर विचार करें ताकि उच्च मेमोरी उपयोग से बचा जा सके। | -| **Unsupported Math constructs** | Aspose.Words Office Math का 99 % कवर करता है। दुर्ल किनारे के मामले में, आपको LaTeX को मैन्युअली पोस्ट‑प्रोसेस करना पड़ सकता है। | -| **Need a .tex file instead of .txt** | `outputPath` को `.tex` पर समाप्त करने के लिए बदलें और वैकल्पिक रूप से `txtOptions.Encoding` को `Encoding.UTF8` सेट करें। | -| **Running on Linux/macOS** | कोड वही काम करता है—सिर्फ सुनिश्चित करें कि फ़ाइल पथ फॉरवर्ड स्लैश या `Path.Combine` का उपयोग करें। | +तीन‑कदम वाला तरीका अधिकांश मामलों में काम करता है, पर वास्तविक प्रोजेक्ट अक्सर चुनौतियाँ लाते हैं। नीचे व्यावहारिक सुझाव हैं जो आपके **Word को साधारण पाठ में बदलें** पाइपलाइन को मजबूत बनाते हैं। -## LaTeX समीकरणों के साथ TXT सहेजने का त्वरित सारांश +### सुसंगत एन्कोडिंग का उपयोग करें -1. **Load** .docx (`Document`). -2. `TxtSaveOptions` में `OfficeMathExportMode = LaTeX` सेट करें। -3. इन विकल्पों के साथ फ़ाइल (`doc.Save`) सहेजें। +`TxtSaveOptions` डिफ़ॉल्ट रूप से UTF‑8 है, जो अधिकांश अक्षरों को संभालता है। यदि आपको कोई अलग कोड पेज चाहिए (जैसे लेगेसी सिस्टम जो Windows‑1252 अपेक्षित रखते हैं), तो `Encoding` प्रॉपर्टी सेट करें: -यह पूरी कार्यप्रवाह है **txt फ़ाइलें कैसे सहेजें** जिनमें LaTeX‑फ़ॉर्मेटेड समीकरण हों। +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -## बोनस: कई फ़ाइलों के लिए रूपांतरण को स्वचालित करना +### अतिरिक्त व्हाइटस्पेस को ट्रिम करें -यदि आपके पास Word दस्तावेज़ों से भरा फ़ोल्डर है, तो ऊपर की लॉजिक को एक सरल लूप में लपेटें: +कई कॉलम वाली टेबल्स लंबी लाइनों का उत्पादन कर सकती हैं। सहेजने के बाद आप फ़ाइल को पोस्ट‑प्रोसेस करके कई स्पेस को एक टैब में बदल सकते हैं: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### नेस्टेड टेबल्स को संभालें + +यदि आपके DOCX में टेबल के अंदर टेबल है, तो `PreserveTableLayout` अभी भी दृश्य पदानुक्रम रखेगा, पर इंडेंटेशन अजीब दिख सकता है। एक त्वरित समाधान है अग्रणी स्पेस को कस्टम मार्कर (जैसे `>>`) से बदलना ताकि डाउनस्ट्रीम पार्सर नेस्टिंग लेवल पहचान सके। + +### कई फ़ाइलों की बैच प्रोसेसिंग + +जब आपको दहियों दस्तावेज़ों के लिए **Word को txt में बदलें** करना हो, तो लॉजिक को लूप में रखें: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -अब आप **Word को LaTeX में बदल सकते** हैं बल्क में—दैनिक दर्जनों पांडुलिपियों प्राप्त करने वाले शोध समूहों के लिए उत्तम। +इस तरह आप **docx को txt के रूप में सहेजें** बड़े पैमाने पर बिना मैन्युअल हस्तक्षेप के कर सकते हैं। + +--- + +## सामान्य समस्याएँ और उनके समाधान + +1. **LaTeX निर्यात मोड नहीं सेट किया** – यदि आप `OfficeMathExportMode = OfficeMathExportMode.LaTeX` सेट करना भूल जाते हैं, तो समीकरण साधारण पाठ में बदल जाएंगे (जैसे “Equation 1”)। हमेशा विकल्प ब्लॉक को दोबारा जांचें। +2. **टेबल लेआउट खो गया** – डिफ़ॉल्ट रूप से `PreserveTableLayout` `false` रहता है। यदि आपका आउटपुट एक दीवार‑समान पाठ जैसा दिख रहा है, तो संभवतः आपने फ़्लैग नहीं बदला। +3. **स्पेस वाले फ़ाइल पाथ** – रॉ स्ट्रिंग (`@"C:\My Folder\input.docx"`) का उपयोग करने से एस्केप समस्याएँ नहीं आतीं। अन्यथा `FileNotFoundException` मिल सकता है। +4. **वर्ज़न असंगति** – पुराने Aspose.Words संस्करण (< 21.9) `OfficeMathExportMode` को सपोर्ट नहीं करते। नवीनतम पैकेज पर अपग्रेड करें ताकि **LaTeX को कैसे निर्यात करें** काम करे। +5. **गैर‑ASCII अक्षरों की एन्कोडिंग त्रुटि** – यदि आप � प्रतीक देखते हैं, तो स्पष्ट रूप से `options.Encoding` को UTF‑8 या उपयुक्त कोड पेज पर सेट करें। + +--- + +## समाधान का विस्तार: TXT से Markdown या HTML तक + +कभी‑कभी आपको साधारण पाठ से अधिक चाहिए—शायद एक Markdown फ़ाइल जिसमें अभी भी LaTeX ब्लॉक हों। वही `TxtSaveOptions` को `HtmlSaveOptions` या `MarkdownSaveOptions` से बदलें: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +यह छोटा परिवर्तन आपको **Word को txt‑स्टाइल आउटपुट** देता है जबकि वह Markdown सिंटैक्स भी रखता है जिसे आप पसंद करते हैं। + +--- ## निष्कर्ष -हमने **Word से LaTeX निर्यात कैसे करें** चरण‑दर‑चरण कवर किया, **txt फ़ाइलें कैसे सहेजें** जो हर Office Math समीकरण को संरक्षित रखती हैं, और यहाँ तक कि दिखाया कि **Word समीकरणों को LaTeX में बदलें** बिना किसी सटीकता के नुकसान के। +हमने **LaTeX को कैसे निर्यात करें** का एक पूर्ण, प्रोडक्शन‑रेडी उत्तर दिया, साथ ही दिखाया कि **Word को txt में बदलें**, **Word को साधारण पाठ में बदलें**, **docx को txt के रूप में सहेजें**, और **टेबल्स को कैसे संरक्षित रखें**। मुख्य बिंदु: + +- `Aspose.Words.Document` से DOCX लोड करें। +- `TxtSaveOptions.OfficeMathExportMode = LaTeX` और `PreserveTableLayout = true` सेट करें। +- `doc.Save(outputPath, options)` को कॉल करके साफ़ LaTeX‑समृद्ध साधारण‑पाठ फ़ाइल प्राप्त करें। -केवल कुछ पंक्तियों के C# कोड और शक्तिशाली Aspose.Words लाइब्रेरी के साथ, आप किसी भी .docx को LaTeX‑तैयार टेक्स्ट में बदल सकते हैं, जो वैज्ञानिक पत्रों, पाठ्यपुस्तकों, या स्वचालित प्रकाशन पाइपलाइनों में सम्मिलित करने के लिए तैयार है। +इसे अपने फ़ाइलों पर आज़माएँ, एन्कोडिंग ट्यूनिंग के साथ प्रयोग करें, और फ़ोल्डर‑स्तर पर बैच‑प्रोसेसिंग करें। यदि आप नेस्टेड टेबल्स, विदेशी अक्षर, या पुराने Aspose संस्करण जैसी किनारी स्थितियों से मिलते हैं, तो “टिप्स” और “सामान्य समस्याएँ” सेक्शन में बताए गए त्वरित समाधान देखें। -**अगले कदम?** उत्पन्न `.txt` (या इसे `.tex` में नाम बदलें) को `pdflatex` या `xelatex` में फीड करके PDF बनाएं, या सीधे `.tex` फ़ाइल के लिए `SaveFormat.LaTeX` विकल्प का अन्वेषण करें। यदि आपको **docx को txt के रूप में सहेजना** है जबकि फ़ॉर्मेटिंग को संरक्षित रखना है, तो `PreserveTableLayout` और कस्टम लाइन‑ब्रेक हैंडलिंग के साथ प्रयोग करें। +अगला कदम? वही DOCX को Markdown में बदलें, या उत्पन्न `.txt` को किसी स्थैतिक‑साइट जेनरेटर में फ़ीड करें जो वेब पर LaTeX रेंडर करता हो। संभावनाएँ अनंत हैं, और अब आपके पास किसी भी **Word को txt में बदलें** वर्कफ़्लो के लिए ठोस आधार है। -किनारे के मामलों, लाइसेंसिंग, या प्रदर्शन समायोजन के बारे में प्रश्न हैं? नीचे टिप्पणी छोड़ें—हैी कोडिंग! +कोडिंग का आनंद लें, और आपका LaTeX हमेशा पहली कोशिश में ही कम्पाइल हो! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/hindi/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/hindi/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..0fa7873116 --- /dev/null +++ b/words/hindi/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words का उपयोग करके C# में Word को PDF के रूप में सहेजें। docx + को PDF में बदलना सीखें, गायब फ़ॉन्ट्स का पता लगाएँ और फ़ॉन्ट प्रतिस्थापन चेतावनियों + को कुशलतापूर्वक संभालें। +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: hi +og_description: Aspose.Words का उपयोग करके Word को PDF के रूप में सहेजें। यह चरण-दर-चरण + ट्यूटोरियल दिखाता है कि docx को pdf में कैसे बदलें और गायब फ़ॉन्ट्स का पता कैसे + लगाएँ। +og_title: Aspose.Words के साथ Word को PDF में सहेजें – पूर्ण गाइड +tags: +- Aspose.Words +- C# +- PDF conversion +title: Aspose.Words के साथ Word को PDF में सहेजें – पूर्ण मार्गदर्शिका +url: /hi/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words के साथ Word को PDF में सहेजें – पूर्ण गाइड + +क्या आपको कभी तुरंत **save Word as PDF** करने की ज़रूरत पड़ी है और सोचा है कि क्या इस प्रक्रिया में कोई फ़ॉन्ट छूट जाएगा? आप अकेले नहीं हैं—डेवलपर्स अक्सर दस्तावेज़ बदलते समय मिसिंग‑फ़ॉन्ट की समस्याओं से जूझते हैं। इस गाइड में हम एक व्यावहारिक समाधान पर चर्चा करेंगे जो न केवल **convert docx to pdf** करता है बल्कि Aspose.Words की फ़ॉन्ट‑सब्स्टिट्यूशन वार्निंग्स का उपयोग करके **detect missing fonts** भी करता है। + +हम सब कुछ कवर करेंगे, चेतावनी कलेक्टर सेट करने से लेकर आउटपुट को समझने तक, ताकि अंत तक आप बिल्कुल जान सकें कि **save Word as PDF** कैसे बिना किसी आश्चर्य के किया जाए। कोई बाहरी टूल नहीं, कोई जटिल सेटिंग नहीं—सिर्फ साफ़ C# कोड जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +## आप को क्या चाहिए + +- **Aspose.Words for .NET** (नवीनतम संस्करण, उदाहरण के लिए 24.10) – आप इसे NuGet के माध्यम से प्राप्त कर सकते हैं (`Install-Package Aspose.Words`). +- एक .NET विकास पर्यावरण (Visual Studio, Rider, या VS Code काम करता है)। +- एक नमूना DOCX फ़ाइल जिसमें लक्ष्य मशीन पर स्थापित न किए गए फ़ॉन्ट हो सकते हैं। + +बस इतना ही। यदि आपके पास ये बुनियादी चीज़ें हैं, तो हम शुरू करने के लिए तैयार हैं। + +## Word को PDF में सहेजें – चरण‑दर‑चरण अवलोकन + +नीचे पूरा, चलाने योग्य प्रोग्राम है। इसे कॉपी‑पेस्ट करके एक कंसोल ऐप प्रोजेक्ट में डालें और **F5** दबाएँ। + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **प्रो टिप:** `YOUR_DIRECTORY` को एक पूर्ण पथ से बदलें या सापेक्ष, सुरक्षित दृष्टिकोण के लिए `Path.Combine(Environment.CurrentDirectory, "input.docx")` का उपयोग करें। + +### हम चेतावनी कॉलबैक क्यों उपयोग करते हैं + +Aspose.Words चुपचाप मिसिंग फ़ॉन्ट को एक फॉलबैक (आमतौर पर Arial) से बदल देता है। बिना कॉलबैक के आपको कभी पता नहीं चलेगा कि प्रतिस्थापन हुआ है, जिससे उत्पन्न PDF में लेआउट गड़बड़ियां हो सकती हैं। `IWarningCallback` को हुक करके, हमें हर मिसिंग‑फ़ॉन्ट इवेंट की स्पष्ट, प्रोग्रामेटिक सूची मिलती है—जो लॉगिंग या अंतिम उपयोगकर्ताओं को सूचित करने के लिए उत्तम है। + +### मिसिंग फ़ॉन्ट्स का पता लगाएँ – क्या देखें + +जब आप प्रोग्राम चलाते हैं, तो कोई भी मिसिंग फ़ॉन्ट कंसोल में नीचे जैसा लाइन उत्पन्न करेगा: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +यदि सूची खाली है, तो बधाई—**save word as pdf** सभी मूल फ़ॉन्ट्स के साथ सफल रहा। + +## Docx को PDF में बदलें – आउटपुट को कस्टमाइज़ करना + +कभी-कभी आपको एक विशिष्ट PDF संस्करण, इमेज क्वालिटी, या अनुपालन स्तर चाहिए होता है। Aspose.Words आपको `Save` कॉल करने से पहले `PdfSaveOptions` ऑब्जेक्ट को समायोजित करने देता है। + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **क्यों यह महत्वपूर्ण है:** यदि आप कानूनी अभिलेखों के लिए PDF बना रहे हैं, तो `PdfA1b` सेट करने से फ़ाइल कड़े मानकों को पूरा करती है। वही परिवर्तन हमारे चेतावनी कॉलबैक का सम्मान करता है, इसलिए आप अभी भी **detect missing fonts** करेंगे। + +## Aspose Words फ़ॉन्ट सब्स्टिट्यूशन – किनारे के मामलों को संभालना + +### परिदृश्य 1: कई मिसिंग फ़ॉन्ट्स + +यदि आपके स्रोत दस्तावेज़ में कई कस्टम फ़ॉन्ट्स उपयोग किए गए हैं, तो चेतावनी कलेक्टर में प्रत्येक फ़ॉन्ट के लिए एक प्रविष्टि होगी। आप उन्हें एकत्रित कर सकते हैं: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### परिदृश्य 2: फॉलबैक फ़ॉन्ट डायरेक्टरी प्रदान करना + +Aspose.Words अतिरिक्त फ़ोल्डरों में फ़ॉन्ट खोज सकता है। दस्तावेज़ लोड करने से पहले `FontSettings` पर `FontsFolder` प्रॉपर्टी सेट करें: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +अब लाइब्रेरी पहले आपके कस्टम फ़ोल्डर को देखेगी, जिससे अनचाहे प्रतिस्थापन की संभावना कम हो जाएगी। + +### परिदृश्य 3: प्रतिस्थापन को अनदेखा करना + +यदि आप चाहते हैं कि फ़ॉन्ट मिसिंग होने पर रूपांतरण विफल हो (बिना चुपचाप प्रतिस्थापित किए), तो कॉलबैक के अंदर एक अपवाद फेंकेँ: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +यह आपको आगे बढ़ने से पहले मिसिंग फ़ॉन्ट को ठीक करने के लिए बाध्य करता है—CI पाइपलाइन में जहाँ चुपचाप विफलताएँ अस्वीकार्य होती हैं, यह उपयोगी है। + +## पूरा एंड‑टू‑एंड उदाहरण + +सब कुछ मिलाकर, यहाँ एक संक्षिप्त संस्करण है जो **Word को PDF में कैसे बदलें** दर्शाता है, कस्टम PDF विकल्प सेट करता है, और किसी भी फ़ॉन्ट समस्या को लॉग करता है: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**अपेक्षित कंसोल आउटपुट** (यदि Calibri मिसिंग है): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +यदि कोई चेतावनी नहीं आती, तो आपका **save word as pdf** ऑपरेशन स्रोत DOCX के समान फ़ॉन्ट्स का उपयोग करता है। + +## दृश्य सारांश + +![Word को PDF में सहेजने का वर्कफ़्लो आरेख](https://example.com/diagram.png "Word को PDF में सहेजने का वर्कफ़्लो") + +*छवि वैकल्पिक पाठ:* **save word as pdf** वर्कफ़्लो जो लोडिंग, चेतावनी संग्रह, और PDF आउटपुट दिखाता है। + +## सामान्य प्रश्न और उत्तर + +| प्रश्न | उत्तर | +|----------|--------| +| **क्या मुझे Aspose.Words के लिए लाइसेंस चाहिए?** | एक मुफ्त मूल्यांकन लाइसेंस परीक्षण के लिए काम करता है, लेकिन उत्पादन उपयोग के लिए मूल्यांकन वॉटरमार्क हटाने हेतु भुगतान वाला लाइसेंस आवश्यक है। | +| **क्या यह .NET Core / .NET 6+ पर काम करेगा?** | बिल्कुल—Aspose.Words .NET Standard 2.0 को लक्षित करता है, इसलिए कोई भी नवीनतम .NET रनटाइम संगत है। | +| **क्या मैं लूप में कई DOCX फ़ाइलें बदल सकता हूँ?** | हां, प्रत्येक फ़ाइल के लिए नया `Document` बनाएं और यदि आप समेकित परिणाम चाहते हैं तो वही `WarningInfoCollector` पुनः उपयोग करें। | +| **यदि आउटपुट फ़ोल्डर मौजूद नहीं है तो क्या होगा?** | `Document.Save` `DirectoryNotFoundException` फेंकेगा। पहले फ़ोल्डर बनाएं या `Directory.CreateDirectory` का उपयोग करें। | +| **क्या मिसिंग फ़ॉन्ट्स को PDF में एम्बेड करने का कोई तरीका है?** | यदि फ़ॉन्ट मशीन पर उपलब्ध हैं तो Aspose.Words स्वचालित रूप से फ़ॉन्ट्स एम्बेड कर सकता है; `PdfSaveOptions.EmbedFullFonts = true` सेट करें। | + +## निष्कर्ष + +अब आपके पास एक ठोस, प्रोडक्शन‑रेडी पैटर्न है **save Word as PDF** करने का, जबकि **detecting missing fonts** और **Aspose.Words font substitution** परिदृश्यों को संभालता है। चेतावनी कॉलबैक जोड़कर, फ़ॉन्ट फ़ोल्डर कस्टमाइज़ करके, और वैकल्पिक रूप से `PdfSaveOptions` को समायोजित करके, आप भरोसेमंद रूप से **convert docx to pdf** कर सकते हैं और उपयोगकर्ताओं को किसी भी फ़ॉन्ट समस्या के बारे में सूचित रख सकते हैं जो लेआउट की सटीकता को प्रभावित कर सकती है। + +अगले कदम के लिए तैयार हैं? कई दस्तावेज़ों से समानांतर में PDF जनरेट करने का प्रयास करें, या वॉटरमार्क और डिजिटल सिग्नेचर जोड़ने का अन्वेषण करें—दोनों ही कोड के सहज विस्तार हैं जो आपने अभी सीखा है। कोडिंग का आनंद लें, और आपके PDF हमेशा इच्छित रूप में दिखें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-loadoptions/_index.md b/words/hindi/net/programming-with-loadoptions/_index.md index 3f300d61d8..95bc42aaa6 100644 --- a/words/hindi/net/programming-with-loadoptions/_index.md +++ b/words/hindi/net/programming-with-loadoptions/_index.md @@ -39,12 +39,13 @@ Aspose.Words for .NET ट्यूटोरियल उन डेवलपर | [मेटाफ़ाइल्स को Png में बदलें](./convert-metafiles-to-png/) | इस चरण-दर-स्टेप ट्यूटोरियल के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में मेटाफ़ाइल्स को PNG में आसानी से बदलें। अपने दस्तावेज़ प्रबंधन को सरल बनाएँ। | | [Word दस्तावेज़ में Chm फ़ाइलें लोड करें](./load-chm/) | इस चरण-दर-स्टेप ट्यूटोरियल के साथ .NET के लिए Aspose.Words का उपयोग करके आसानी से CHM फ़ाइलों को Word दस्तावेज़ों में लोड करें। अपने तकनीकी दस्तावेज़ों को समेकित करने के लिए बिल्कुल सही। | | [क्षतिग्रस्त Word फ़ाइल पुनर्प्राप्त करें – भ्रष्ट DOCX खोलने और पृष्ठ गिनती प्राप्त करने के पूर्ण गाइड](./recover-damaged-word-file-complete-guide-to-open-corrupted-d/) | भ्रष्ट DOCX फ़ाइल को खोलने, सामग्री पुनर्स्थापित करने और पृष्ठ गिनती जानने के चरण-दर-स्टेप मार्गदर्शन। | -| [docx को पुनर्प्राप्त करने की विधि – भ्रष्ट Word फ़ाइलों के लिए C# गाइड](./how-to-recover-docx-c-guide-for-corrupted-word-files/) भ्रष्ट .docx फ़ाइलों को पुनर्स्थापित करने के लिए C# कोड उदाहरण और चरण-दर-चरण मार्गदर्शिका। | +| [docx को पुनर्प्राप्त करने की विधि – भ्रष्ट Word फ़ाइलों के लिए C# गाइड](./how-to-recover-docx-c-guide-for-corrupted-word-files/) भ्रष्ट .docx फ़ाइलों को पुनर्स्थापित करने के लिए C# कोड उदाहरण और चरण-दर-स्टेप मार्गदर्शिका। | | [Aspose.Words के साथ docx पुनर्प्राप्ति – चरण दर चरण](./how-to-recover-docx-with-aspose-words-step-by-step/) | -| [docx पुनर्प्राप्ति – रिकवरी मोड सेट करें और क्षतिग्रस्त Word फ़ाइलें खोलें](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) रिकवरी मोड सेट करके और क्षतिग्रस्त Word फ़ाइलें खोलकर docx फ़ाइलों को पुनर्प्राप्त करने की चरण-दर-चरण प्रक्रिया सीखें। | +| [docx पुनर्प्राप्ति – रिकवरी मोड सेट करें और क्षतिग्रस्त Word फ़ाइलें खोलें](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | रिकवरी मोड सेट करके और क्षतिग्रस्त Word फ़ाइलें खोलकर docx फ़ाइलों को पुनर्प्राप्त करने की चरण-दर-स्टेप प्रक्रिया सीखें। | | [Aspose Load Options – कस्टम फ़ॉन्ट सेटिंग्स के साथ DOCX लोड करें](./aspose-load-options-load-docx-with-custom-font-settings/) | -| [LoadOptions के साथ Aspose.Words का उपयोग कैसे करें – पूर्ण गाइड](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Aspose.Words में LoadOptions के साथ उन्नत लोडिंग विकल्पों को लागू करने की विस्तृत चरण-दर-चरण गाइड। | +| [LoadOptions के साथ Aspose.Words का उपयोग कैसे करें – पूर्ण गाइड](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Aspose.Words में LoadOptions के साथ उन्नत लोडिंग विकल्पों को लागू करने की विस्तृत चरण-दर-स्टेप गाइड। | | [C# में भ्रष्ट दस्तावेज़ पुनर्प्राप्त करें – रिकवरी मोड सेट करें और उपयोगकर्ता को प्रॉम्प्ट करें](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | C# में Aspose.Words का उपयोग करके भ्रष्ट Word दस्तावेज़ को रिकवरी मोड में लोड करना और उपयोगकर्ता को पुनर्प्राप्ति विकल्प दिखाना सीखें। | +| [भ्रष्ट docx पुनर्प्राप्त करें – C# में क्षतिग्रस्त Word फ़ाइलें लोड करने के लिए पूर्ण गाइड](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | C# में Aspose.Words का उपयोग करके भ्रष्ट docx फ़ाइलों को लोड करने और पुनर्प्राप्त करने की विस्तृत चरण-दर-चरण गाइड। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/hindi/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..2e1eb36bdc --- /dev/null +++ b/words/hindi/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words का उपयोग करके क्षतिग्रस्त docx फ़ाइलों को जल्दी से पुनर्प्राप्त + करें। पुनर्प्राप्ति मोड सेट करना, docx को सुरक्षित रूप से लोड करना, और कुछ ही चरणों + में क्षतिग्रस्त Word फ़ाइलों को पढ़ना सीखें। +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: hi +og_description: C# में भ्रष्ट docx फ़ाइलों को पुनर्प्राप्त करें। रिकवरी मोड सेट करें, + docx को सुरक्षित रूप से लोड करें, और Aspose.Words के साथ क्षतिग्रस्त Word फ़ाइलें + पढ़ें। +og_title: भ्रष्ट docx को पुनर्प्राप्त करें – त्वरित C# गाइड +tags: +- Aspose.Words +- C# +- Document Recovery +title: दोषग्रस्त docx को पुनर्प्राप्त करें – C# में क्षतिग्रस्त Word फ़ाइलों को लोड + करने की पूर्ण गाइड +url: /hi/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# भ्रष्ट docx – त्वरित C# गाइड + +क्या आपने कभी ऐसा Word फ़ाइल खोलने की कोशिश की है जो लोड ही नहीं होती और आप सोचते हैं कि सामग्री हमेशा के लिए खो गई है? कई वास्तविक‑दुनिया के प्रोजेक्ट्स में आप **recover corrupted docx** फ़ाइलों को उपयोगकर्ता से अटैचमेंट फिर से भेजने को कहे बिना पुनर्प्राप्त करेंगे। अच्छी खबर यह है कि Aspose.Words इसे बहुत आसान बना देता है: आप बस recovery mode सेट करते हैं और लाइब्रेरी को बाकी काम करने देते हैं। + +इस ट्यूटोरियल में हम **recover corrupted docx** फ़ाइलों के सटीक चरणों को दिखाएंगे, यह समझाएंगे कि `RecoveryMode.AutoRecover` विकल्प सबसे सुरक्षित क्यों है, और आपको दिखाएंगे कि **how to load docx** फ़ाइलों को कैसे लोड किया जाए जो आंशिक रूप से क्षतिग्रस्त हो सकती हैं। अंत तक आप एक क्षतिग्रस्त Word फ़ाइल पढ़ सकेंगे, बचा हुआ टेक्स्ट निकाल सकेंगे, और भविष्य के ऑडिट के लिए मूल फ़ॉर्मेट को भी लॉग कर सकेंगे। कोई बाहरी टूल नहीं, सिर्फ साफ़ C# कोड। + +## आपको क्या चाहिए + +- **Aspose.Words for .NET** (कोई भी नवीनतम संस्करण; हम जो API उपयोग करते हैं वह 23.5 और उसके बाद के संस्करणों के साथ काम करता है)। +- एक .NET विकास पर्यावरण (Visual Studio, VS Code, या Rider)। +- वह भ्रष्ट या आंशिक रूप से क्षतिग्रस्त `.docx` फ़ाइल जिसे आप बचाना चाहते हैं। + +कोई विशेष अनुमतियाँ नहीं, कोई COM इंटरऑप नहीं, और सर्वर पर Microsoft Office स्थापित करने की आवश्यकता नहीं। सरल, है ना? + +## चरण 1: Recovery Mode को Auto‑Recover पर सेट करें + +जब कोई Word फ़ाइल टूट जाती है, तो डिफ़ॉल्ट लोडिंग व्यवहार एक अपवाद फेंकता है और प्रक्रिया रोक देता है। एक `LoadOptions` ऑब्जेक्ट को कॉन्फ़िगर करके आप Aspose.Words को **set recovery mode** को `AutoRecover` पर सेट करने को कहते हैं, जो ज़िप पैकेज को स्कैन करता है, अपठनीय भागों को छोड़ देता है, और जितना संभव हो सके उसे जोड़कर लौटाता है। + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Why AutoRecover?** +> यह यथासंभव अधिक पढ़ने की कोशिश करता है जबकि दस्तावेज़ ऑब्जेक्ट को उपयोग योग्य रखता है। यदि आप `RecoveryMode.NoRecovery` चुनते हैं, तो लोड पहले भ्रष्टाचार पर ही विफल हो जाएगा, जिससे **recover corrupted docx** परिदृश्यों का उद्देश्य विफल हो जाता है। + +## चरण 2: कॉन्फ़िगर किए गए विकल्पों के साथ दस्तावेज़ लोड करें + +अब जब recovery mode सेट हो गया है, आप सुरक्षित रूप से फ़ाइल खोलने का प्रयास कर सकते हैं। `"YOUR_DIRECTORY/input.docx"` को अपनी क्षतिग्रस्त फ़ाइल के वास्तविक पथ से बदलें। + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +यदि फ़ाइल केवल आंशिक रूप से भ्रष्ट है, तो भी `Document` इंस्टेंस बनाया जाएगा। यदि आपको अतिरिक्त सत्यापन चाहिए तो आप बाद में `document.IsStructureValid` जांच सकते हैं। + +## चरण 3: पता लगाए गए फ़ॉर्मेट की जाँच करें + +Aspose.Words स्वचालित रूप से मूल फ़ॉर्मेट (DOC, DOCX, ODT, आदि) का पता लगाता है। इस मान को प्रिंट करने से आपको यह पुष्टि करने में मदद मिलती है कि लाइब्रेरी ने फ़ाइल को सही ढंग से पहचाना है, जो **recover corrupted docx** ऑपरेशन के बाद एक त्वरित सत्यापन है। + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +सामान्य आउटपुट: + +``` +Loaded with Docx format. +``` + +भले ही कुछ भाग गायब हों, फ़ॉर्मेट डिटेक्शन अभी भी सफल रहता है—**recover corrupted docx** वर्कफ़्लो के लिए एक और जीत। + +## चरण 4: जितना संभव हो उतना निकालें + +एक बार दस्तावेज़ लोड हो जाने पर, आप इसे किसी भी स्वस्थ Word फ़ाइल की तरह उपयोग कर सकते हैं। नीचे एक संक्षिप्त उदाहरण है जो प्लेन टेक्स्ट निकालता है और उसे कंसोल में लिखता है। यह दर्शाता है कि आप **read damaged word file** सामग्री को बिना क्रैश के पढ़ सकते हैं। + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +यदि मूल फ़ाइल में टेबल या इमेजेज़ थे जो भ्रष्ट थे, तो वे टेक्स्ट आउटपुट से बस हटा दिए जाएंगे। दस्तावेज़ का बाकी हिस्सा अपरिवर्तित रहता है। + +## चरण 5: एक साफ़ कॉपी सहेजें (वैकल्पिक) + +अक्सर आप पुनर्प्राप्ति के बाद उपयोगकर्ता को फ़ाइल का नया, साफ़ संस्करण देना चाहेंगे। समान फ़ॉर्मेट में सहेजने से किसी भी डाउनस्ट्रीम प्रक्रिया के साथ संगतता सुनिश्चित होती है। + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +अब आपके पास एक **recover damaged docx** फ़ाइल है जिसे आप सुरक्षित रूप से ईमेल में अटैच कर सकते हैं या किसी अन्य सेवा को पास कर सकते हैं। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ मिलाकर, यहाँ पूरा, तैयार‑चलाने योग्य प्रोग्राम है। इसे एक नए कंसोल प्रोजेक्ट में पेस्ट करें, फ़ाइल पाथ को समायोजित करें, और F5 दबाएँ। + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Expected output** (मान लेते हैं कि फ़ाइल में एक पैराग्राफ “Hello world!” और कुछ भ्रष्ट XML है): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +ध्यान दें कि प्रोग्राम कभी क्रैश नहीं करता—भले ही स्रोत फ़ाइल आंशिक रूप से टूटी हुई थी। यही Aspose.Words का उपयोग करके **recover corrupted docx** करने का सार है। + +## सामान्य प्रश्न और किनारे के मामले + +### अगर फ़ाइल पूरी तरह से अपठनीय है तो? + +भले ही `AutoRecover` की सीमाएँ हैं। यदि ज़िप कंटेनर स्वयं मरम्मत से बाहर भ्रष्ट है, तो Aspose.Words एक `CorruptedFileException` फेंकेगा। ऐसे में आपको **recover corrupted docx** फिर से प्रयास करने से पहले एक थर्ड‑पार्टी ज़िप रिपेयर टूल की आवश्यकता पड़ सकती है। + +### क्या मैं अन्य फ़ॉर्मेट (जैसे `.doc`, `.odt`) को पुनर्प्राप्त कर सकता हूँ? + +बिल्कुल। वही `LoadOptions` Aspose.Words द्वारा समर्थित किसी भी फ़ॉर्मेट के लिए काम करता है। बस फ़ाइल एक्सटेंशन बदलें और लाइब्रेरी स्वचालित रूप से मूल फ़ॉर्मेट का पता लगा लेगी। इसका मतलब है कि आप समान कोड के साथ `.doc` या `.rtf` जैसे **recover damaged docx**‑जैसे फ़ाइलों को भी पुनर्प्राप्त कर सकते हैं। + +### बड़े दस्तावेज़ों को बिना पूरी मेमोरी लोड किए कैसे संभालूँ? + +गिगाबाइट‑साइज़ फ़ाइलों के लिए आप `LoadOptions.LoadFormat` जैसी **load options** को सक्षम कर सकते हैं या दस्तावेज़ को पेज‑दर‑पेज स्ट्रीम कर सकते हैं। हालांकि, रिकवरी एल्गोरिद्म को अभी भी पूरे पैकेज को पढ़ना पड़ता है, इसलिए बहुत बड़े भ्रष्ट फ़ाइलों के लिए अधिक मेमोरी उपयोग की उम्मीद रखें। + +### क्या यह पता लगाने का कोई तरीका है कि कौन से भाग खो गए? + +लोड करने के बाद, आप `document.GetChildNodes(NodeType.Any, true)` की जाँच कर सकते हैं और उसकी गिनती को अपेक्षित बेसलाइन से तुलना कर सकते हैं। गायब टेबल, इमेज या हेडर बस नोड कलेक्शन में नहीं दिखेंगे। यह आपको ठीक‑ठीक लॉग करने देता है कि क्या **recover damaged docx** हुआ और उपयोगकर्ता को सूचित करता है। + +## विश्वसनीय रिकवरी के लिए प्रो टिप्स + +- **Validate the input file size** लोड करने से पहले; शून्य‑बाइट फ़ाइल हमेशा विफल होगी। +- **Log the `RecoveryMode` result** `DocumentLoadingException` को पकड़कर और अपवाद संदेश को संग्रहीत करके; यह अक्सर बताता है कि कौन से भाग छोड़े गए थे। +- **Run the recovery on a background thread** यदि आप वेब सर्विस में अपलोड प्रोसेस कर रहे हैं—यह अनुरोध को प्रतिक्रियाशील रखता है। +- **Combine with a checksum** (जैसे, MD5) ताकि यह पता चल सके कि पुनर्प्राप्त फ़ाइल मूल से अलग है या नहीं; फिर आप तय कर सकते हैं कि दोनों संस्करण रखें या नहीं। + +## निष्कर्ष + +हमने अभी दिखाया कि C# में **recover corrupted docx** फ़ाइलों को कैसे **setting recovery mode** को `AutoRecover` पर सेट करके, दस्तावेज़ को सुरक्षित रूप से लोड करके, बचा हुआ टेक्स्ट निकालकर, और वैकल्पिक रूप से एक साफ़ कॉपी सहेजकर पुनर्प्राप्त किया जा सकता है। यह तरीका आपको **how to load docx** फ़ाइलों को लोड करने देता है जो अन्यथा अपवाद फेंकतीं, और यह आपको बाहरी टूल्स के बिना **read damaged word file** सामग्री को पढ़ने का भरोसेमंद तरीका प्रदान करता है। + +अगले कदम? अंतर देखने के लिए `RecoveryMode.AutoRecover` को `RecoveryMode.NoRecovery` से बदलें, या पासवर्ड हैंडलिंग और फ़ॉन्ट प्रतिस्थापन को नियंत्रित करने वाले `LoadOptions` प्रॉपर्टीज़ के साथ प्रयोग करें। आप इस रिकवरी रूटीन को एक ASP.NET Core API में भी एकीकृत कर सकते हैं जो अपलोड स्वीकार करता है और एक मरम्मत फ़ाइल लौटाता है—एंटरप्राइज़ दस्तावेज़‑प्रबंधन पाइपलाइन के लिए उत्तम। + +Word दस्तावेज़ रिकवरी के बारे में और प्रश्न हैं, या आप देखना चाहते हैं कि कैसे **recover damaged docx** फ़ाइलों को कस्टम कॉलबैक्स के साथ किया जाए? नीचे टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + +![पुनर्स्थापित दस्तावेज़ का चित्रण – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-markdownsaveoptions/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/_index.md index e783bae3f5..beeaaac589 100644 --- a/words/hindi/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hindi/net/programming-with-markdownsaveoptions/_index.md @@ -30,24 +30,26 @@ MarkdownSaveOptions के साथ वर्ड प्रोसेसिंग | [DOCX को मार्कडाउन में बदलें – चरण‑दर‑चरण C# गाइड](./convert-docx-to-markdown-step-by-step-c-guide/) | DOCX फ़ाइलों को C# में चरण‑दर‑चरण मार्कडाउन में बदलने की गाइड। | | [DOCX को मार्कडाउन में सहेजें – LaTeX समीकरणों के साथ पूर्ण C# गाइड](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | C# में LaTeX समीकरणों के साथ DOCX को Markdown में बदलने की पूरी गाइड। | | [DOCX को मार्कडाउन के रूप में सहेजें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | इमेज एक्सट्रैक्शन के साथ DOCX को Markdown में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | -| [DOCX को मार्कडाउन में सहेजें – LaTeX समीकरणों के साथ पूर्ण C# गाइड](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | C# में LaTeX समीकरणों के साथ DOCX को मार्कडाउन में बदलने की पूरी गाइड। | -| [DOCX को मार्कडाउन के रूप में सहेजें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | इमेज एक्सट्रैक्शन के साथ DOCX को मार्कडाउन में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | +| [DOCX को मार्कडाउन में सहेजें – LaTeX समीकरणों के साथ पूर्ण C# गाइड](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | C# में LaTeX समीकरणों के साथ DOCX को Markdown में बदलने की पूरी गाइड। | +| [DOCX को मार्कडाउन के रूप में सहेजें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | इमेज एक्सट्रैक्शन के साथ DOCX को Markdown में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | | [Word को Markdown में बदलें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) | इमेज एक्सट्रैक्शन के साथ Word को Markdown में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | | [Word से Markdown निर्यात कैसे करें – पूर्ण C# गाइड](./how-to-export-markdown-from-word-complete-c-guide/) | Word दस्तावेज़ को Markdown में निर्यात करने की पूरी C# गाइड | -| [DOCX को मार्कडाउन में सहेजें – LaTeX समीकरणों के साथ पूर्ण C# गाइड](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | C# में LaTeX समीकरणों के साथ DOCX को मार्कडाउन में बदलने की पूरी गाइड। | -| [DOCX को मार्कडाउन में सहेजें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | इमेज एक्सट्रैक्शन के साथ DOCX को मार्कडाउन में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | +| [DOCX को मार्कडाउन में सहेजें – LaTeX समीकरणों के साथ पूर्ण C# गाइड](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | C# में LaTeX समीकरणों के साथ DOCX को Markdown में बदलने की पूरी गाइड। | +| [DOCX को मार्कडाउन में सहेजें – इमेज एक्सट्रैक्शन के साथ पूर्ण C# गाइड](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | इमेज एक्सट्रैक्शन के साथ DOCX को Markdown में बदलने की पूरी गाइड। C# में चरण‑दर‑चरण प्रक्रिया। | | [Word से Markdown निर्यात कैसे करें – पूर्ण C# गाइड](./how-to-export-markdown-from-word-complete-c-guide/) | Word दस्तावेज़ को Markdown में निर्यात करने की पूरी C# गाइड | | [DOCX को मार्कडाउन में बदलें – चरण‑दर‑चरण गाइड](./how-to-save-markdown-from-docx-step-by-step-guide/) | DOCX फ़ाइल को मार्कडाउन में बदलने की चरण‑दर‑चरण प्रक्रिया सीखें। | | [DOCX से Markdown निर्यात कैसे करें – पूरी गाइड](./how-to-export-markdown-from-docx-complete-guide/) | DOCX फ़ाइल को Markdown में निर्यात करने की विस्तृत चरण‑दर‑चरण गाइड। | | [Word से LaTeX निर्यात कैसे करें: Aspose के साथ DOCX को Markdown में बदलें](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) | Aspose.Words का उपयोग करके Word दस्तावेज़ से LaTeX निर्यात करके DOCX को Markdown में परिवर्तित करने की चरण‑दर‑चरण गाइड। | | [Word को Markdown में बदलें – छवियों को Base64 के रूप में एम्बेड करें](./convert-word-to-markdown-embed-images-as-base64/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों को Markdown में बदलें और छवियों को Base64 एन्कोडेड रूप में एम्बेड करें। | -| [मार्कडाउन का उपयोग कैसे करें: LaTeX समीकरणों के साथ DOCX को मार्कडाउन में परिवर्तित करें](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | DOCX फ़ाइलों को LaTeX समीकरणों के साथ मार्कडाउन में बदलने की चरण-दर-स्तर मार्गदर्शिका। | +| [मार्कडाउन का उपयोग कैसे करें: LaTeX समीकरणों के साथ DOCX को मार्कडाउन में परिवर्तित करें](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | DOCX फ़ाइलों को LaTeX समीकरणों के साथ मार्कडाउन में बदलने की चरण‑दर‑स्तर मार्गदर्शिका। | | [DOCX को मार्कडाउन में बदलें – चरण‑दर‑चरण C# गाइड](./convert-docx-to-markdown-step-by-step-c-guide/) | DOCX फ़ाइलों को C# में चरण‑दर‑चरण मार्कडाउन में बदलने की गाइड। | | [Word से Markdown कैसे सहेजें – पूर्ण C# गाइड](./how-to-save-markdown-from-word-complete-c-guide/) | .NET के लिए Aspose.Words का उपयोग करके Word को Markdown में सहेजने की पूरी गाइड | | [Word से Markdown कैसे सहेजें – पूर्ण गाइड](./how-to-save-markdown-from-word-complete-guide/) | .NET के लिए Aspose.Words का उपयोग करके Word को Markdown में सहेजने की पूरी गाइड | | [LaTeX निर्यात कैसे करें: DOCX को Markdown और TXT में बदलें](./how-to-export-latex-convert-docx-to-markdown-txt/) | DOCX फ़ाइल को LaTeX के साथ Markdown और TXT फ़ॉर्मेट में निर्यात करने की चरण‑दर‑चरण गाइड। | | [DOCX को Markdown में बदलते समय छवियों का नाम कैसे बदलें](./how-to-rename-images-when-converting-docx-to-markdown/) | DOCX को Markdown में बदलते समय छवियों के नाम बदलने की प्रक्रिया और कोड उदाहरण। | | [Aspose.Words के साथ docx को markdown में सहेजें – पूर्ण C# गाइड](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Aspose.Words का उपयोग करके C# में docx को markdown में बदलने की पूरी गाइड | +| [DOCX को मार्कडाउन में सहेजें – Aspose.Words के साथ Word गणित को LaTeX में निर्यात करें](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Aspose.Words का उपयोग करके Word दस्तावेज़ में गणितीय समीकरणों को LaTeX में निर्यात करके DOCX को Markdown में बदलें। | +| [Word को Markdown में बदलते समय छवियों को क्लाउड पर अपलोड करें](./upload-images-to-cloud-when-converting-word-to-markdown/) | Word दस्तावेज़ को Markdown में बदलते समय छवियों को क्लाउड स्टोरेज में अपलोड करने की प्रक्रिया। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..f9f79fc859 --- /dev/null +++ b/words/hindi/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words का उपयोग करके docx को markdown के रूप में सहेजें – शब्द + को markdown में बदलना सीखें, समीकरणों को LaTeX में निर्यात करें, और एक सहज कार्यप्रवाह + में markdown छवि रिज़ॉल्यूशन सेट करें। +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: hi +og_description: Aspose.Words के साथ docx को markdown के रूप में सहेजें। यह ट्यूटोरियल + दिखाता है कि कैसे वर्ड को markdown में बदलें, समीकरणों को लैटेक्स में निर्यात करें, + और markdown छवि रिज़ॉल्यूशन सेट करें। +og_title: docx को markdown के रूप में सहेजें – Word गणित को LaTeX में निर्यात करने + की पूरी गाइड +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx को markdown के रूप में सहेजें – Aspose.Words के साथ Word गणित को LaTeX + में निर्यात करें +url: /hi/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx को markdown के रूप में सहेजें – Aspose.Words के साथ Word Math को LaTeX में निर्यात करें + +क्या आपको कभी **docx को markdown के रूप में सहेजने** की ज़रूरत पड़ी और आप Office Math समीकरणों को स्पष्ट रूप से रखने में फँस गए? आप अकेले नहीं हैं। अधिकांश डेवलपर्स तब रुक जाते हैं जब डिफ़ॉल्ट रूपांतरण समीकरणों को धुंधली छवियों के रूप में छोड़ देता है, जिससे LaTeX में मैन्युअल री‑राइट की ज़रूरत पड़ती है। + +अच्छी ख़बर: Aspose.Words यह सब आपके लिए कर सकता है। इस ट्यूटोरियल में हम **word को markdown में बदलेंगे**, इंजन को **समीकरणों को LaTeX में निर्यात करने** के लिए कहेंगे, और शेष दस्तावेज़ के लिए **markdown छवि रिज़ॉल्यूशन सेट करेंगे**। अंत में आपके पास एक ही कमांड होगा जो साफ़ `.md` फ़ाइल को LaTeX‑तैयार गणित और हाई‑रेज़ॉल्यूशन छवियों के साथ उत्पन्न करेगा। + +## आप क्या सीखेंगे + +- कैसे एक `.docx` लोड करें जिसमें Office Math ऑब्जेक्ट्स हों। +- कौन‑से `MarkdownSaveOptions` प्रॉपर्टीज़ **समीकरणों को LaTeX में निर्यात** करने और **markdown छवि रिज़ॉल्यूशन सेट** करने को नियंत्रित करती हैं। +- एक पूरा, चलाने योग्य C# स्निपेट जो आप किसी भी .NET प्रोजेक्ट में पेस्ट कर सकते हैं। +- सामान्य समस्याओं, जैसे गायब फ़ॉन्ट्स या असमर्थित समीकरण सुविधाओं, को हल करने के टिप्स। + +**पूर्वापेक्षाएँ**: .NET 6+ (या .NET Framework 4.6+), Aspose.Words for .NET का लाइसेंस, और C# की बुनियादी समझ। यदि आप एक कंसोल ऐप बना सकते हैं, तो आप तैयार हैं। + +--- + +## चरण 1 – docx को markdown के रूप में सहेजें: अपना Word फ़ाइल लोड करें + +सबसे पहले हमें एक `Document` ऑब्जेक्ट चाहिए जो स्रोत `.docx` की ओर इशारा करता हो। इसे इस तरह समझें जैसे आप किताब खोल रहे हों इससे पहले कि आप अध्याय कॉपी करना शुरू करें। + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*क्यों महत्वपूर्ण है*: यदि दस्तावेज़ में कोई गणित नहीं है, तो **समीकरणों को LaTeX में निर्यात** चरण कोई प्रभाव नहीं डालेगा, लेकिन बाकी रूपांतरण अभी भी चलेगा। यह जांच आपको यह सोचने से बचाती है कि आपका आउटपुट Markdown क्यों LaTeX ब्लॉक्स से रहित है। + +--- + +## चरण 2 – समीकरणों को LaTeX में निर्यात करने के लिए कॉन्फ़िगर करें + +Aspose.Words आपको यह तय करने देता है कि Office Math कैसे रेंडर किया जाए। डिफ़ॉल्ट रूप से यह उन्हें PNG छवियों में बदल देता है, इसलिए कई ट्यूटोरियल ग्रेनी markdown फ़ाइलों के साथ समाप्त होते हैं। `OfficeMathExportMode` को `LaTeX` पर सेट करने से आपको साफ़, कॉपी‑पेस्ट‑तैयार समीकरण मिलते हैं। + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*क्यों `OfficeMathExportMode.LaTeX`?* LaTeX वैज्ञानिक प्रकाशन की lingua franca है। जब आप बाद में markdown को किसी static‑site जेनरेटर या Jupyter notebook में रेंडर करेंगे, तो समीकरण किसी भी ज़ूम लेवल पर स्पष्ट दिखेंगे। + +--- + +## चरण 3 – Markdown छवि रिज़ॉल्यूशन सेट करें (गैर‑गणित सामग्री के लिए) + +भले ही हम गणित पर ध्यान केंद्रित कर रहे हों, अधिकांश Word दस्तावेज़ों में चित्र, चार्ट या एम्बेडेड SVG भी होते हैं। `ImageResolution` प्रॉपर्टी यह नियंत्रित करती है कि Aspose.Words उन एसेट्स को कैसे रास्टराइज़ करे। **300 DPI** का मान स्क्रीन और प्रिंट दोनों के लिए एक आदर्श बिंदु है। + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*प्रो टिप*: यदि आपका markdown केवल वेब पर दिखाया जाएगा, तो फ़ाइल आकार कम रखने के लिए इसे 150 DPI तक घटा सकते हैं। इसके विपरीत, प्रिंट‑तैयार PDFs के लिए इसे 600 DPI तक बढ़ा दें। + +--- + +## चरण 4 – रूपांतरण चलाएँ – Word Math को LaTeX में बदलें + +अब जब सब कुछ कॉन्फ़िगर हो गया है, वास्तविक रूपांतरण केवल एक पंक्ति का काम है। Aspose.Words पर्दे के पीछे भारी काम करता है। + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**अपेक्षित आउटपुट**: उत्पन्न `.md` फ़ाइल खोलें और आपको कुछ इस तरह दिखना चाहिए: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +ध्यान दें कि LaTeX ब्लॉक्स (`$...$` और `$$...$$`) पहले की PNG स्निपेट्स की जगह ले चुके हैं। नीचे की छवि अभी भी PNG है, जिसे हमने 300 DPI पर रेंडर किया है। + +--- + +## चरण 5 – सामान्य किनारी मामलों और उनके समाधान + +| स्थिति | क्या होता है | समाधान | +|-----------|--------------|------------| +| **गायब फ़ॉन्ट्स** (जैसे Cambria Math इंस्टॉल नहीं) | LaTeX आउटपुट में अज्ञात प्रतीक दिख सकते हैं। | सर्वर पर गायब फ़ॉन्ट इंस्टॉल करें या रूपांतरण से पहले दस्तावेज़ में एम्बेड करें। | +| **जटिल समीकरण** (कस्टम डिलिमिटर वाला मैट्रिक्स) | `LaTeX` मोड के बावजूद Aspose.Words छवि में फॉल्बैक कर सकता है। | नवीनतम Aspose.Words संस्करण में अपग्रेड करें; लाइब्रेरी लगातार समीकरण कवरेज सुधार रही है। | +| **बड़े दस्तावेज़** ( > 50 MB ) | मेमोरी दबाव से `OutOfMemoryException` हो सकता है। | `LoadOptions` के साथ `LoadFormat.Docx` उपयोग करें और फ़ाइल को स्ट्रीम करें, या रूपांतरण से पहले दस्तावेज़ को सेक्शन में बाँटें। | +| **छवि आकार बहुत बड़ा** | Markdown फ़ाइल बहुत बड़ी हो जाती है, जिससे static‑site बिल्ड धीमा हो जाता है। | वेब‑केवल परिदृश्यों के लिए `ImageResolution` को 150 DPI तक घटाएँ (देखें चरण 3)। | + +--- + +## चरण 6 – सब कुछ एक साथ रखें: पूर्ण कार्यशील उदाहरण + +नीचे *पूरा* कंसोल‑ऐप प्रोग्राम है जिसे आप `Program.cs` में कॉपी‑पेस्ट कर सकते हैं। इसमें हमने चर्चा किए सभी हिस्से और थोड़ा अतिरिक्त एरर हैंडलिंग शामिल है। + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +प्रोग्राम चलाएँ (`dotnet run`) और आपको एक markdown फ़ाइल मिलेगी जो **docx को markdown के रूप में सहेजती** है जबकि हर समीकरण को LaTeX के रूप में रखती है। कोई मैन्युअल कॉपी‑पेस्ट नहीं, कोई बदसूरत रास्टर छवियां नहीं। + +--- + +## निष्कर्ष + +हमने Aspose.Words के साथ **docx को markdown के रूप में सहेजने** की पूरी प्रक्रिया को कवर किया, Word फ़ाइल लोड करने से लेकर **समीकरणों को LaTeX में निर्यात** करने और **markdown छवि रिज़ॉल्यूशन सेट** करने तक। अंतिम स्निपेट प्रोडक्शन‑रेडी है, और आप इसे किसी भी .NET प्रोजेक्ट में डाल सकते हैं जिसे **word को markdown में बदलने** की आवश्यकता है। + +अगला कदम? उत्पन्न `.md` को Hugo या Jekyll जैसे static‑site जेनरेटर में फीड करें और देखें कि आपके समीकरण कितने सुंदर रेंडर होते हैं। यदि आपको **word math को latex में बदलने** के बाद अन्य फ़ॉर्मेट (PDF, HTML) चाहिए, तो बस `MarkdownSaveOptions` को `PdfSaveOptions` या `HtmlSaveOptions` से बदल दें—`OfficeMathExportMode` फ़्लैग सभी में समान रूप से काम करता है। + +क्या आपका वर्कफ़्लो Azure Blob स्टोरेज से Word फ़ाइलें खींचना या API से स्ट्रीम करना शामिल करता है? वही पैटर्न लागू होता है; केवल फ़ाइल‑सिस्टम `Document` कंस्ट्रक्टर को स्ट्रीम‑आधारित वाले से बदलें। + +प्रयोग करने में संकोच न करें, और कमेंट्स में बताएं कि इस दृष्टिकोण ने आपके रूपांतरण समस्याओं को कैसे हल किया। Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..b07109e771 --- /dev/null +++ b/words/hindi/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,246 @@ +--- +category: general +date: 2026-05-01 +description: वर्ड दस्तावेज़ को मार्कडाउन में बदलते समय छवियों को क्लाउड पर अपलोड करें। + जानिए कैसे docx से छवियों को निकालें और उन्हें Azure Blob स्टोरेज में संग्रहित करें। +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: hi +og_description: वर्ड दस्तावेज़ को मार्कडाउन में बदलते समय छवियों को क्लाउड पर अपलोड + करें। यह गाइड दिखाता है कि कैसे docx से छवियों को निकालें और उन्हें Azure Blob स्टोरेज + में संग्रहित करें। +og_title: वर्ड को मार्कडाउन में बदलते समय छवियों को क्लाउड पर अपलोड करें +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: वर्ड को मार्कडाउन में बदलते समय छवियों को क्लाउड पर अपलोड करें +url: /hi/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word को Markdown में बदलते समय इमेजेज़ को क्लाउड पर अपलोड करना + +क्या आपको कभी Word फ़ाइल को Markdown में बदलते समय **इमेजेज़ को क्लाउड पर अपलोड** करने की ज़रूरत पड़ी है? आप अकेले नहीं हैं—डेवलपर्स लगातार डॉक्यूमेंट कन्वर्ज़न और एसेट मैनेजमेंट को संभालते रहते हैं, और दोनों को एक ही सुगम प्रक्रिया में करना कभी‑कभी चलती हुई लक्ष्य को पकड़ने जैसा लगता है। + +अच्छी खबर? Aspose.Words के साथ आप .docx से हर तस्वीर, चार्ट या डायग्राम निकाल सकते हैं, उसे सीधे Azure Blob Storage में पुश कर सकते हैं, और जेनरेटेड Markdown को उन क्लाउड URLs की ओर इशारा करने दे सकते हैं बजाय लोकल फ़ाइलों के। इस ट्यूटोरियल में हम पूरे प्रोसेस को देखेंगे, स्रोत डॉक्यूमेंट को लोड करने से लेकर एक साफ़ Markdown फ़ाइल बनाने तक जो आपके Azure बकेट की ओर इशारा करती है। + +इस गाइड के अंत तक आप **docx को markdown में बदल** सकेंगे, **docx से इमेजेज़ निकाल** सकेंगे, और **इमेजेज़ को Azure Blob में स्टोर** कर सकेंगे—सिर्फ कुछ ही C# लाइनों के साथ। कोई बाहरी टूल नहीं, कोई मैनुअल कॉपी‑पेस्ट नहीं, और निश्चित रूप से कोई टूटे हुए इमेज लिंक नहीं। + +## आपको क्या चाहिए + +- **.NET 6.0** या बाद का (कोड .NET Core और .NET Framework पर भी काम करता है) +- **Aspose.Words for .NET** (NuGet पैकेज `Aspose.Words`) +- एक **Azure Storage account** जिसमें एक कंटेनर हो (जैसे `images`) और एक शेयरड एक्सेस की – फ़ाइलें अपलोड करने के लिए आपको कनेक्शन स्ट्रिंग चाहिए होगी। +- C# और async/await की बुनियादी समझ (वैकल्पिक लेकिन उपयोगी)। + +यदि आपके पास ये सभी चीज़ें पहले से हैं, तो बढ़िया—चलिए सीधे समाधान की ओर बढ़ते हैं। यदि नहीं, तो अंत में दिया गया “Prerequisites” सेक्शन आपको तेज़ सेटअप स्टेप्स की ओर निर्देशित करेगा। + +## चरण 1: Azure Blob हेल्पर सेट अप करें (यह क्यों महत्वपूर्ण है) + +Word डॉक्यूमेंट को छूने से पहले, हमें एक छोटा हेल्पर चाहिए जो बाइट एरे को Azure Blob Storage में पुश करना और एक पब्लिक URL रिटर्न करना जानता हो। यह एब्स्ट्रैक्शन कन्वर्ज़न लॉजिक को साफ़ रखता है और बाद में स्टोरेज प्रोवाइडर बदलना आसान बनाता है। + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**इस हेल्पर की आवश्यकता क्यों?** +1. **Separation of concerns** – markdown कन्वर्ज़न कोड डॉक्यूमेंट हैंडलिंग पर केंद्रित रहता है, HTTP विवरणों पर नहीं। +2. **Reusability** – आप अपने ऐप में कहीं भी `UploadAsync` को कॉल कर सकते हैं (जैसे, यूज़र‑अपलोडेड तस्वीरों के लिए)। +3. **Future‑proofing** – Amazon S3 या Google Cloud Storage में स्विच करने के लिए केवल उसी इंटरफ़ेस की नई इम्प्लीमेंटेशन चाहिए होगी। + +> **Pro tip:** कंटेनर का एक्सेस लेवल `Blob` (पब्लिक) तभी सेट करें जब आप चाहते हों कि कोई भी इमेज देख सके। प्राइवेट परिस्थितियों में, प्रत्येक अपलोड के लिए SAS टोकन जेनरेट करें और उन URLs को एम्बेड करें। + +## चरण 2: Resource‑Saving Callback परिभाषित करें (Upload‑While‑Convert का कोर) + +Aspose.Words आपको हर रिसोर्स (इमेज, चार्ट, आदि) को इंटरसेप्ट करने देता है जो सामान्यतः डॉक्यूमेंट को Markdown के रूप में सेव करने पर डिस्क पर लिखा जाता। `ResourceSavingCallback` प्रदान करके, हम प्रत्येक रिसोर्स को Azure Blob में अपलोड कर सकते हैं और लोकल फ़ाइलनाम को क्लाउड URL से बदल सकते हैं। + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**What’s happening here?** + +- **Extract** – Aspose.Words प्रत्येक इमेज के लिए हमें एक स्ट्रीम देता है। +- **Upload** – हम उस स्ट्रीम को `AzureBlobUploader` को देते हैं। +- **Replace** – Markdown राइटर पब्लिक URL प्राप्त करता है और उसे markdown इमेज सिंटैक्स (`![](https://…)`) में लिखता है। + +क्योंकि हमने `args.AlreadyExists = true` सेट किया है, कोई टेम्पररी फ़ाइलें फ़ाइल सिस्टम को गंदा नहीं करतीं—एक साफ़, स्टेटलेस ऑपरेशन जो सर्वरलेस फ़ंक्शन्स के लिए परफेक्ट है। + +## चरण 3: Markdown Save Options कॉन्फ़िगर करें (सब कुछ जोड़ें) + +अब हम कॉलबैक को Aspose.Words के `MarkdownSaveOptions` में जोड़ते हैं। महत्वपूर्ण फ़्लैग्स हैं `ExportImagesAsBase64 = false` (ताकि हमें एक्सटर्नल लिंक मिलें) और `ResourceSavingCallback = new CloudResourceSaver(uploader)`। + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**हम Base64 को क्यों डिसेबल करते हैं?** +जब `ExportImagesAsBase64` true होता है, Aspose हर तस्वीर को सीधे markdown में डेटा URI के रूप में एम्बेड कर देता है। यह **इमेजेज़ को क्लाउड पर अपलोड** करने के उद्देश्य को नष्ट कर देता है क्योंकि markdown फ़ाइल का आकार बढ़ जाता है और इमेजेज़ CDN से छिपी रहती हैं। इसे बंद करके हमें साफ़, एक्सटर्नल लिंक मिलते हैं जो Azure Blob की ओर इशारा करते हैं—बिल्कुल वही जो एक आधुनिक static‑site जेनरेटर की अपेक्षा होती है। + +## चरण 4: सब कुछ मिलाएँ – एक मिनिमल कंसोल ऐप + +नीचे एक पूर्ण, तैयार‑चलाने योग्य कंसोल प्रोग्राम दिया गया है। प्लेसहोल्डर्स को अपने वास्तविक Azure कनेक्शन स्ट्रिंग और कंटेनर नाम से बदलें। + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### अपेक्षित आउटपुट + +जब आप प्रोग्राम को `sample.docx` के साथ चलाते हैं जिसमें दो तस्वीरें हैं, तो यह उत्पन्न करेगा: + +- `output.md` जिसमें markdown इमेज सिंटैक्स होगा जैसे: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-pdfsaveoptions/_index.md b/words/hindi/net/programming-with-pdfsaveoptions/_index.md index 9b7d828190..cadace7f90 100644 --- a/words/hindi/net/programming-with-pdfsaveoptions/_index.md +++ b/words/hindi/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ PdfSaveOptions के साथ Words Processing पर Aspose.Words for .NET | [C# में सुलभ PDF बनाएं – PDF अभिगम्यता ट्यूटोरियल](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | C# के लिए Aspose.Words का उपयोग करके सुलभ PDF बनाने की चरण-दर-चरण गाइड। | | [Word से सुलभ PDF बनाएं – पूर्ण गाइड](./create-accessible-pdf-from-word-complete-guide/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ से सुलभ PDF बनाने की पूरी प्रक्रिया सीखें। | | [सुलभ PDF बनाएं – PDF/UA अनुपालन के लिए चरण‑दर‑चरण गाइड](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | PDF/UA मानकों के अनुरूप सुलभ PDF बनाने के लिए चरण‑दर‑चरण मार्गदर्शिका। | +| [दस्तावेज़ को PDF के रूप में सहेजें Aspose.Words – पूर्ण C# गाइड](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | C# में Aspose.Words का उपयोग करके दस्तावेज़ को PDF में बदलने की पूरी मार्गदर्शिका। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/hindi/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..81fe5d737c --- /dev/null +++ b/words/hindi/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words का उपयोग करके C# में दस्तावेज़ को PDF के रूप में सहेजना + सीखें। ट्यूटोरियल में शब्द को PDF में बदलना, गणितीय LaTeX निर्यात करना, और गायब + फ़ॉन्ट्स को संभालना भी शामिल है। +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: hi +og_description: Aspose.Words के साथ दस्तावेज़ को आसानी से PDF के रूप में सहेजें। यह + गाइड दिखाता है कि कैसे वर्ड को PDF में बदलें, गणितीय LaTeX निर्यात करें, और लापता + फ़ॉन्ट्स को संभालें। +og_title: Aspose.Words के साथ दस्तावेज़ को PDF के रूप में सहेजें – पूर्ण C# गाइड +tags: +- Aspose.Words +- C# +- PDF generation +title: Aspose.Words के साथ दस्तावेज़ को PDF के रूप में सहेजें – पूर्ण C# गाइड +url: /hi/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words के साथ डॉक्यूमेंट को PDF में सेव करें – पूर्ण C# गाइड + +क्या आप कभी सोचते हैं **डॉक्यूमेंट को PDF के रूप में कैसे सेव करें** सीधे Word फ़ाइल से, बिना एक्सेसिबिलिटी फीचर्स खोए? आप अकेले नहीं हैं—डेवलपर्स लगातार एक भरोसेमंद तरीका चाहते हैं **Word को PDF में कनवर्ट करने** का, जबकि गणितीय समीकरणों को संरक्षित रखा जाए और गुम फ़ॉन्ट्स को सहजता से संभाला जाए। + +इस ट्यूटोरियल में हम एक चरण‑दर‑चरण समाधान पर चलेंगे जो न केवल **डॉक्यूमेंट को PDF के रूप में सेव करें** बल्कि **Word को PDF में कनवर्ट करें**, **गणित को LaTeX में निर्यात करें**, और **गुम फ़ॉन्ट्स को संभालें** नवीनतम Aspose.Words for .NET का उपयोग करके दिखाता है। अंत तक आपके पास एक तैयार‑चलाने‑योग्य C# प्रोग्राम होगा जो PDF/UA‑2 अनुरूप फ़ाइलें बनाता है, एक्सेसिबिलिटी ऑडिट्स के लिए उत्तम। + +## आपको क्या चाहिए + +- .NET 6 या बाद का (कोड .NET Core और .NET Framework के साथ भी काम करता है) +- Aspose.Words for .NET 25.10 या नया – आप Aspose वेबसाइट से मुफ्त ट्रायल प्राप्त कर सकते हैं +- एक साधारण Word दस्तावेज़ (`input.docx`) जिसमें कम से कम एक फ़्लोटिंग शैप और एक गणितीय समीकरण हो (ताकि export‑math‑latex फीचर को कार्रवाई में देख सकें) +- Visual Studio 2022 (या कोई भी IDE जो आपको पसंद हो) + +> **Pro tip:** यदि आप CI/CD पाइपलाइन पर हैं, तो अपने प्रोजेक्ट फ़ाइल में Aspose.Words NuGet पैकेज जोड़ें: + +```xml + +``` + +अब कोड में डुबकी लगाते हैं। + +## चरण 1: ऑटोमैटिक रिकवरी के साथ स्रोत दस्तावेज़ लोड करें + +वास्तविक‑दुनिया के Word फ़ाइलों से निपटते समय आपको भ्रष्ट सेक्शन या गुम संसाधन मिल सकते हैं। ऑटोमैटिक रिकवरी को सक्षम करने से लोडिंग प्रक्रिया कभी अपवाद नहीं फेंकेगी। + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**यह क्यों महत्वपूर्ण है:** +`RecoveryMode.AutoRecover` आपके पाइपलाइन को खराब इनपुट पर क्रैश होने से बचाता है, जो विशेष रूप से तब उपयोगी है जब आप बड़े पैमाने पर **Word को PDF में कनवर्ट करें**। + +## चरण 2: पूर्ण एक्सेसिबिलिटी के लिए PDF सेव विकल्प सेट करें + +PDF/UA‑2 एक्सेसिबल PDFs के लिए ISO मानक है। कुछ फ़्लैग्स को कॉन्फ़िगर करके हम एक ऐसी फ़ाइल प्राप्त करते हैं जिसे स्क्रीन रीडर नेविगेट कर सकते हैं, और हम यह भी सुनिश्चित करते हैं कि गणितीय समीकरण छिपे हुए LaTeX के रूप में निर्यात हों। + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**मुख्य बिंदु:** + +- **ExportFloatingShapesAsInlineTag** – यह सुनिश्चित करता है कि परिणामी PDF मूल लेआउट का सम्मान करे जबकि अर्थपूर्ण रूप से सही बना रहे। +- **OfficeMathExportMode.LaTeX** – **गणित को LaTeX में निर्यात** की आवश्यकता को पूरा करता है, जिससे डाउनस्ट्रीम टूल्स को आवश्यकता पड़ने पर समीकरण निकालने की सुविधा मिलती है। + +## चरण 3: चेतावनियों को कैप्चर करें (जैसे, गुम फ़ॉन्ट्स) + +फ़ॉन्ट्स की कमी दस्तावेज़ों को कनवर्ट करते समय एक सामान्य समस्या है। Aspose.Words इन मुद्दों को `WarningCallback` के माध्यम से रिपोर्ट कर सकता है। हम इन्हें एकत्र करेंगे ताकि आप बाद में लॉग या कार्रवाई कर सकें। + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**आपको क्यों परवाह है:** +यदि स्रोत में ऐसा फ़ॉन्ट उपयोग किया गया है जो सर्वर पर स्थापित नहीं है, तो PDF डिफ़ॉल्ट फ़ॉन्ट पर वापस आएगा, जिससे लेआउट टूट सकता है। **गुम फ़ॉन्ट्स को संभालें** द्वारा हम उपयोगकर्ता को चेतावनी दे सकते हैं या एक विकल्प एम्बेड कर सकते हैं। + +## चरण 4: दस्तावेज़ को एक्सेसिबल PDF के रूप में सेव करें + +अब सत्य का क्षण—वास्तव में रूपांतरण करना। + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +यदि सब कुछ सुचारू रूप से चलता है, तो आपके पास एक PDF/UA‑2 फ़ाइल होगी जिसमें प्रत्येक समीकरण के लिए छिपा हुआ LaTeX और फ़्लोटिंग शैप्स के लिए उचित टैगिंग होगी। + +## चरण 5: कैप्चर की गई चेतावनियों की समीक्षा करें (वैकल्पिक लेकिन अनुशंसित) + +सेव ऑपरेशन के बाद, आप एकत्रित चेतावनियों पर इटररेट कर सकते हैं और उन्हें लॉग कर सकते हैं। + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +सामान्य आउटपुट इस प्रकार दिख सकता है: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +इन संदेशों को जल्दी देखना आपको **गुम फ़ॉन्ट्स को संभालने** में मदद करता है, इससे पहले कि वे अंतिम उपयोगकर्ताओं को प्रभावित करें। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ रखते हुए, यहाँ पूर्ण, तैयार‑चलाने‑योग्य प्रोग्राम है। प्लेसहोल्डर पाथ्स को अपने पाथ्स से बदलें। + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**अपेक्षित परिणाम:** +- `output.pdf` PDF/UA‑2 के अनुरूप है। +- सभी फ़्लोटिंग शैप्स को इनलाइन फ़िगर के रूप में टैग किया गया है। +- प्रत्येक Office Math ऑब्जेक्ट छिपे हुए LaTeX के रूप में दिखाई देता है (PDF की संरचना की जांच करने पर दिखता है)। +- कोई भी फ़ॉन्ट‑संबंधी मुद्दे कंसोल में प्रिंट होते हैं, जिससे आपको फ़ाइल शिप करने से पहले **गुम फ़ॉन्ट्स को संभालने** का मौका मिलता है। + +![डायग्राम जो Word → Aspose.Words → Accessible PDF (save document as pdf) के प्रवाह को दिखाता है](conversion-diagram.png "डॉक्यूमेंट को PDF में सेव करने के लिए फ्लो डायग्राम") + +*Image alt text:* **Aspose.Words का उपयोग करके डॉक्यूमेंट को PDF में कैसे सेव करें, इसका डायग्राम** + +## सामान्य प्रश्न और किनारी मामलों + +### यदि मैं पुराना Aspose.Words संस्करण उपयोग कर रहा हूँ तो क्या? + +`OfficeMathExportMode.LaTeX` फ़्लैग 25.10 में पेश किया गया था। पुराने रिलीज़ के लिए आप अभी भी **Word को PDF में कनवर्ट कर सकते हैं**, लेकिन गणित LaTeX के रूप में निर्यात होने के बजाय रास्टराइज़ हो जाएगा। सर्वोत्तम एक्सेसिबिलिटी के लिए अपग्रेड करें। + +### क्या मैं कस्टम फ़ॉन्ट्स एम्बेड कर सकता हूँ ताकि फ़ॉलबैक से बचा जा सके? + +हाँ। `Save` कॉल करने से पहले `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` सेट करें। यह भी **गुम फ़ॉन्ट्स को संभालने** में मदद करता है, PDF को आवश्यक ग्लिफ़्स शामिल करने के लिए मजबूर करके। + +### मैं PDF/UA‑2 अनुरूपता कैसे सत्यापित करूँ? + +फ़ाइल को Adobe Acrobat Pro में खोलें → “Print Production” → “Preflight”。 “PDF/A‑2b” या “PDF/UA‑2” प्रोफ़ाइल चुनें; Acrobat कोई भी उल्लंघन रिपोर्ट करेगा। + +### पासवर्ड‑सुरक्षित Word फ़ाइलों के बारे में क्या? + +`Password` शामिल करने वाले `LoadOptions` के साथ दस्तावेज़ लोड करें। उदाहरण: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +पाइपलाइन का बाकी हिस्सा अपरिवर्तित रहता है। + +## निष्कर्ष + +हमने Aspose.Words का उपयोग करके C# में **डॉक्यूमेंट को PDF के रूप में सेव करें** के लिए आवश्यक सब कुछ कवर किया है। ट्यूटोरियल ने यह भी दिखाया कि कैसे **Word को PDF में कनवर्ट करें**, **गणित को LaTeX में निर्यात करें**, और **गुम फ़ॉन्ट्स को संभालें**—सभी एक एक्सेसिबल PDF/UA‑2 फ़ाइल बनाते हुए। + +कोड को चलाकर देखें, विभिन्न `PdfSaveOptions` (जैसे, इमेज कम्प्रेशन, PDF/A‑2b) के साथ प्रयोग करें, और इसे अपने डॉक्यूमेंट‑प्रोसेसिंग सर्विस में इंटीग्रेट करें। यदि आपको आगे जाना है, तो पोस्ट‑प्रोसेसिंग या डिजिटल सिग्नेचर के लिए Aspose की PDF‑विशिष्ट लाइब्रेरी को एक्सप्लोर करने पर विचार करें। + +क्या आपके पास और परिदृश्य हैं जिन्हें आप हल करना चाहते हैं? बेझिझक टिप्पणी छोड़ें या हमारे अन्य गाइड देखें **PDF मैनिपुलेशन**, **इमेज एक्सट्रैक्शन**, और **बैच कनवर्ज़न** पर। कोडिंग का आनंद लें! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-shapes/_index.md b/words/hindi/net/programming-with-shapes/_index.md index 50ecf71d2b..0d72b75366 100644 --- a/words/hindi/net/programming-with-shapes/_index.md +++ b/words/hindi/net/programming-with-shapes/_index.md @@ -27,20 +27,21 @@ | [समूह आकार जोड़ें](./add-group-shape/) | इस व्यापक, चरण-दर-चरण ट्यूटोरियल के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में समूह आकृतियों को जोड़ना सीखें। | | [आकृति डालें](./insert-shape/) | हमारे चरण-दर-चरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में आकृतियों को सम्मिलित करना और उनमें हेरफेर करना सीखें। | | [पहलू अनुपात लॉक किया गया](./aspect-ratio-locked/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में आकृतियों के पहलू अनुपात को लॉक करना सीखें। अपनी छवियों और आकृतियों को आनुपातिक बनाए रखने के लिए इस चरण-दर-चरण मार्गदर्शिका का पालन करें। | -| [सेल में लेआउट](./layout-in-cell/) | इस विस्तृत गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके सेल में लेआउट सेट करना सीखें। Word दस्तावेज़ों को कस्टमाइज़ करने के इच्छुक डेवलपर्स के लिए बिल्कुल सही। | -| [कटे हुए कोने जोड़ें](./add-corners-snipped/) | जानें कि Aspose.Words for .NET का उपयोग करके अपने Word दस्तावेज़ों में कोनों को काटकर आकार कैसे जोड़ें। यह चरण-दर-श... | +| [सेल में लेआउट](./layout-in-cell/) | इस विस्तृत गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके सेल में लेआउट सेट करना सीखें। Word दस्तावेज़ों को कस्टमाइज़ करने की इच्छुक डेवलपर्स के लिए बिल्कुल सही। | +| [कटे हुए कोने जोड़ें](./add-corners-snipped/) | जानें कि Aspose.Words for .NET का उपयोग करके अपने Word दस्तावेज़ों में कोनों को काटकर आकार कैसे जोड़ें। यह चरण‑श... | | [वास्तविक आकार सीमा अंक प्राप्त करें](./get-actual-shape-bounds-points/) | जानें कि .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में वास्तविक आकार सीमा बिंदु कैसे प्राप्त करें। इस विस्तृत गाइड के साथ सटीक आकार हेरफेर सीखें। | -| [वर्टिकल एंकर](./vertical-anchor/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में टेक्स्टबॉक्स के लिए वर्टिकल एंकर पोजिशन सेट करना सीखें। आसान चरण-दर-शरण मार्गदर्शिका शामिल है।| +| [वर्टिकल एंकर](./vertical-anchor/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में टेक्स्टबॉक्स के लिए वर्टिकल एंकर पोजिशन सेट करना सीखें। आसान चरण‑दर‑शरण मार्गदर्शिका शामिल है।| | [स्मार्ट आर्ट आकार का पता लगाएं](./detect-smart-art-shape/) | इस व्यापक गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में SmartArt आकृतियों का पता लगाना सीखें। आपके दस्तावेज़ वर्कफ़्लो को स्वचालित करने के लिए बिल्कुल सही। | -| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण-दर-चरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में स्मार्ट आर्ट ड्रॉइंग को अपडेट करना सीखें। सुनिश्चित करें कि आपके दृश्य हमेशा सटीक हों। | +| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण‑दर‑चरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में स्मार्ट आर्ट ड्रॉइंग को अपडेट करना सीखें। सुनिश्चित करें कि आपके दृश्य हमेशा सटीक हों। | | [Aspose.Words के साथ Word में आयत आकार बनाएं – चरण‑दर‑चरण गाइड](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Aspose.Words का उपयोग करके Word दस्तावेज़ में आयत आकार बनाने और अनुकूलित करने के चरण‑दर‑चरण निर्देश। | -| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण-दर-शरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में स्मार्ट आर्ट ड्रॉइंग को अपडेट करना सीखें। सुनिश्चित करें कि आपके दृश्य हमेशा सटीक हों। | +| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण‑दर‑शरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में स्मार्ट आर्ट ड्रॉइंग को अपडेट करना सीखें। सुनिश्चित करें कि आपके दृश्य हमेशा सटीक हों। | | [C# का उपयोग करके Word में आयत आकार बनाएं – चरण‑दर‑चरण गाइड](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | C# के साथ Aspose.Words का उपयोग करके Word दस्तावेज़ में आयत आकृति जोड़ना और अनुकूलित करना सीखें। | -| [वर्टिकल एंकर](./vertical-anchor/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में टेक्स्टबॉक्स के लिए वर्टिकल एंकर पोजिशन सेट करना सीखें। आसान चरण-दर-श...| +| [वर्टिकल एंकर](./vertical-anchor/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में टेक्स्टबॉक्स के लिए वर्टिकल एंकर पोजिशन सेट करना सीखें। आसान चरण‑दर‑श...| | [स्मार्ट आर्ट आकार का पता लगाएं](./detect-smart-art-shape/) | इस व्यापक गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में SmartArt आकृतियों का पता लगाना सीखें। आपके दस्तावेज़ वर्कफ़्लो को स्वचालित करने के लिए बिल्कुल सही। | -| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण-दर-श... | -| [Aspose.Words आकृति शैडो ट्यूटोरियल – C# में Word आकृति में शैडो जोड़ें](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | C# में Aspose.Words का उपयोग करके Word आकृति में शैडो कैसे जोड़ें, इस चरण-दर-चरण ट्यूटोरियल के साथ सीखें। | +| [स्मार्ट आर्ट ड्राइंग अपडेट करें](./update-smart-art-drawing/) | इस चरण‑दर‑श... | +| [Aspose.Words आकृति शैडो ट्यूटोरियल – C# में Word आकृति में शैडो जोड़ें](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | C# में Aspose.Words का उपयोग करके Word आकृति में शैडो कैसे जोड़ें, इस चरण‑दर‑चरण ट्यूटोरियल के साथ सीखें। | | [छाया वाले आयत आकार के साथ खाली Word दस्तावेज़ बनाएं – चरण‑दर‑चरण गाइड](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Aspose.Words का उपयोग करके छाया वाले आयत आकार के साथ एक खाली Word दस्तावेज़ बनाने के चरण‑दर‑चरण निर्देश। | +| [Aspose.Words में शैडो को कैसे मूव करें – पूर्ण C# गाइड](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Aspose.Words में C# का उपयोग करके आकृति की छाया को स्थानांतरित करने की चरण‑दर‑शिक्षा। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/hindi/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..e4d3d1a076 --- /dev/null +++ b/words/hindi/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-01 +description: C# का उपयोग करके Aspose.Words में किसी आकार पर छाया को कैसे ले जाएँ। + मिनटों में आकार में छाया जोड़ना, ब्लर बदलना, पारदर्शिता सेट करना और छाया को घुमाना + सीखें। +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: hi +og_description: C# का उपयोग करके Aspose.Words में किसी आकार पर छाया को कैसे ले जाएँ। + यह ट्यूटोरियल आपको दिखाता है कि आकार में छाया कैसे जोड़ें, ब्लर बदलें, पारदर्शिता + सेट करें, और छाया को घुमाएँ। +og_title: Aspose.Words में शैडो कैसे मूव करें – पूर्ण C# गाइड +tags: +- Aspose.Words +- C# +- Document Automation +title: Aspose.Words में छाया को कैसे स्थानांतरित करें – पूर्ण C# गाइड +url: /hi/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words में शैडो कैसे मूव करें – पूर्ण C# गाइड + +क्या आपने कभी **शैडो को कैसे मूव करें** इस बारे में सोचा है कि Word दस्तावेज़ में किसी आकार की शैडो को बिना Word को मैन्युअली खोले कैसे बदलें? मेरे दैनिक काम में, मुझे अक्सर प्रोग्रामेटिक रूप से आकार की शैडो को ट्यून करना पड़ता है—चाहे वह एक पॉलिश्ड रिपोर्ट हो या एक डायनामिक टेम्पलेट। अच्छी खबर? Aspose.Words के साथ आप इसे कुछ ही लाइनों में कर सकते हैं, और आप **add shadow to shape**, **how to change blur**, **how to set transparency**, और **how to rotate shadow** भी एक ही पास में सीखेंगे। + +इस ट्यूटोरियल में हम एक वास्तविक परिदृश्य पर चलते हैं: एक मौजूदा DOCX फ़ाइल को लोड करना जिसमें पहले से ही एक आकार मौजूद है, शैडो की स्थिति, नरमी, अपारदर्शिता और दिशा को समायोजित करना, और अंत में परिणाम को सेव करना। अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं, और आप समझेंगे कि प्रत्येक प्रॉपर्टी क्यों महत्वपूर्ण है। + +## आवश्यकताएँ – शुरू करने से पहले आपको क्या चाहिए + +- **Aspose.Words for .NET** (संस्करण 23.12 या बाद का)। आप इसे NuGet से `Install-Package Aspose.Words` कमांड से प्राप्त कर सकते हैं। +- एक .NET 6+ विकास पर्यावरण (Visual Studio, VS Code, Rider—जो भी आपको पसंद हो)। +- एक इनपुट Word फ़ाइल (`input.docx`) जिसमें पहले से कम से कम एक आकार (आयत, वृत्त, या चित्र) हो। +- C# सिंटैक्स की बुनियादी समझ—कुछ भी जटिल नहीं। + +यदि आप इनमें से कोई भी चीज़ नहीं रखते, तो एक क्षण रुकें और लाइब्रेरी इंस्टॉल करें; गाइड का बाकी हिस्सा मानता है कि पैकेज पहले से ही रेफ़रेंस किया गया है। + +## Step 1: Load the Document and Grab the Target Shape – **How to Move Shadow** Begins Here + +सबसे पहले हम स्रोत दस्तावेज़ को लोड करते हैं और उस आकार को खोजते हैं जिसे हम संशोधित करना चाहते हैं। Aspose.Words हर ऑब्जेक्ट (पैराग्राफ, टेबल, शैप) को ट्री में एक नोड के रूप में मानता है, इसलिए हम इसे सीधे क्वेरी कर सकते हैं। + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Why this matters:** दस्तावेज़ को एक बार लोड करके उसी `Document` इंस्टेंस को पुन: उपयोग करना कुशल है। `GetChild` कॉल सुरक्षित है क्योंकि यदि इंडेक्स रेंज से बाहर है तो यह `null` लौटाता है, जिससे हम गायब आकारों को सहजता से हैंडल कर सकते हैं। + +## Step 2: Adjust the Blur Radius – Master **How to Change Blur** + +एक मुलायम शैडो प्रोफेशनल दिखती है, जबकि कठोर किनारा सस्ता महसूस हो सकता है। `BlurRadius` प्रॉपर्टी पॉइंट्स में नरमी को नियंत्रित करती है (1 pt ≈ 1/72 इंच)। चलिए इसे 8 pt तक बढ़ाते हैं। + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** डिफ़ॉल्ट ब्लर 0.5 pt है। 5 pt से ऊपर की कोई भी मान आमतौर पर दिखाई देती है, लेकिन बहुत बड़ी न करें—यह आकार को पेज से अलग दिखा सकता है। + +## Step 3: Set Transparency – The Answer to **How to Set Transparency** + +ट्रांसपेरेंसी निर्धारित करती है कि शैडो कितनी पारदर्शी है। `0` का मान पूरी तरह अपारदर्शी दर्शाता है; `1` पूरी तरह अदृश्य। सूक्ष्म प्रभाव के लिए हम `0.3` (30 % ट्रांसपेरेंट) का उपयोग करेंगे। + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Why you might care:** यदि आकार गहरा है, तो पूरी तरह अपारदर्शी शैडो नीचे के टेक्स्ट को डुबो सकता है। ट्रांसपेरेंसी को समायोजित करने से दस्तावेज़ पढ़ने योग्य रहता है जबकि गहराई बनी रहती है। + +## Step 4: Move the Shadow – The Core of **How to Move Shadow** + +`Distance` प्रॉपर्टी निर्धारित करती है कि शैडो आकार से कितनी दूरी पर ऑफ़सेट है, पॉइंट्स में मापी जाती है। बड़ी दूरी शैडो को अधिक दूर धकेलती है, जिससे अधिक नाटकीय प्रभाव बनता है। + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **What if you need a tiny offset?** `Distance` को `0` सेट करने से शैडो सीधे आकार के पीछे बैठ जाएगी, जो एम्बॉसिंग इफ़ेक्ट के लिए उपयोगी हो सकता है। + +## Step 5: Rotate the Light Source – Solving **How to Rotate Shadow** + +शैडो केवल नीचे की ओर नहीं गिरती; यह लाइट सोर्स के एंगल का अनुसरण करती है। `Angle` प्रॉपर्टी (डिग्री में) शैडो को आकार के चारों ओर घुमाती है। चलिए इसे 45° तक झुकाते हैं। + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Quick experiment:** `90` आज़माएँ ताकि दाएँ‑हाथ शैडो मिले या `-30` बाएँ‑झुकी शैडो के लिए। दृश्य परिवर्तन तुरंत दिखेगा। + +## Step 6: Save the Document – Seeing the Result of **Add Shadow to Shape** + +अब जब हमने शैडो को ट्यून कर दिया है, हम दस्तावेज़ को डिस्क पर लिखेंगे। आप मूल फ़ाइल को ओवरराइट कर सकते हैं या नई फ़ाइल बना सकते हैं; उदाहरण में नई आउटपुट फ़ाइल का उपयोग किया गया है। + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Expected output:** `output.docx` खोलें। आकार की शैडो अधिक मुलायम, थोड़ा ऑफ़सेट, अर्ध‑पारदर्शी, और 45° पर एंगल्ड दिखेगी। यदि आप इसे `input.docx` के साथ साइड‑बाय‑साइड तुलना करेंगे, तो अंतर स्पष्ट होगा। + +### Full Working Example (Copy‑Paste Ready) + +नीचे पूरा प्रोग्राम एक ब्लॉक में दिया गया है। इसे एक नए कंसोल प्रोजेक्ट में पेस्ट करें, `YOUR_DIRECTORY` को वास्तविक फ़ोल्डर पाथ से बदलें, और चलाएँ। + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Common Questions & Edge Cases + +### What if the document has multiple shapes? + +यदि दस्तावेज़ में कई आकार हैं तो आप सभी आकारों पर लूप कर सकते हैं: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Can I add a shadow to a shape that currently has none? + +क्या मैं ऐसे आकार में शैडो जोड़ सकता हूँ जिसमें अभी तक शैडो नहीं है? + +बिल्कुल। `ShadowFormat` ऑब्जेक्ट हमेशा मौजूद रहता है; आपको केवल इसे एनेबल करना है: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Does this work with pictures and SmartArt? + +क्या यह चित्रों और SmartArt के साथ काम करता है? + +हां। `Shape` से डेराइव्ड कोई भी नोड—जिसमें चित्र, चार्ट, और SmartArt शामिल हैं—`ShadowFormat` को एक्सपोज़ करता है। वही प्रॉपर्टीज़ लागू होती हैं। + +### How do I control the shadow color? + +शैडो का रंग कैसे नियंत्रित करूँ? + +`Color` प्रॉपर्टी का उपयोग करें: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Compatibility concerns? + +अनुकूलता संबंधी चिंताएँ? + +Aspose.Words 23.12+ .NET 6, .NET Core 3.1, और .NET Framework 4.6.2+ को सपोर्ट करता है। दिखाया गया API इन संस्करणों में स्थिर है। + +## Conclusion + +हमने अभी **how to move shadow** को Aspose.Words का उपयोग करके आकार पर लागू किया, और इस दौरान **add shadow to shape**, **how to change blur**, **how to set transparency**, और **how to rotate shadow** भी दर्शाए। पूर्ण, चलाने योग्य उदाहरण आपको किसी भी आकार की शैडो को कुछ सेकंड में ट्यून करने देता है, जिससे आपके दस्तावेज़ बिना Word खोले ही पॉलिश्ड और प्रोफ़ेशनल लुक प्राप्त करते हैं। + +अगले कदम के लिए तैयार हैं? इन शैडो ट्यूनिंग को **conditional formatting** के साथ मिलाएँ—उदाहरण के लिए, केवल हेडिंग्स या उन चार्ट्स पर गहरी शैडो लागू करें जिनका आकार निश्चित सीमा से अधिक हो। या आकार के लिए **gradient fills** का प्रयोग करके एक वास्तव में आकर्षक डिज़ाइन बनाएँ। + +यदि आपको कोई समस्या आती है, तो नीचे टिप्पणी छोड़ें। Happy coding, और आपकी शैडो हमेशा वहीँ गिरें जहाँ आप चाहते हैं! + +![शैडो को एक आकार पर ले जाने के प्रभाव को दर्शाने वाला आरेख – शैडो कैसे ले जाएँ उदाहरण](https://example.com/images/shadow-demo.png "शैडो कैसे ले जाएँ उदाहरण") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/basic-conversions/_index.md b/words/hongkong/net/basic-conversions/_index.md index a802f472b1..ef8ca4c68f 100644 --- a/words/hongkong/net/basic-conversions/_index.md +++ b/words/hongkong/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [將 PDF 儲存為 Jpeg](./pdf-to-jpeg/) |使用 Aspose.Words for .NET 輕鬆將 PDF 轉換為 JPEG。請遵循我們的詳細指南,其中包含範例和常見問題。非常適合開發人員和愛好者。 | | [將 PDF 儲存為 Word 格式 (Docx)](./pdf-to-docx/) |透過本詳細的逐步指南了解如何使用 Aspose.Words for .NET 將 PDF 轉換為 Word 文件 (Docx)。非常適合開發人員。 | | [使用 Aspose.Words 將 Word 儲存為 PDF – 完整 C# 教學](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | 完整指南教您在 C# 中使用 Aspose.Words 將 Word 檔案儲存為 PDF,提供程式碼範例與最佳實踐。 | +| [使用 Aspose.Words 將 Word 儲存為 PDF – 完整指南](./save-word-as-pdf-with-aspose-words-complete-guide/) | 完整指南教您使用 Aspose.Words 將 Word 檔案儲存為 PDF,提供程式碼範例與最佳實踐。 | | [使用 Aspose.Words 將 Docx 儲存為 PDF – 完整 C# 教學](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | 完整指南教您在 C# 中使用 Aspose.Words 將 Docx 檔案儲存為 PDF,提供程式碼範例與最佳實踐。 | diff --git a/words/hongkong/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/hongkong/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index ebe29ee99e..62ed1bc246 100644 --- a/words/hongkong/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/hongkong/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,24 +1,22 @@ --- category: general -date: 2025-12-29 -description: 如何使用 Aspose.Words 從 Word 匯出 LaTeX – 學習將 Word 轉換為 LaTeX、將 docx 儲存為 txt,並在純文字中處理方程式。 +date: 2026-05-01 +description: 學習如何從 Word 檔案匯出 LaTeX、將 Word 轉換為 txt,並使用 Aspose.Words 在 C# 中保留表格。 draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: zh-hant -og_description: 如何使用 Aspose.Words 從 Word 匯出 LaTeX。本指南將向您展示如何將 Word 轉換為 LaTeX、將 docx - 儲存為 txt,並保持公式完整。 -og_title: 如何從 Word 匯出 LaTeX – 快速 C# 教學 +og_description: 了解如何從 Word 匯出 LaTeX、將 Word 轉換為純文字,並使用 Aspose.Words 保持表格版面不變。 +og_title: 如何從 Word 匯出 LaTeX – 完整 C# 教學 tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: 如何從 Word 匯出 LaTeX – 步驟指南 +title: 如何從 Word 匯出 LaTeX – 逐步指南 url: /zh-hant/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -26,178 +24,215 @@ url: /zh-hant/net/basic-conversions/how-to-export-latex-from-word-step-by-step-g {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# 如何從 Word 匯出 LaTeX – 步驟說明指南 +# 如何從 Word 匯出 LaTeX – 完整 C# 教學 -有沒有想過 **如何從 Word 匯出 LaTeX**,卻不會遺失那些複雜的 Office Math 方程式?你並不是唯一有此困擾的人。許多開發者在嘗試 *將 Word 轉換成 LaTeX* 以撰寫學術論文、科學報告或自動化出版流程時,都會卡關。 +有沒有想過 **如何從 Word 文件匯出 LaTeX**,而且不會遺失任何數學公式?你並不孤單。許多開發者需要將含有 Office Math 的 .docx 轉成乾淨的 LaTeX,同時 **convert Word to txt** 以供後續處理。在本指南中,我們將一步步示範一個可直接執行的解決方案,**保留表格**、產生純文字檔,且讓 LaTeX 標記正好出現在需要的地方。 -在本教學中,我們將示範一個完整、可直接執行的 C# 範例,說明 **如何匯出 LaTeX**,教你 **如何儲存含 LaTeX 標記的 txt** 檔,甚至涵蓋 **convert word equations latex** 的細節,確保不會遺失任何資訊。 +我們會從載入來源檔案說起,接著調整 `TxtSaveOptions`,讓輸出既易讀又適合機器處理。完成後,你將能 **save docx as txt**、**convert Word to plain text**,並了解 **how to preserve tables** 的做法。全程不需要外部腳本或手動複製貼上——只要純 C# 程式碼,隨時可放入任何 .NET 專案。 -> **小技巧:** 同樣的作法適用於任何 .docx 檔,只要把程式碼指向不同的檔案路徑即可。 +## 需要的環境 + +- **Aspose.Words for .NET**(最新版,2024.x 或更新)。NuGet 套件名稱為 `Aspose.Words`。 +- .NET 開發環境(Visual Studio、VS Code、Rider 任一即可)。 +- 一個包含 Office Math 公式且至少有一個表格的 Word 檔案(`.docx`),讓我們能看到表格保留的魔法。 + +就這些。如果你已備妥,繼續閱讀;否則先取得 NuGet 套件與範例 DOCX 再深入。 --- -## 需要的環境 +## 如何從 Word 文件匯出 LaTeX -在開始之前,請先確認已具備以下前置條件: +以下是本教學的核心——三個簡潔步驟,解答 **how to export latex** 同時兼顧 **convert word to txt**、**convert word to plain text**、**save docx as txt**、以及 **how to preserve tables** 等需求。 -| 前置條件 | 為什麼需要 | -|--------------|----------------| -| **.NET 6.0+**(或 .NET Framework 4.6+) | Aspose.Words 針對現代 .NET 執行環境開發。 | -| **Aspose.Words for .NET** NuGet 套件(`Aspose.Words`) | 此函式庫負責解析 Word 並產生 LaTeX。 | -| **一個包含至少一個 Office Math 方程式的 .docx 範例** | 觀察 LaTeX 轉換的實際效果。 | -| **Visual Studio 2022**(或任意你喜歡的 IDE) | 讓除錯與執行範例變得輕鬆。 | +### 步驟 1:載入 DOCX 檔案 -如果尚未安裝 NuGet 套件,請執行: +首先,我們需要把 Word 文件讀入 `Aspose.Words.Document` 物件。無論之後是 **convert word to txt** 還是 **save docx as txt**,這一步都是相同的。 -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -就這樣——不需要額外的 DLL、也不需要 COM interop,只有乾淨的受管理函式庫。 +> **為什麼重要:** 載入檔案會在記憶體中建立所有 Word 元素的表示——段落、表格與 Office Math 物件。沒有這個物件,就無法操作匯出選項。 ---- +### 步驟 2:為 LaTeX 與表格佈局設定 `TxtSaveOptions` -## 如何從 Word 匯出 LaTeX – 概觀 +`TxtSaveOptions` 類別讓你精確控制純文字檔的產生方式。以下兩個屬性是本情境的關鍵: -以下是我們將完成的整體流程: +| 屬性 | 功能說明 | 為什麼需要 | +|------|----------|------------| +| `OfficeMathExportMode` | 決定 Office Math 的呈現方式。設定為 `LaTeX` 後,公式會轉成 LaTeX 語法。 | 這就是 **how to export latex** 的核心。 | +| `PreserveTableLayout` | 設為 `true` 時,Aspose 會加入空白,使表格保有類似格線的外觀。 | 滿足 **how to preserve tables**,同時 **convert word to txt**。 | -1. **載入**來源 Word 文件(`.docx`)。 -2. **設定** `TxtSaveOptions`,讓所有 Office Math 物件以 LaTeX 形式輸出。 -3. **儲存**為純文字(`.txt`)檔,之後即可直接交給任何 LaTeX 編譯器。 +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![如何從 Word 匯出 LaTeX 範例](image.png "如何從 Word 匯出 LaTeX") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **小技巧:** 若只需要原始 LaTeX 而不在乎表格格式,可將 `PreserveTableLayout` 設為 `false`。檔案會更小,但會失去視覺上的表格提示。 -## 步驟 1:載入 Word 文件 +### 步驟 3:將文件儲存為純文字 -首先,打開要轉換的 .docx。`Document` 類別會將底層的 XML 抽象化,提供友善的物件模型。 +現在使用剛才定義的選項,把文件寫入 `.txt` 檔。這一行即可一次完成 **convert word to plain text**、**save docx as txt**,以及 **how to export latex**。 ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**為什麼重要:** -提前載入檔案可以讓我們在序列化前檢查內容(例如方程式數量)。若檔案損毀,`Document` 會拋出明確的例外,避免之後產生莫名其妙的輸出。 +執行完畢後,開啟 `output.txt`,你會看到: ---- +- 每個 Office Math 公式皆以 `\frac{a}{b}` 之類的 LaTeX 片段呈現。 +- 表格以 `|` 與 `-` 字元繪製,保持欄位對齊。 +- 普通段落則為純文字,隨時可供下游解析器使用。 -## 步驟 2:設定 TxtSaveOptions 以匯出 LaTeX +### 完整範例程式 -魔法發生在 `TxtSaveOptions`。將 `OfficeMathExportMode` 設為 `LaTeX`,即可把每個 Office Math 物件轉換成對應的 LaTeX 表示。 +把所有步驟合併,以下是一個可直接編譯執行的自包含程式: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**為什麼選擇這些設定:** +**預期輸出**(節錄): -- `OfficeMathExportMode.LaTeX` 是唯一能保證數學式忠實翻譯的模式。 -- `PreserveTableLayout` 讓表格的外觀保持與 Word 中相同,方便之後嵌入 LaTeX 的 `tabular` 環境。 -- UTF‑8 確保「α」、「β」或「∑」等字元在往返過程中不會遺失。 +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -如果你想 **convert word to latex** 而不使用純文字包裝,只需改用 `SaveFormat.LaTeX`——這是進階情境的快速提示。 +可以看到表格仍保有格線,公式則是乾淨的 LaTeX。這正是同時 **convert word to txt** 且忠實保留結構與數學的最佳平衡。 --- -## 步驟 3:將文件儲存為文字檔 +## 轉換 Word 為 TXT 並保留表格的技巧 -現在把含 LaTeX 的文字寫入磁碟。產生的 `.txt` 之後可以改名為 `.tex`,或直接 pipe 給 LaTeX 編譯器。 +雖然三步法已能應付大多數情況,實務專案常會遇到各種挑戰。以下提供實用建議,讓你的 **convert word to plain text** 流程更穩健。 -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### 使用一致的編碼 -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` 預設為 UTF‑8,能處理大多數字元。若需其他代碼頁(例如舊系統期待的 Windows‑1252),請設定 `Encoding` 屬性: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**`output.txt` 內的內容會是這樣:** +### 修剪多餘的空白 -``` -\begin{equation} -E = mc^{2} -\end{equation} +欄位很多的表格會產生過長的行。儲存後,你可以後處理檔案,將連續空格壓縮成單一 Tab: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -所有其他段落會以純文字形式呈現,而任何 Office Math 方程式則會被包在 LaTeX 的 `equation` 環境(若在 Word 中為行內則為 `inline`)。這正好滿足 **convert word equations latex** 的需求。 +### 處理巢狀表格 ---- +若 DOCX 含有表格內嵌表格,`PreserveTableLayout` 仍會保留視覺層次,但縮排可能顯得怪異。快速解法是將前導空格替換為自訂標記(例如 `>>`),讓下游解析器能偵測巢狀層級。 -## 邊緣案例與常見問題 +### 批次處理多個檔案 -| 情境 | 處理方式 | -|-----------|------------| -| **來源文件沒有方程式** | 仍會正常轉換,只會得到純文字,且不會額外產生 LaTeX 程式碼。 | -| **文件非常大(>100 MB)** | 考慮使用 `MemoryStream` 串流輸出,以降低記憶體使用量。 | -| **不支援的數學結構** | Aspose.Words 已覆蓋 99 % 的 Office Math。若遇到極少數例外,可能需要手動後處理 LaTeX。 | -| **需要 .tex 檔而非 .txt** | 把 `outputPath` 改成以 `.tex` 結尾,並可自行設定 `txtOptions.Encoding = Encoding.UTF8`。 | -| **在 Linux/macOS 上執行** | 程式碼相同,只要確保檔案路徑使用正斜線或 `Path.Combine` 即可。 | +當需要為數十份文件 **convert word to txt** 時,可將邏輯包在迴圈內: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +如此即可一次 **save docx as txt** 多檔,免除手動操作。 -## 如何儲存含 LaTeX 方程式的 TXT – 快速回顧 +--- -1. **載入** .docx(`Document`)。 -2. **設定** `OfficeMathExportMode = LaTeX` 於 `TxtSaveOptions`。 -3. **儲存**(`doc.Save`)時使用上述選項。 +## 常見陷阱與避免方式 -以上即完成 **how to save txt** 含 LaTeX 方程式的完整流程。 +1. **忘記設定 LaTeX 匯出模式** – 若未將 `OfficeMathExportMode = OfficeMathExportMode.LaTeX`,公式會退回純文字(例如 “Equation 1”)。務必檢查選項區塊。 +2. **表格佈局遺失** – `PreserveTableLayout` 的預設值為 `false`。若輸出變成一長串文字,可能是忘記開啟此旗標。 +3. **檔案路徑含空格** – 使用原始字串(`@"C:\My Folder\input.docx"`)可避免跳脫問題,否則會拋出 `FileNotFoundException`。 +4. **版本不相容** – 早於 21.9 版的 Aspose.Words 不支援 `OfficeMathExportMode`。請升級至最新套件,確保 **how to export latex** 能正常運作。 +5. **非 ASCII 字元的編碼錯誤** – 若看到 � 符號,請明確設定 `options.Encoding` 為 UTF‑8 或相應的代碼頁。 --- -## 加分技巧:批次自動轉換多個檔案 +## 延伸應用:從 TXT 轉成 Markdown 或 HTML -若有一整個資料夾的 Word 文件,只要把上述邏輯包在簡單的迴圈裡: +有時你需要的不只是純文字——例如想要保留 LaTeX 區塊的 Markdown 檔。只要把 `TxtSaveOptions` 換成 `HtmlSaveOptions` 或 `MarkdownSaveOptions` 即可: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -這樣就能 **convert word to latex** 批次處理——非常適合每日收到大量手稿的研究團隊。 +這個小變動讓你在 **convert word to txt** 風格的輸出中,同時保有喜愛的 Markdown 語法。 --- ## 結論 -我們已逐步說明 **如何從 Word 匯出 LaTeX**,示範了 **如何儲存含 LaTeX 方程式的 txt**,並展示了 **convert word equations latex** 時不會遺失任何資訊的完整作法。 +我們已完整示範如何從 Word 文件 **export latex**,同時說明 **convert word to txt**、**convert word to plain text**、**save docx as txt**,以及 **how to preserve tables** 的作法。關鍵要點如下: + +- 使用 `Aspose.Words.Document` 載入 DOCX。 +- 設定 `TxtSaveOptions.OfficeMathExportMode = LaTeX` 並將 `PreserveTableLayout = true`。 +- 呼叫 `doc.Save(outputPath, options)`,即可取得含 LaTeX 的純文字檔。 -只要幾行 C# 程式碼,加上功能強大的 Aspose.Words 函式庫,就能把任何 .docx 轉成 LaTeX 準備好的文字,方便嵌入學術論文、教科書或自動化出版流程。 +請在自己的檔案上試試看,調整編碼設定,或批次處理整個資料夾。若遇到巢狀表格、特殊字元或舊版 Aspose 等邊緣情況,請回顧「技巧」與「陷阱」章節取得快速解決方案。 -**接下來要做什麼?** 嘗試把產生的 `.txt`(或改名為 `.tex`)交給 `pdflatex` 或 `xelatex`,產出 PDF;或探索 `SaveFormat.LaTeX` 直接產生 `.tex` 檔的選項。若想 **save docx as txt** 同時保留格式,可再實驗 `PreserveTableLayout` 與自訂換行處理。 +準備好下一步了嗎?試著把同一個 DOCX 轉成 Markdown,或將產生的 `.txt` 交給能在網頁上渲染 LaTeX 的靜態網站產生器。可能性無限,而你現在已擁有堅實的 **convert word to txt** 工作流程基礎。 -有關邊緣案例、授權或效能調校的問題嗎?歡迎在下方留言——祝開發順利! +祝開發順利,願你的 LaTeX 永遠一次編譯成功! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/hongkong/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/hongkong/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..4f8b237ac4 --- /dev/null +++ b/words/hongkong/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 於 C# 將 Word 另存為 PDF。學習如何將 docx 轉換為 PDF、偵測缺少字型,並有效處理字型替換警告。 +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: zh-hant +og_description: 使用 Aspose.Words 將 Word 儲存為 PDF。本逐步教學示範如何將 docx 轉換為 PDF 並偵測缺失字型。 +og_title: 使用 Aspose.Words 將 Word 另存為 PDF – 完整指南 +tags: +- Aspose.Words +- C# +- PDF conversion +title: 使用 Aspose.Words 將 Word 另存為 PDF – 完整指南 +url: /zh-hant/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.Words 將 Word 儲存為 PDF – 完整指南 + +是否曾經需要即時 **save Word as PDF**,並擔心途中會缺少字型?你並不孤單——開發者在轉換文件時常常為缺字型問題頭疼。在本指南中,我們將示範一個實作方案,不僅能 **convert docx to pdf**,還能使用 Aspose.Words 的字型替換警告 **detect missing fonts**。 + +我們將涵蓋從設定警告收集器到解讀輸出結果的全部內容,最後你將清楚知道如何 **save Word as PDF** 而不會有意外。無需外部工具,無需複雜設定——只要乾淨的 C# 程式碼即可直接放入任何 .NET 專案。 + +## 需要的條件 + +- **Aspose.Words for .NET** (最新版本,例如 24.10) – 你可以透過 NuGet 取得 (`Install-Package Aspose.Words`)。 +- .NET 開發環境(Visual Studio、Rider,或 VS Code 都可以)。 +- 一個可能包含目標機器未安裝字型的範例 DOCX 檔案。 +就這樣。只要具備上述基礎,我們就可以開始深入探討。 + +## Save Word as PDF – 步驟概覽 + +以下是完整、可執行的程式碼。隨意將它複製貼上到 Console 應用程式專案中,然後按 **F5**。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** 將 `YOUR_DIRECTORY` 替換為絕對路徑,或使用 `Path.Combine(Environment.CurrentDirectory, "input.docx")` 以取得相對且更安全的方式。 + +### 為何使用 Warning Callback + +Aspose.Words 會在背後靜默地將缺少的字型替換為備用字型(通常是 Arial)。如果沒有回呼,你永遠不會知道已發生替換,這可能導致最終 PDF 的版面配置出錯。透過掛接 `IWarningCallback`,我們可以取得每一次缺字型事件的清晰程式化清單——非常適合用於記錄或通知最終使用者。 + +### 偵測缺少字型 – 需要留意的地方 + +執行程式時,任何缺少的字型都會在主控台輸出類似以下的訊息: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +如果清單為空,恭喜——**save word as pdf** 已成功完成,且所有原始字型皆完整保留。 + +## Convert Docx to PDF – 自訂輸出 + +有時你需要特定的 PDF 版本、影像品質或符合性等級。Aspose.Words 允許你在呼叫 `Save` 之前調整 `PdfSaveOptions` 物件。 + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Why this matters:** 若你為法律檔案產生 PDF,設定 `PdfA1b` 可確保檔案符合嚴格標準。同樣的轉換仍會遵循我們的 warning callback,因此仍能 **detect missing fonts**。 + +## Aspose Words Font Substitution – 處理邊緣案例 + +### 情境 1:多個缺少字型 + +如果來源文件使用多種自訂字型,警告收集器會針對每個字型產生一筆條目。你可以將它們彙總: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### 情境 2:提供備用字型資料夾 + +Aspose.Words 可以搜尋額外的資料夾以尋找字型。於載入文件前,於 `FontSettings` 上設定 `FontsFolder` 屬性: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +現在函式庫會先嘗試你的自訂資料夾,降低不必要的替換機會。 + +### 情境 3:忽略替換 + +如果你希望在缺少字型時讓轉換失敗(而非靜默替換),可在回呼內拋出例外: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +這會迫使你在繼續之前先解決缺少的字型——在不容許靜默失敗的 CI 流程中相當有用。 + +## 完整端對端範例 + +將所有內容整合在一起,以下是一個精簡版範例,示範 **how to convert Word to PDF**、設定自訂 PDF 選項,並記錄任何字型問題: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**預期的主控台輸出**(若缺少 Calibri): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +如果沒有任何警告,表示你的 **save word as pdf** 操作使用了與來源 DOCX 完全相同的字型。 + +## 視覺摘要 + +![save word as pdf 工作流程圖示](https://example.com/diagram.png "save word as pdf 工作流程") + +*圖片說明文字:* **save word as pdf** 工作流程,顯示載入、警告收集與 PDF 輸出。 + +## 常見問題與解答 + +| Question | Answer | +|----------|--------| +| **我需要 Aspose.Words 的授權嗎?** | 免費的評估授權可用於測試,但正式環境使用需購買授權以移除評估浮水印。 | +| **這在 .NET Core / .NET 6+ 上能運作嗎?** | 絕對可以——Aspose.Words 以 .NET Standard 2.0 為目標,任何近期的 .NET 執行環境皆相容。 | +| **我可以在迴圈中轉換多個 DOCX 檔案嗎?** | 可以,只要為每個檔案建立新的 `Document`,若想彙總結果亦可重複使用相同的 `WarningInfoCollector`。 | +| **如果輸出資料夾不存在會怎樣?** | `Document.Save` 會拋出 `DirectoryNotFoundException`。請先建立資料夾,或使用 `Directory.CreateDirectory`。 | +| **有沒有方法將缺少的字型嵌入 PDF?** | 若機器上有該字型,Aspose.Words 可自動嵌入;只需設定 `PdfSaveOptions.EmbedFullFonts = true`。 | + +## 結論 + +現在你已掌握一套穩固、可投入生產環境的模式,能在 **save Word as PDF** 的同時 **detect missing fonts**,並處理 **Aspose.Words font substitution** 情境。透過掛接 warning callback、客製化字型資料夾,並視需要調整 `PdfSaveOptions`,即可可靠地 **convert docx to pdf**,並讓使用者了解可能影響版面忠實度的任何字型問題。 + +準備好進一步了嗎?試著平行產生多份文件的 PDF,或探索加入浮水印與數位簽章——這兩者都是你剛掌握程式碼的簡易延伸。祝開發順利,願你的 PDF 永遠如預期般完美! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-loadoptions/_index.md b/words/hongkong/net/programming-with-loadoptions/_index.md index 824d1497dc..2b79c7de43 100644 --- a/words/hongkong/net/programming-with-loadoptions/_index.md +++ b/words/hongkong/net/programming-with-loadoptions/_index.md @@ -37,6 +37,7 @@ Aspose.Words for .NET 教學課程為希望掌握使用 LoadOptions 進行文字 | [使用 Aspose.Words 在 C# 中復原 Word 文件](./recover-word-document-with-aspose-words-in-c/) |了解如何使用 Aspose.Words for .NET 在 C# 中復原受損的 Word 文件,確保資料完整性。 | | [恢復受損的 Word 檔案 – 完整指南:開啟損壞的 DOCX 並取得頁數](./recover-damaged-word-file-complete-guide-to-open-corrupted-d/) |依照本逐步教學,使用 Aspose.Words for .NET 輕鬆恢復受損的 Word 檔案,開啟損壞的 DOCX 並取得頁數。 | +| [復原受損的 docx – 完整指南:在 C# 中載入損壞的 Word 檔案](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) |了解如何在 C# 中使用 Aspose.Words 載入受損的 docx 檔案,提供完整步驟與範例說明。 | | [如何恢復 docx – C# 受損 Word 檔案指南](./how-to-recover-docx-c-guide-for-corrupted-word-files/) |了解如何使用 Aspose.Words for .NET 在 C# 中恢復受損的 docx 文件。 | | [如何復原 docx – 設定復原模式並開啟受損的 Word 檔案](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) |了解如何設定復原模式以開啟受損的 Word 檔案,恢復 docx 文件內容。 | | [如何在 Aspose.Words 中使用 LoadOptions – 完整指南](./how-to-use-loadoptions-in-aspose-words-complete-guide/) |了解如何使用 Aspose.Words for .NET 的 LoadOptions 完整設定與應用,提供步驟說明與範例程式碼。 | diff --git a/words/hongkong/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/hongkong/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..5ab0fef1a2 --- /dev/null +++ b/words/hongkong/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 快速恢復受損的 docx 檔案。了解如何設定復原模式、安全載入 docx,以及僅需幾個步驟即可讀取受損的 + Word 檔案。 +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: zh-hant +og_description: 修復 C# 中受損的 docx 檔案。設定復原模式,安全載入 docx,並使用 Aspose.Words 讀取受損的 Word 檔案。 +og_title: 修復受損的 docx – 快速 C# 指南 +tags: +- Aspose.Words +- C# +- Document Recovery +title: 修復損毀的 docx – C# 完整載入受損 Word 檔案指南 +url: /zh-hant/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 恢復損毀的 docx – 快速 C# 指南 + +有沒有試過打開一個根本無法載入的 Word 檔案,並懷疑內容是否永遠遺失?在許多實務專案中,你會 **recover corrupted docx** 檔案,而不必請使用者重新傳送附件。好消息是 Aspose.Words 讓這件事變得輕而易舉:只需設定恢復模式,讓函式庫自行處理繁重工作。 + +在本教學中,我們將逐步說明如何 **recover corrupted docx** 檔案,解釋為什麼 `RecoveryMode.AutoRecover` 選項是最安全的選擇,並示範如何 **how to load docx** 可能部分損壞的檔案。完成後,你將能讀取損壞的 Word 檔案,擷取仍存活的文字,甚至記錄原始格式以供未來稽核。無需外部工具,僅使用純淨的 C# 程式碼。 + +## 需要的條件 + +- **Aspose.Words for .NET** (any recent version; the API we use works with 23.5 and newer). (任何近期版本;我們使用的 API 支援 23.5 及更新版本)。 +- A .NET development environment (Visual Studio, VS Code, or Rider). (.NET 開發環境 (Visual Studio、VS Code 或 Rider)。) +- The corrupted or partially damaged `.docx` you want to salvage. (你想要修復的損壞或部分損毀的 `.docx`)。 + +不需要特殊權限、COM interop,也不必在伺服器上安裝 Microsoft Office。很簡單,對吧? + +## 步驟 1:設定恢復模式為 Auto‑Recover + +當 Word 檔案損毀時,預設的載入行為會拋出例外並中止。透過設定 `LoadOptions` 物件,你告訴 Aspose.Words **set recovery mode** 為 `AutoRecover`,它會掃描 zip 包,跳過無法讀取的部分,並返回能拼湊出的內容。 + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **為什麼選擇 AutoRecover?** +> 它會盡可能多地讀取內容,同時保持 document 物件可用。如果你選擇 `RecoveryMode.NoRecovery`,載入會在第一個損毀處失敗,這會抵消 **recover corrupted docx** 情境的目的。 + +## 步驟 2:使用已設定的選項載入文件 + +現在已設定恢復模式,你可以安全地嘗試開啟檔案。將 `"YOUR_DIRECTORY/input.docx"` 替換為實際的損毀檔案路徑。 + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +如果檔案僅部分損毀,`Document` 實例仍會建立。若需要額外驗證,可稍後檢查 `document.IsStructureValid`。 + +## 步驟 3:驗證偵測到的格式 + +Aspose.Words 會自動偵測原始格式(DOC、DOCX、ODT 等)。列印此值可協助確認函式庫正確辨識檔案,這是在 **recover corrupted docx** 操作後的快速 sanity check。 + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +典型輸出: + +``` +Loaded with Docx format. +``` + +即使有些部分缺失,格式偵測仍會成功——這是 **recover corrupted docx** 工作流程的另一個成功。 + +## 步驟 4:擷取可取得的內容 + +文件載入後,你可以像處理任何正常的 Word 檔案一樣使用它。以下是一個簡潔範例,提取純文字並寫入主控台。這示範了即使是 **read damaged word file** 內容也不會當機。 + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +如果原始檔案的表格或圖片損毀,它們會在文字輸出中被省略。文件的其餘部分仍保持完整。 + +## 步驟 5:儲存乾淨的副本(可選) + +通常在恢復後,你會想提供使用者一個全新、乾淨的檔案版本。以相同格式儲存可確保與任何後續流程相容。 + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +現在你擁有一個 **recover damaged docx** 檔案,可安全地附加於電子郵件或傳遞給其他服務。 + +## 完整範例程式 + +將上述步驟整合起來,以下是完整、可直接執行的程式。將它貼到新的 console 專案中,調整檔案路徑,然後按 F5。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**預期輸出**(假設檔案包含單一段落 “Hello world!” 以及一些損毀的 XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +請注意程式從未當機——即使來源檔案部分損毀。這正是使用 Aspose.Words 進行 **recover corrupted docx** 的精髓。 + +## 常見問題與邊緣案例 + +### 如果檔案完全無法讀取? + +即使是 `AutoRecover` 也有其限制。如果 zip 容器本身損毀到無法修復,Aspose.Words 會拋出 `CorruptedFileException`。此時你可能需要使用第三方 zip 修復工具,然後再嘗試 **recover corrupted docx**。 + +### 我可以恢復其他格式嗎(例如 `.doc`、`.odt`)? + +當然可以。相同的 `LoadOptions` 可用於 Aspose.Words 支援的任何格式。只要更改檔案副檔名,函式庫會自動偵測原始格式。這表示你也能使用相同程式碼 **recover damaged docx**‑類似的檔案,例如 `.doc` 或 `.rtf`。 + +### 如何在不將整個文件載入記憶體的情況下處理大型文件? + +對於 GB 級別的檔案,你可以啟用 **load options** 如 `LoadOptions.LoadFormat` 或逐頁串流文件。然而,恢復演算法仍需讀取整個包,因此在處理非常大的損毀檔案時,記憶體使用量會較高。 + +### 有沒有方法得知哪些部分遺失了? + +載入後,你可以檢查 `document.GetChildNodes(NodeType.Any, true)`,並將計數與預期基準比較。缺失的表格、圖片或標頭會在節點集合中缺席。這讓你能精確記錄 **recover damaged docx** 的情況,並通知使用者。 + +## 專業提示:可靠的恢復 + +- **Validate the input file size** 在載入前驗證輸入檔案大小;零位元組的檔案必定失敗。 +- **Log the `RecoveryMode` result** 透過捕捉 `DocumentLoadingException` 並儲存例外訊息;它通常包含哪些部分被跳過的線索。 +- **Run the recovery on a background thread** 若在 Web 服務中處理上傳,請於背景執行緒執行恢復——可保持請求回應。 +- **Combine with a checksum**(例如 MD5)以偵測恢復後的檔案是否與原始檔不同;如此即可決定是否保留兩個版本。 + +## 結論 + +我們剛剛示範了如何在 C# 中透過 **setting recovery mode** 為 `AutoRecover` 來 **recover corrupted docx** 檔案,安全載入文件、擷取仍存活的文字,並可選擇儲存乾淨的副本。此方法讓你能 **how to load docx** 那些本會拋出例外的檔案,並提供一種可靠的方式在無需外部工具的情況下 **read damaged word file** 內容。 + +接下來的步驟?嘗試將 `RecoveryMode.AutoRecover` 換成 `RecoveryMode.NoRecovery` 觀察差異,或試驗 `LoadOptions` 中控制密碼處理與字型替換的屬性。你也可以將恢復流程整合到接受上傳並回傳修復檔案的 ASP.NET Core API 中——非常適合企業文件管理管線。 + +對 Word 文件恢復有更多問題,或想了解如何使用自訂回呼 **recover damaged docx** 檔案?在下方留言吧,祝編程愉快! + +![已恢復文件的示意圖 – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-markdownsaveoptions/_index.md b/words/hongkong/net/programming-with-markdownsaveoptions/_index.md index faadf329d8..4d1b0d2845 100644 --- a/words/hongkong/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hongkong/net/programming-with-markdownsaveoptions/_index.md @@ -32,11 +32,12 @@ | [將 docx 儲存為 markdown – 完整 C# 指南(含圖像提取)](./save-docx-as-markdown-full-c-guide-with-image-extraction/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 DOCX 轉換為 Markdown,並提取圖像。 | | [如何將 Word 匯出為 Markdown – 完整 C# 指南](./how-to-export-markdown-from-word-complete-c-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 Word 文件匯出為 Markdown,提供完整步驟與範例程式碼。 | | [如何將 DOCX 匯出為 Markdown – 完整 C# 指南](./how-to-export-markdown-from-docx-complete-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 DOCX 匯出為 Markdown,提供完整步驟與範例程式碼。 | -| [如何從 Word 匯出 LaTeX:使用 Aspose 將 DOCX 轉換為 Markdown](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) |示範如何使用 Aspose.Words for .NET 從 Word 匯出 LaTeX 方程式並轉換為 Markdown。 | +| [如何從 Word 匯出 LaTeX:使用 Aspose 將 DOCX 轉換為 Markdown](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) |示篯如何使用 Aspose.Words for .NET 從 Word 匯出 LaTeX 方程式並轉換為 Markdown。 | | [將 Word 轉換為 Markdown – 嵌入圖像為 Base64](./convert-word-to-markdown-embed-images-as-base64/) |示範如何使用 Aspose.Words for .NET 將 Word 匯出為 Markdown,並將圖像嵌入為 Base64 編碼。 | | [如何將 Markdown 從 Word 儲存 – 完整 C# 指南](./how-to-save-markdown-from-word-complete-c-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 Word 文件儲存為 Markdown,完整步驟指南。 | | [如何將 Markdown 從 Word 儲存 – 完整指南](./how-to-save-markdown-from-word-complete-guide/) |示範如何使用 Aspose.Words for .NET 將 Word 文件儲存為 Markdown,完整步驟指南。 | | [如何匯出 LaTeX:將 DOCX 轉換為 Markdown 與 TXT](./how-to-export-latex-convert-docx-to-markdown-txt/) |示範如何使用 Aspose.Words for .NET 將含 LaTeX 方程式的 DOCX 文件匯出為 Markdown 與純文字 TXT 格式。 | +| [將 docx 儲存為 markdown – 使用 Aspose.Words 匯出 Word 數學為 LaTeX](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) |示範如何使用 Aspose.Words for .NET 將 DOCX 中的數學公式匯出為 LaTeX,並儲存為 Markdown 格式。 | | [重新命名圖像:將 DOCX 轉換為 Markdown](./how-to-rename-images-when-converting-docx-to-markdown/) |了解如何在將 DOCX 轉換為 Markdown 時重新命名圖像,以避免衝突並保持檔案組織。 | | [使用 Aspose.Words 將 docx 儲存為 markdown – 完整 C# 指南](./save-docx-as-markdown-with-aspose-words-full-c-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中完整將 DOCX 轉換為 Markdown,提供完整步驟與範例程式碼。 | | [儲存 Word 圖像 – 使用 Aspose 將 Word 轉換為 Markdown](./save-word-images-convert-word-to-markdown-with-aspose/) |示範如何使用 Aspose.Words for .NET 從 Word 文件中提取圖像並將其匯出為 Markdown 格式。 | diff --git a/words/hongkong/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/hongkong/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..071b77270e --- /dev/null +++ b/words/hongkong/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-05-01 +description: 使用 Aspose.Words 將 docx 儲存為 markdown – 學習將 Word 轉換為 markdown、將公式匯出為 LaTeX,並在一個順暢的工作流程中設定 + markdown 圖像解析度。 +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: zh-hant +og_description: 使用 Aspose.Words 將 docx 儲存為 markdown。本教學示範如何將 Word 轉換為 markdown、將方程式匯出為 + LaTeX,並設定 markdown 圖像解析度。 +og_title: 將 docx 另存為 markdown – 完整指南:將 Word 數學公式匯出為 LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: 將 docx 儲存為 markdown – 使用 Aspose.Words 匯出 Word 數學公式為 LaTeX +url: /zh-hant/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 docx 儲存為 markdown – 使用 Aspose.Words 匯出 Word 數學為 LaTeX + +是否曾經需要 **save docx as markdown**,卻卡在如何讓 Office Math 方程式保持清晰?你並不孤單。大多數開發者在預設轉換把方程式降為模糊影像,必須手動改寫成 LaTeX 時,都會卡關。 + +好消息:Aspose.Words 可以為你完成繁重的工作。在本教學中,我們將 **convert word to markdown**,告訴引擎 **export equations to latex**,並且 **set markdown image resolution** 給文件的其他部分。完成後,你只需一條指令,就能產出含 LaTeX 數學與高解析度影像的乾淨 `.md` 檔案。 + +## 你將學會 + +- 如何載入包含 Office Math 物件的 `.docx`。 +- 哪些 `MarkdownSaveOptions` 屬性負責 **export equations to latex** 與 **set markdown image resolution**。 +- 一段完整、可執行的 C# 程式碼,直接貼到任何 .NET 專案中。 +- 常見問題的排除技巧,例如缺少字型或不支援的方程式功能。 + +**先決條件**:.NET 6+(或 .NET Framework 4.6+)、Aspose.Words for .NET 授權,以及基本的 C# 知識。如果你會建立 Console 應用程式,就可以直接開始。 + +--- + +## Step 1 – Save docx as markdown: Load Your Word File + +首先,我們需要一個指向來源 `.docx` 的 `Document` 物件。把它想成在開始複製章節前先打開書本。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*為什麼這很重要*:如果文件中沒有任何數學內容,**export equations to latex** 步驟會變成無操作,但其餘的轉換仍會執行。這個檢查可以避免你疑惑為何輸出的 Markdown 缺少 LaTeX 區塊。 + +--- + +## Step 2 – Configure Export Equations to LaTeX + +Aspose.Words 讓你決定 Office Math 的呈現方式。預設會把它們轉成 PNG 影像,這也是許多教學最後得到顆粒感 markdown 檔的原因。將 `OfficeMathExportMode` 設為 `LaTeX`,即可取得乾淨、可直接複製的方程式。 + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*為什麼使用 `OfficeMathExportMode.LaTeX`*?LaTeX 是科學出版的通用語言。之後在靜態網站產生器或 Jupyter Notebook 中渲染 markdown 時,方程式在任何縮放比例下都會保持銳利。 + +--- + +## Step 3 – Set Markdown Image Resolution (for Non‑Math Content) + +雖然我們的重點是數學,絕大多數 Word 文件同時也包含圖片、圖表或嵌入的 SVG。`ImageResolution` 屬性控制 Aspose.Words 如何點陣化這些資產。**300 DPI** 是螢幕與列印的平衡點。 + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*小技巧*:如果你的 markdown 只會在網路上顯示,可以將解析度降至 150 DPI,以減少檔案大小。相反地,若要產出列印品質的 PDF,則可提升至 600 DPI。 + +--- + +## Step 4 – Run the Conversion – Convert Word Math LaTeX + +所有設定完成後,實際的轉換只需要一行程式碼。Aspose.Words 會在背後完成繁重的工作。 + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**預期輸出**:開啟產生的 `.md` 檔案,你會看到類似以下的內容: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +注意 LaTeX 區塊(`$...$` 與 `$$...$$`)已取代先前的 PNG 片段。檔案底部的影像仍是 PNG,且以我們設定的 300 DPI 解析度輸出。 + +--- + +## Step 5 – Common Edge Cases & How to Handle Them + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (e.g., Cambria Math not installed) | LaTeX output may contain unknown symbols. | Install the missing font on the server or embed it in the document before conversion. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words may fall back to an image despite `LaTeX` mode. | Upgrade to the latest Aspose.Words version; the library continuously improves equation coverage. | +| **Large documents** ( > 50 MB ) | Memory pressure can cause `OutOfMemoryException`. | Use `LoadOptions` with `LoadFormat.Docx` and stream the file, or split the document into sections before conversion. | +| **Image size too big** | Markdown file becomes huge, slowing down static‑site builds. | Reduce `ImageResolution` to 150 DPI for web‑only scenarios (see Step 3). | + +--- + +## Step 6 – Put It All Together: Full Working Example + +以下是可直接貼到 `Program.cs` 的 *完整* Console 應用程式範例,包含我們前面討論的所有設定與少量錯誤處理。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +執行程式 (`dotnet run`) 後,你會得到一個 **save docx as markdown** 的 markdown 檔,且每個方程式皆以 LaTeX 形式保留。無需手動複製,亦不會出現難看的點陣圖。 + +--- + +## Conclusion + +我們已完整示範如何使用 Aspose.Words **saving docx as markdown**,從載入 Word 檔案、設定 **export equations to latex** 到 **set markdown image resolution**。最終程式碼已具備可直接投入生產環境的水準,且可在任何需要 **convert word to markdown** 的 .NET 專案中使用。 + +接下來可以嘗試將產生的 `.md` 交給 Hugo、Jekyll 等靜態網站產生器,觀賞方程式的完美渲染。若需將 **convert word math latex** 成其他格式(PDF、HTML),只要把 `MarkdownSaveOptions` 換成 `PdfSaveOptions` 或 `HtmlSaveOptions`,同樣的 `OfficeMathExportMode` 旗標皆適用。 + +工作流程有其他變化,例如從 Azure Blob 取得 Word 檔或從 API 串流讀取?只要把檔案系統的 `Document` 建構子換成以串流為基礎的版本,即可套用相同模式。 + +盡情實驗,並在留言區分享此方法如何解決你的轉換痛點。祝開發順利! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-pdfsaveoptions/_index.md b/words/hongkong/net/programming-with-pdfsaveoptions/_index.md index 8673e47fb1..a80417bd14 100644 --- a/words/hongkong/net/programming-with-pdfsaveoptions/_index.md +++ b/words/hongkong/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ Aspose.Words for .NET 教學中有關使用 PdfSaveOptions 進行文字處理的 | [在 PDF 文件中渲染 3D DML 3DEffects](./dml-3deffects-rendering/) |透過本全面的逐步指南了解如何使用 Aspose.Words for .NET 在 PDF 文件中呈現令人驚嘆的 3D DML 效果。 | | [在 PDF 文件中插入影像](./interpolate-images/) |透過我們的逐步指南了解如何使用 Aspose.Words for .NET 在 PDF 文件中插入影像。輕鬆提升 PDF 的影像品質。 | | [使用 Aspose.Words 將 docx 另存為 PDF – 完整 C# 指南](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) |透過本完整 C# 教學,了解如何使用 Aspose.Words 將 docx 檔案轉換為高品質 PDF。 | +| [使用 Aspose.Words 將文件另存為 PDF – 完整 C# 指南](./save-document-as-pdf-with-aspose-words-complete-c-guide/) |透過本完整 C# 教學,了解如何使用 Aspose.Words 將文件轉換為高品質 PDF。 | | [使用 C# 從 Word 建立可存取的 PDF – 步驟指南](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) |了解如何使用 Aspose.Words for .NET 以 C# 從 Word 文件生成符合可存取性標準的 PDF。 | | [在 C# 中建立可存取的 PDF – PDF 可存取性教學](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) |使用 Aspose.Words for .NET 在 C# 中建立符合可存取性標準的 PDF 文件。 | | [從 Word 建立可存取的 PDF – 完整指南](./create-accessible-pdf-from-word-complete-guide/) |了解如何使用 Aspose.Words for .NET 從 Word 文件建立符合無障礙標準的 PDF,完整步驟指南。 | diff --git a/words/hongkong/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/hongkong/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..0421fecc57 --- /dev/null +++ b/words/hongkong/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: 學習如何使用 Aspose.Words 在 C# 中將文件另存為 PDF。此教學亦涵蓋將 Word 轉換為 PDF、匯出數學 LaTeX,以及處理缺失字型。 +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: zh-hant +og_description: 使用 Aspose.Words 輕鬆將文件儲存為 PDF。本指南亦示範如何將 Word 轉換為 PDF、匯出數學 LaTeX,以及處理缺少字型。 +og_title: 使用 Aspose.Words 將文件儲存為 PDF – 完整 C# 指南 +tags: +- Aspose.Words +- C# +- PDF generation +title: 使用 Aspose.Words 將文件另存為 PDF – 完整 C# 指南 +url: /zh-hant/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.Words 將文件另存為 PDF – 完整 C# 指南 + +有沒有想過 **如何將文件另存為 PDF**,直接從 Word 檔案而不失去可及性功能?你並不是唯一有此疑問的人——開發者不斷尋求一種可靠的方法,將 Word 轉換為 PDF,同時保留數學方程式並優雅地處理缺失字型。 + +在本教學中,我們將逐步說明一個解決方案,不僅 **將文件另存為 PDF**,還示範 **將 Word 轉換為 PDF**、**匯出數學 LaTeX**,以及 **處理缺失字型**,使用最新的 Aspose.Words for .NET。完成後,你將擁有一個可直接執行的 C# 程式,產生符合 PDF/UA‑2 標準的檔案,完美適用於可及性稽核。 + +## 需要的條件 + +- .NET 6 或更新版本(此程式碼同樣適用於 .NET Core 與 .NET Framework) +- Aspose.Words for .NET 25.10 或更新版 – 可從 Aspose 官方網站取得免費試用版 +- 一個簡單的 Word 文件(`input.docx`),內含至少一個浮動圖形與一個數學方程式(以觀察 export‑math‑latex 功能) +- Visual Studio 2022(或任何你喜歡的 IDE) + +> **專業提示:** 如果你在 CI/CD 流程中,請將 Aspose.Words NuGet 套件加入你的專案檔案: + +```xml + +``` + +## 步驟 1:使用自動復原載入來源文件 + +在處理真實世界的 Word 檔案時,你可能會遇到損壞的區段或缺失的資源。啟用自動復原可確保載入過程不會拋出例外。 + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**為什麼這很重要:** +`RecoveryMode.AutoRecover` 可防止你的流水線因格式不良的輸入而崩潰,這在大量 **將 Word 轉換為 PDF** 時特別有用。 + +## 步驟 2:設定 PDF 儲存選項以實現完整可及性 + +PDF/UA‑2 是可及性 PDF 的 ISO 標準。透過設定少數旗標,我們即可產生螢幕閱讀器可導航的檔案,並確保數學方程式以隱藏 LaTeX 形式匯出。 + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**重點說明:** + +- **ExportFloatingShapesAsInlineTag** – 確保產生的 PDF 保持原始版面配置,同時語意正確。 +- **OfficeMathExportMode.LaTeX** – 滿足 **匯出數學 LaTeX** 的需求,讓後續工具能提取方程式(如有需要)。 + +## 步驟 3:捕獲警告(例如缺失字型) + +缺失字型是轉換文件時常見的痛點。Aspose.Words 可透過 `WarningCallback` 回報這些問題。我們會將它們收集起來,讓你之後可以記錄或處理。 + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**為什麼你在乎:** +如果來源使用的字型未在伺服器上安裝,PDF 會回退至預設字型,可能導致版面錯亂。透過 **處理缺失字型**,我們可以提醒使用者或嵌入替代字型。 + +## 步驟 4:將文件儲存為可及性 PDF + +現在是真正的關鍵時刻——執行轉換。 + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +如果一切順利,你將得到一個 PDF/UA‑2 檔案,內含每個方程式的隱藏 LaTeX 以及正確標記的浮動圖形。 + +## 步驟 5:檢視捕獲的警告(可選但建議) + +儲存操作完成後,你可以遍歷收集到的警告並將其記錄。 + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +典型的輸出可能如下: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +提前看到這些訊息有助於在影響最終使用者之前 **處理缺失字型**。 + +## 完整範例程式 + +將所有步驟整合起來,以下是完整、可直接執行的程式。請將佔位路徑替換為你自己的路徑。 + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**預期結果:** +- `output.pdf` 符合 PDF/UA‑2 標準。 +- 所有浮動圖形皆標記為內嵌圖形。 +- 每個 Office Math 物件皆以隱藏 LaTeX 形式呈現(在檢查 PDF 結構時可見)。 +- 任何與字型相關的問題都會印在主控台,讓你有機會在發佈檔案前 **處理缺失字型**。 + +![顯示從 Word → Aspose.Words → 可及性 PDF(將文件另存為 PDF)的流程圖](conversion-diagram.png "將文件另存為 PDF 的流程圖") + +*圖片替代文字:* **使用 Aspose.Words 將文件另存為 PDF 的示意圖** + +## 常見問題與邊緣情況 + +### 如果我使用較舊的 Aspose.Words 版本呢? + +`OfficeMathExportMode.LaTeX` 旗標於 25.10 版首次加入。對於較舊的版本,你仍然可以 **將 Word 轉換為 PDF**,但數學方程式會被光柵化,而非匯出為 LaTeX。建議升級以獲得最佳可及性。 + +### 我可以嵌入自訂字型以避免回退嗎? + +可以。於呼叫 `Save` 前設定 `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll`。此設定亦可透過強制 PDF 包含所需字形來 **處理缺失字型**。 + +### 我要如何驗證 PDF/UA‑2 的符合性? + +在 Adobe Acrobat Pro 中開啟檔案 → “列印製作” → “預檢”。選擇 “PDF/A‑2b” 或 “PDF/UA‑2” 設定檔;Acrobat 會報告任何違規項目。 + +### 密碼保護的 Word 檔案該怎麼處理? + +使用包含 `Password` 的 `LoadOptions` 來載入文件。例如: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +## 結論 + +我們已說明使用 Aspose.Words 在 C# 中 **將文件另存為 PDF** 所需的全部內容。教學同時示範了如何 **將 Word 轉換為 PDF**、**匯出數學 LaTeX**,以及 **處理缺失字型**——全部產出符合可及性標準的 PDF/UA‑2 檔案。 + +試跑這段程式碼,實驗不同的 `PdfSaveOptions`(例如影像壓縮、PDF/A‑2b),並將其整合至你的文件處理服務中。若需更進一步的功能,可考慮探索 Aspose 的 PDF 專屬函式庫,用於後處理或數位簽章。 + +還有其他想要解決的情境嗎?歡迎留言或參考我們其他關於 **PDF 操作**、**影像擷取** 與 **批次轉換** 的指南。祝開發愉快! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-shapes/_index.md b/words/hongkong/net/programming-with-shapes/_index.md index 2a00219d42..79f6de6378 100644 --- a/words/hongkong/net/programming-with-shapes/_index.md +++ b/words/hongkong/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Aspose.Words for .NET 教學中關於使用形狀進行文字處理的教學提 | [在 Word 中使用 Aspose.Words 建立矩形形狀](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) |透過本逐步教學了解如何使用 Aspose.Words for .NET 在 Word 文件中插入矩形形狀。 | | [Aspose.Words 形狀陰影教學 – 在 C# 中為 Word 形狀新增陰影](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) |透過本教學學習如何在 C# 中使用 Aspose.Words 為 Word 形狀新增陰影效果。 | | [建立帶陰影矩形形狀的空白 Word 文件 – 逐步指南](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) |透過本逐步教學了解如何使用 Aspose.Words for .NET 建立帶陰影的矩形形狀的空白 Word 文件。 | +| [如何在 Aspose.Words 中移動陰影 – 完整 C# 指南](./how-to-move-shadow-in-aspose-words-complete-c-guide/) |透過本完整 C# 教學了解如何在 Aspose.Words 中調整與移動形狀陰影,以提升文件視覺效果。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hongkong/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/hongkong/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..e6bd98fc0f --- /dev/null +++ b/words/hongkong/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-01 +description: 如何使用 C# 在 Aspose.Words 中移動形狀的陰影。學習在幾分鐘內為形狀添加陰影、調整模糊、設定透明度以及旋轉陰影。 +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: zh-hant +og_description: 如何使用 C# 在 Aspose.Words 中移動形狀的陰影。本教學示範如何為形狀添加陰影、更改模糊程度、設定透明度以及旋轉陰影。 +og_title: 如何在 Aspose.Words 中移動陰影 – 完整 C# 指南 +tags: +- Aspose.Words +- C# +- Document Automation +title: 在 Aspose.Words 中如何移動陰影 – 完整 C# 指南 +url: /zh-hant/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 Aspose.Words 中移動陰影 – 完整 C# 指南 + +有沒有想過 **如何在 Word 文件中的形狀上移動陰影** 而不必手動開啟 Word?在我的日常工作中,我常常需要以程式方式微調形狀的陰影——無論是為了打造精緻的報告或是動態範本。好消息是?使用 Aspose.Words 只需幾行程式碼,即可完成,同時您還會學到 **add shadow to shape**、**how to change blur**、**how to set transparency**、以及 **how to rotate shadow**。 + +在本教學中,我們將示範一個真實情境:載入已有形狀的 DOCX 檔案,調整陰影的位置、柔和度、不透明度與方向,最後儲存結果。完成後您將擁有可重複使用的程式碼片段,能直接放入任何 .NET 專案,並了解每個屬性的意義。 + +## 前置條件 – 開始前您需要的項目 + +- **Aspose.Words for .NET**(版本 23.12 或更新)。您可以透過 NuGet 使用 `Install-Package Aspose.Words` 取得。 +- .NET 6+ 開發環境(Visual Studio、VS Code、Rider——您喜歡的任何工具)。 +- 一個已包含至少一個形狀(矩形、圓形或圖片皆可)的輸入 Word 檔案(`input.docx`)。 +- 基本的 C# 語法認識——不需要太深入。 + +如果您缺少上述任一項,請先暫停並安裝相應的套件;本指南的後續內容皆假設已正確引用該套件。 + +## 步驟 1:載入文件並取得目標形狀 – **How to Move Shadow** 開始 + +我們首先要做的是載入來源文件,並定位要修改的形狀。Aspose.Words 將每個物件(段落、表格、形狀)視為樹狀結構中的節點,因而可以直接查詢。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **為什麼這很重要:** 只載入一次文件並重複使用相同的 `Document` 實例,可提升效能。`GetChild` 呼叫是安全的,因為若索引超出範圍會回傳 `null`,讓我們能優雅地處理缺少形狀的情況。 + +## 步驟 2:調整模糊半徑 – 掌握 **How to Change Blur** + +柔和的陰影看起來更專業,而硬邊則顯得廉價。`BlurRadius` 屬性以點 (pt) 為單位控制柔軟度 (1 pt ≈ 1/72 英吋)。我們將其提升至 8 pt。 + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **專業提示:** 預設的模糊度為 0.5 pt。超過 5 pt 通常會明顯可見,但請注意不要設定過大,否則形狀會顯得與頁面脫節。 + +## 步驟 3:設定透明度 – 解答 **How to Set Transparency** + +透明度決定陰影的透視程度。`0` 代表完全不透明;`1` 代表完全透明。為了取得細膩的效果,我們使用 `0.3`(30 % 透明)。 + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **為什麼您可能在意:** 若形狀顏色較深,完全不透明的陰影會掩蓋底層文字。調整透明度可保持文件可讀性,同時仍提供層次感。 + +## 步驟 4:移動陰影 – **How to Move Shadow** 的核心 + +`Distance` 屬性定義陰影相對於形狀的偏移距離,以點為單位。距離越大,陰影越遠離形狀,產生更戲劇化的效果。 + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **如果需要極小的偏移呢?** 將 `Distance` 設為 `0` 會使陰影直接位於形狀後方,這對浮雕效果很有幫助。 + +## 步驟 5:旋轉光源 – 解決 **How to Rotate Shadow** + +陰影不一定垂直向下;它會依光源角度而變化。`Angle` 屬性(以度為單位)繞形狀旋轉陰影。我們將其傾斜 45°。 + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **快速實驗:** 嘗試 `90` 產生右側陰影,或 `-30` 產生左傾陰影。視覺變化會立即顯現。 + +## 步驟 6:儲存文件 – 觀察 **Add Shadow to Shape** 的結果 + +現在我們已調整完陰影,將把文件寫回磁碟。您可以覆寫原檔或建立新檔;範例使用新輸出檔案。 + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **預期輸出:** 開啟 `output.docx`。形狀的陰影將變得更柔和、略微偏移、半透明,且以 45° 角度呈現。若與 `input.docx` 並排比較,差異顯而易見。 + +### 完整可執行範例(直接複製貼上) + +以下是一個完整的程式碼區塊。將其貼到新的 Console 專案中,將 `YOUR_DIRECTORY` 替換為實際的資料夾路徑,然後執行。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## 常見問題與邊緣情況 + +### 如果文件中有多個形狀呢? + +您可以遍歷所有形狀: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### 我可以為目前沒有陰影的形狀新增陰影嗎? + +當然可以。`ShadowFormat` 物件始終存在,只需啟用即可: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### 這適用於圖片和 SmartArt 嗎? + +是的。任何繼承自 `Shape` 的節點——包括圖片、圖表與 SmartArt——皆具備 `ShadowFormat`,且可使用相同的屬性。 + +### 如何控制陰影顏色? + +使用 `Color` 屬性: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 相容性考量? + +Aspose.Words 23.12 以上支援 .NET 6、.NET Core 3.1 與 .NET Framework 4.6.2+。此範例所示的 API 在這些版本中皆保持穩定。 + +## 結論 + +我們剛剛說明了如何使用 Aspose.Words 在形狀上 **how to move shadow**,同時也示範了 **add shadow to shape**、**how to change blur**、**how to set transparency** 與 **how to rotate shadow**。完整且可執行的範例讓您在數秒內調整任意形狀的陰影,為文件帶來精緻、專業的外觀,且無需開啟 Word。 + +準備好進一步了嗎?試著將這些陰影調整與 **conditional formatting** 結合——例如,只對標題或超過特定尺寸的圖表套用較深的陰影。或探索形狀本身的 **gradient fills**,打造真正吸睛的設計。 + +如果遇到任何問題,歡迎在下方留言。祝程式開發愉快,願您的陰影永遠落在理想的位置! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/basic-conversions/_index.md b/words/hungarian/net/basic-conversions/_index.md index 869c1fbeee..95bd6e4d2c 100644 --- a/words/hungarian/net/basic-conversions/_index.md +++ b/words/hungarian/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ Az Alapvető konverziók című útmutató végigvezeti Önt az Aspose.Words for | [Word konvertálása PDF-be C#-ban az Aspose.Words – Útmutató](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Tanulja meg, hogyan konvertálhat Word dokumentumokat PDF-be C#-ban az Aspose.Words használatával. | | [Word mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Tanulja meg, hogyan menthet Word dokumentumokat PDF-be C#-ban az Aspose.Words használatával, részletes lépésekkel. | | [Docx mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Tanulja meg, hogyan menthet docx fájlokat PDF-be C#-ban az Aspose.Words használatával, részletes lépésekkel. | +| [Word mentése PDF-be az Aspose.Words segítségével – Teljes útmutató](./save-word-as-pdf-with-aspose-words-complete-guide/) | Tanulja meg, hogyan menthet Word dokumentumokat PDF-be az Aspose.Words használatával, részletes lépésekkel. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/hungarian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index c6f152d335..467edef031 100644 --- a/words/hungarian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/hungarian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,24 @@ --- category: general -date: 2025-12-29 -description: Hogyan exportáljunk LaTeX-et a Wordből az Aspose.Words segítségével – - tanulja meg a Word LaTeX-re konvertálását, a docx mentését txt formátumban, és az - egyenletek kezelését egyszerű szövegben. +date: 2026-05-01 +description: Tanulja meg, hogyan exportálhat LaTeX-et egy Word-fájlból, hogyan konvertálhatja + a Word-öt txt formátumba, és hogyan őrizheti meg a táblázatokat az Aspose.Words + C#-ban. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: hu -og_description: Hogyan exportáljunk LaTeX-et a Wordből az Aspose.Words segítségével. - Ez az útmutató megmutatja, hogyan konvertálhatjuk a Word dokumentumot LaTeX-re, - menthetjük a docx-et txt formátumban, és megőrizhetjük a képleteket érintetlenül. -og_title: Hogyan exportáljunk LaTeX-et a Wordből – Gyors C# útmutató +og_description: Fedezze fel, hogyan exportálhat LaTeX-et a Wordből, konvertálhatja + a Word dokumentumot egyszerű szöveggé, és megőrizheti a táblázat elrendezését az + Aspose.Words segítségével. +og_title: Hogyan exportáljunk LaTeX-et a Wordből – Teljes C# oktatóanyag tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Hogyan exportáljunk LaTeX-et a Wordből – Lépésről lépésre útmutató url: /hu/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,179 +28,213 @@ url: /hu/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Hogyan exportáljunk LaTeX-et Word-ből – Lépésről‑lépésre útmutató +# Hogyan exportáljunk LaTeX-et Word-ből – Teljes C# útmutató -Valaha elgondolkodtál már azon, **hogyan exportáljunk LaTeX-et Word-ből** anélkül, hogy elveszítenénk a nehézkes Office Math egyenleteket? Nem vagy egyedül. Sok fejlesztő akadályba ütközik, amikor *Word‑t LaTeX‑re konvertálni* próbál megvalósítani tudományos dolgozatok, jelentések vagy automatizált kiadási folyamatok számára. +Gondolkodtál már azon, **hogyan exportáljunk LaTeX-et** egy Word dokumentumból anélkül, hogy elveszítenénk a matematikai egyenleteket? Nem vagy egyedül. Sok fejlesztőnek szüksége van arra, hogy egy .docx‑et, amely Office Math‑ot tartalmaz, tiszta LaTeX‑be konvertáljon, miközben **Word‑ot txt‑re konvertál** a további feldolgozáshoz. Ebben az útmutatóban egy gyakorlati, azonnal futtatható megoldáson keresztül vezetünk, amely **megőrzi a táblázatokat**, egy egyszerű szövegfájlt ad, és a LaTeX jelölést pontosan ott tartja, ahol szükséged van rá. -Ebben az útmutatóban végigvezetünk egy teljes, azonnal futtatható C# példán, amely bemutatja, **hogyan exportáljunk LaTeX-et** az Aspose.Words használatával, elmagyarázza, **hogyan mentsünk txt** fájlokat LaTeX jelöléssel, és még a **word egyenletek latex‑re konvertálása** finomságait is lefedi, hogy semmi se vesszen el a fordítás során. - -> **Pro tipp:** Ugyanaz a megközelítés működik bármely .docx fájlra—csak a kódot irányítsd egy másik fájlútvonalra. - ---- +Mindent lefedünk a forrásfájl betöltésétől a `TxtSaveOptions` finomhangolásáig, hogy a kimenet ember‑olvasásra és gép‑barát módra egyaránt alkalmas legyen. A végére képes leszel **docx‑et txt‑ként menteni**, **Word‑ot egyszerű szöveggé konvertálni**, és tudni **hogyan őrizhetők meg a táblázatok** az export során. Nincs külső szkript, nincs manuális másolás‑beillesztés – csak tiszta C# kód, amelyet bármely .NET projektbe beilleszthetsz. ## Amire szükséged lesz -Mielőtt belevágunk, győződj meg róla, hogy a következő előfeltételek rendelkezésedre állnak: - -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Az Aspose.Words a modern .NET futtatókörnyezeteket célozza meg. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | A könyvtár elvégzi a nehéz munkát a Word feldolgozásában és a LaTeX kiadásában. | -| **A sample .docx** containing at least one Office Math equation | A LaTeX konverzió működés közben történő megtekintéséhez. | -| **Visual Studio 2022** (or any IDE you likeyszerűvé teszi a minta hibakeresését és futtatását. | - -Ha még nem telepítetted a NuGet csomagot, futtasd: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (legújabb verzió, 2024.x vagy újabb). A NuGet csomag neve `Aspose.Words`. +- Egy .NET fejlesztői környezet (Visual Studio, VS Code, Rider – bármelyik megfelel). +- Egy Word fájl (`.docx`), amely Office Math egyenleteket és legalább egy táblázatot tartalmaz (hogy láthassuk a táblázat‑megőrző varázslatot). -Ennyi—nincs extra DLL, nincs COM interop, csak egy tiszta, kezelt könyvtár. +Ennyi. Ha már megvan mindez, olvasd tovább; egyébként szerezd be a NuGet csomagot és egy minta DOCX‑et, mielőtt mélyebben belemerülnénk. --- -## Hogyan exportáljunk LaTeX-et Word-ből – Áttekintés +## Hogyan exportáljunk LaTeX-et egy Word dokumentumból -Az alábbiakban látható a nagy kép arról, amit el fogunk érni: +Az alábbiakban a tutorial központi része – három tömör lépés, amely megválaszolja a **hogyan exportáljunk latex-et** kérdést, miközben kezeli a másodlagos célokat is: **convert word to txt**, **convert word to plain text**, **save docx as txt**, és **how to preserve tables**. -1. **Betöltés** a forrás Word dokumentumot (`.docx`). -2. **Konfigurálás** `TxtSaveOptions`-t úgy, hogy minden Office Math objektum LaTeX kódként legyen kiadva. -3. **Mentés** a dokumentumot egyszerű szöveg (`.txt`) fájlként, amelyet közvetlenül bármely LaTeX fordítóba betáplálhatsz. +### 1. lépés: A DOCX fájl betöltése -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") - ---- - -## 1. lépés: A Word dokumentum betöltése - -Először is—nyisd meg a konvertálni kívánt .docx fájlt. A `Document` osztály elrejti a mögöttes XML-t, és egy felhasználóbarát objektummodellt biztosít. +Először be kell olvasnunk a Word dokumentumot egy `Aspose.Words.Document` objektumba. Ez a lépés ugyanaz, függetlenül attól, hogy később **convert word to txt** vagy **save docx as txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Miért fontos ez:** - -A fájl korai betöltése lehetővé teszi, hogy megvizsgáljuk a tartalmát (pl. egyenletek számlálása), mielőtt eldöntenénk, hogyan sorosítsuk. Ha a fájl sérült, a `Document` egy egyértelmű kivételt dob, így elkerülheted a későbbi rejtélyes kimenetet. +> **Miért fontos:** A fájl betöltése egy memóriában létező reprezentációt hoz létre minden Word elemből – bekezdések, táblázatok és Office Math objektumok. Enélkül az objektum nélkül nem tudod módosítani az export beállításait. ---- +### 2. lépés: `TxtSaveOptions` konfigurálása LaTeX-hez és táblázat elrendezéshez -## 2. lépés: TxtSaveOptions konfigurálása LaTeX exporthoz +A `TxtSaveOptions` osztály lehetővé teszi, hogy pontosan szabályozd, hogyan jön létre a egyszerű szövegfájl. Két tulajdonság kulcsfontosságú a jelen helyzetben: -A varázslat a `TxtSaveOptions`-ben történik. Az `OfficeMathExportMode` `LaTeX`‑re állításával minden Office Math objektum a megfelelő LaTeX ábrázolásra konvertálódik. +| Property | Mit csinál | Miért szükséges | +|----------|------------|-----------------| +| `OfficeMathExportMode` | Meghatározza, hogyan jelenik meg az Office Math. `LaTeX`‑re állítva az egyenletek LaTeX szintaxisra konvertálódnak. | Ez a **how to export latex** lényege. | +| `PreserveTableLayout` | Ha `true`, az Aspose szóközöket ad hozzá, hogy a táblázatok rácsszerű megjelenést tartsanak. | Ez teljesíti a **how to preserve tables** feltételt, miközben **convert word to txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Miért ezeket a beállításokat választjuk:** +> **Pro tipp:** Ha csak a nyers LaTeX‑re van szükséged táblázat formázás nélkül, állítsd a `PreserveTableLayout`‑ot `false`‑ra. A fájl kisebb lesz, de elveszíted a vizuális táblázat jelzést. -- `OfficeMathExportMode.LaTeX` az egyetlen mód, amely garantálja a hűséges matematikai fordítást. -- `PreserveTableLayout` megőrzi a táblázatok megjelenését, ahogy azok Word-ben látszanak, ami hasznos, ha később a kimenetet egy LaTeX `tabular` környezetbe ágyazod. -- Az UTF‑8 biztosítja, hogy az olyan karakterek, mint a “α”, “β”, vagy “∑”, megmaradjanak a körúton. +### 3. lépés: A dokumentum mentése egyszerű szövegként -Ha valaha **word‑t latex‑re konvertálni** kell a sima szöveg burkoló nélkül, akkor helyette `SaveFormat.LaTeX`-re válthatsz—csak egy gyors tipp haladó esetekhez. +Most a dokumentumot egy `.txt` fájlba írjuk a most definiált beállításokkal. Ez az egyetlen sor egyszerre megvalósítja a **convert word to plain text**, **save docx as txt**, és természetesen a **how to export latex** feladatot. ---- +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -## 3. lépés: A dokumentum mentése szövegfájlként +doc.Save(outputPath, saveOptions); +``` -Most a LaTeX‑gazdag szöveget írjuk a lemezre. A keletkezett `.txt` később átnevezhető `.tex`-re, vagy közvetlenül egy LaTeX fordítóba csővezetheted. +A hívás befejezése után nyisd meg a `output.txt` fájlt. A következőket fogod látni: -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +- LaTeX kódrészletek, például `\frac{a}{b}` minden Office Math egyenlethez. +- Táblázatok, amelyek `|` és `-` karakterekkel jelennek meg, megőrizve az oszlopok igazítását. +- Általános bekezdések egyszerű szövegként, készen állva bármely további feldolgozó számára. + +### Teljes működő példa -// Save using the configured options -doc.Save(outputPath, txtOptions); +Mindent egybe rakva, itt egy önálló program, amelyet ma lefordíthatsz és futtathatsz: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**A `output.txt`-ben látható lesz:** +**Várható kimenet** (részlet): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Minden egyéb bekezdés egyszerű szövegként jelenik meg, míg minden Office Math egyenlet LaTeX `equation` környezetbe (vagy `inline`-ba, ha a Word-ben inline volt) van ágyazva. Ez tökéletesen teljesíti a **word egyenletek latex‑re konvertálása** követelményt. +Vedd észre, hogy a táblázat megőrzi a rácsát, és az egyenlet tiszta LaTeX‑ként jelenik meg. Ez a tökéletes megoldás, amikor **convert word to txt**, és még mindig hiteles ábrázolásra van szükség a struktúra és a matematika tekintetében. --- -## Szélsőséges esetek és gyakori kérdések +## Tippek a Word TXT‑re konvertálásához és a táblázatok megőrzéséhez -| Situation | What to do | -|-----------|------------| -| **No equations in the source** | A konverzió továbbra is működik; csak egyszerű szöveget kapsz. Nem adódik extra LaTeX kód. | -| **Very large documents (>100 MB)** | Fontold meg a kimenet streamingelését `MemoryStream` használatával a magas memóriahasználat elkerülése érdekében. | -| **Unsupported Math constructs** | Az Aspose.Words az Office Math 99 %-át lefedi. A ritka szélsőséges esetben előfordulhat, hogy manuálisan kell post‑processzálnod a LaTeX-et. | -| **Need a .tex file instead of .txt** | Módosítsd az `outputPath`-t, hogy `.tex`-re végződjön, és opcionálisan állítsd be a `txtOptions.Encoding`-t `Encoding.UTF8`-re. | -| **Running on Linux/macOS** | Ugyanaz a kód működik—csak győződj meg róla, hogy a fájlutak előre‑döntött perjeleket vagy `Path.Combine`-t használnak. | +Miközben a háromlépéses megközelítés a legtöbb esetben működik, a valós projektek gyakran hoznak váratlan kihívásokat. Az alábbiakban gyakorlati javaslatok találhatók, amelyek a **convert word to plain text** folyamatodat robusztusabbá teszik. ---- +### Használj konzisztens kódolást -## Hogyan mentsünk TXT fájlt LaTeX egyenletekkel – Gyors összefoglaló +`TxtSaveOptions` alapértelmezés szerint UTF‑8, amely a legtöbb karaktert kezeli. Ha más kódlapot kell használnod (pl. régi rendszerek, amelyek a Windows‑1252‑t várják), állítsd be az `Encoding` tulajdonságot: -1. **Betöltés** a .docx (`Document`). -2. **Beállítás** `OfficeMathExportMode = LaTeX` a `TxtSaveOptions`-ban. -3. **Mentés** a fájl (`doc.Save`) ezekkel a beállításokkal. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -Ez a teljes munkafolyamat a **txt fájlok mentéséhez**, amelyek LaTeX‑formázott egyenleteket tartalmaznak. +### Felesleges szóközök eltávolítása ---- +Sok oszlopot tartalmazó táblázatok hosszú sorokat generálhatnak. Mentés után érdemes lehet a fájlt utófeldolgozni, hogy a több szóközt egyetlen tabulátorra csökkentsd: -## Bónusz: A konverzió automatizálása több fájlhoz +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -Ha egy mappád tele van Word dokumentumokkal, csomagold be a fenti logikát egy egyszerű ciklusba: +### Beágyazott táblázatok kezelése -```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +Ha a DOCX-ed táblázatokat tartalmaz táblázatokon belül, a `PreserveTableLayout` továbbra is megőrzi a vizuális hierarchiát, de a behúzás furcsán nézhet ki. Egy gyors megoldás, ha a kezdő szóközöket egy egyedi jelzővel (pl. `>>`) helyettesíted, hogy a downstream parser-ek felismerjék a beágyazási szinteket. -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Tömeges feldolgozás több fájlon + +Amikor **convert word to txt**-t kell végrehajtanod tucatnyi dokumentumon, csomagold a logikát egy ciklusba: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Most **word‑t latex‑re konvertálhatsz** tömegesen—tökéletes a kutatócsoportok számára, akik naponta tucatnyi kéziratot kapnak. +Így **save docx as txt**-t tudsz tömegesen végrehajtani manuális beavatkozás nélkül. + +--- + +## Gyakori hibák és hogyan kerüld el őket + +1. **Hiányzó LaTeX Export Mode** – Ha elfelejted beállítani a `OfficeMathExportMode = OfficeMathExportMode.LaTeX` értéket, az egyenletek egyszerű szövegként fognak megjelenni (pl. “Equation 1”). Mindig ellenőrizd kétszer az opciók blokkot. +2. **A táblázat elrendezése elveszik** – A `PreserveTableLayout` alapértelmezett értéke `false`. Ha a kimeneted szövegtömbnek tűnik, valószínűleg nem kapcsoltad be a flag-et. +3. **Szóközöket tartalmazó fájlutak** – A nyers stringek (`@"C:\My Folder\input.docx"`) használata elkerüli az escape problémákat. Ellenkező esetben `FileNotFoundException`-t kapsz. +4. **Verzióeltérés** – A régebbi Aspose.Words verziók (< 21.9) nem támogatják a `OfficeMathExportMode`-ot. Frissíts a legújabb csomagra, hogy a **how to export latex** működjön. +5. **Kódolási hibák nem ASCII karaktereknél** – Ha � szimbólusokat látsz, állítsd be explicit módon az `options.Encoding`-ot UTF‑8-ra vagy a megfelelő kódlapra. + +## A megoldás kiterjesztése: TXT‑ről Markdown vagy HTML formátumra + +Néha többre van szükség, mint egyszerű szöveg – például egy Markdown fájlra, amely még mindig LaTeX blokkokat tartalmaz. A `TxtSaveOptions` helyett használható `HtmlSaveOptions` vagy `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Ez az apró változtatás lehetővé teszi, hogy **convert word to txt**‑stílusú kimenetet kapj, miközben megőrzöd a kedvenc markdown szintaxist. --- ## Összegzés -Átbeszéltük, **hogyan exportáljunk LaTeX-et Word-ből** lépésről‑lépésre, bemutattuk, **hogyan mentsünk txt** fájlokat, amelyek megőrzik minden Office Math egyenletet, és még azt is megmutattuk, hogyan **word egyenleteket latex‑re konvertáljunk** anélkül, hogy a pontosságot elveszítenénk. +Végigvezettünk egy teljes, termelés‑kész megoldáson, amely válasz a **how to export latex** kérdésre egy Word dokumentumból, miközben egyszerre megmutattuk, hogyan **convert word to txt**, **convert word to plain text**, **save docx as txt**, és **how to preserve tables**. A fő tanulságok: + +- Töltsd be a DOCX-et `Aspose.Words.Document`‑del. +- Állítsd be a `TxtSaveOptions.OfficeMathExportMode = LaTeX` és `PreserveTableLayout = true` értékeket. +- Hívd meg a `doc.Save(outputPath, options)`‑t, hogy tiszta, LaTeX‑gazdag egyszerű szövegfájlt kapj. -Csak néhány C# sorral és az erőteljes Aspose.Words könyvtárral bármely .docx-et LaTeX‑kész szöveggé alakíthatsz, amely készen áll a tudományos dolgozatokba, tankönyvekbe vagy automatizált kiadási folyamatokba való beillesztésre. +Próbáld ki a saját fájljaidon, kísérletezz a kódolási beállításokkal, és bátran dolgozz fel egész mappákat kötegelt módon. Ha edge case‑ekbe ütközöl – beágyazott táblázatok, egzotikus karakterek vagy régi Aspose verziók – nézd meg a „Tippek” és „Gyakori hibák” részeket a gyors megoldásokért. -**Következő lépések?** Próbáld meg a generált `.txt`-et (vagy nevezd át `.tex`-re) betáplálni a `pdflatex` vagy `xelatex` programba PDF előállításához, vagy fedezd fel a `SaveFormat.LaTeX` opciót egy közvetlen `.tex` fájlhoz. Ha **docx‑t txt‑ként szeretnéd menteni** a formázás megőrzése mellett, kísérletezz a `PreserveTableLayout` és egyedi sortörés kezelésével. +Készen állsz a következő lépésre? Próbáld meg ugyanazt a DOCX-et Markdown‑ra konvertálni, vagy add a generált `.txt`‑et egy statikus weboldalkészítőnek, amely a weben rendereli a LaTeX‑et. A lehetőségek végtelenek, és most már egy szilárd alapod van bármely **convert word to txt** munkafolyamathoz. -Van kérdésed a szélsőséges esetekkel, licenceléssel vagy teljesítmény finomhangolással kapcsolatban? Hagyj egy megjegyzést alább—boldog kódolást! +Boldog kódolást, és legyen a LaTeX‑ed mindig első próbálásra fordítható! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/hungarian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/hungarian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..e3bfe8f0b3 --- /dev/null +++ b/words/hungarian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-01 +description: Word mentése PDF-ként az Aspose.Words használatával C#-ban. Tanulja meg, + hogyan konvertáljon docx-et PDF-re, hogyan észlelje a hiányzó betűtípusokat, és + hatékonyan kezelje a betűtípuscsere figyelmeztetéseket. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: hu +og_description: Mentse a Word dokumentumot PDF‑be az Aspose.Words segítségével. Ez + a lépésről‑lépésre útmutató bemutatja, hogyan konvertálhatja a docx‑et PDF‑re, és + hogyan észlelhet hiányzó betűtípusokat. +og_title: Word mentése PDF-be az Aspose.Words segítségével – Teljes útmutató +tags: +- Aspose.Words +- C# +- PDF conversion +title: Word dokumentum mentése PDF‑be az Aspose.Words segítségével – Teljes útmutató +url: /hu/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save Word as PDF with Aspose.Words – Complete Guide + +Valaha is szükséged volt **Word PDF‑ként mentésére** menet közben, és azon tűnődtél, hogy esetleg hiányzik-e egy betűtípus? Nem vagy egyedül – a fejlesztők állandóan küzdenek a hiányzó betűtípusok okozta fejfájással a dokumentumok konvertálásakor. Ebben az útmutatóban egy gyakorlati megoldáson keresztül vezetünk végig, amely nem csak **docx konvertálása pdf‑be**, hanem **hiányzó betűtípusok észlelése** is az Aspose.Words betűtípus‑helyettesítési figyelmeztetései segítségével. + +Mindent lefedünk a figyelmeztető gyűjtő beállításától a kimenet értelmezéséig, így a végére pontosan tudni fogod, hogyan **menthetsz Word‑et PDF‑ként** meglepetések nélkül. Nincs külső eszköz, nincs rejtett beállítás – csak tiszta C# kód, amelyet bármely .NET projektbe beilleszthetsz. + +## What You’ll Need + +- **Aspose.Words for .NET** (legújabb verzió, pl. 24.10) – NuGet‑en keresztül szerezhető be (`Install-Package Aspose.Words`). +- .NET fejlesztői környezet (Visual Studio, Rider vagy VS Code is megfelelő). +- Egy minta DOCX fájl, amely esetleg olyan betűtípusokat tartalmaz, amelyek nincsenek telepítve a célgépen. +Ennyi. Ha ezek megvannak, készen állunk a merülésre. + +## Save Word as PDF – Step‑by‑Step Overview + +Az alábbiakban a teljes, futtatható program látható. Nyugodtan másold be egy konzolos alkalmazás projektbe, és nyomd meg az **F5**‑öt. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** Cseréld le a `YOUR_DIRECTORY`‑t egy abszolút útra, vagy használd a `Path.Combine(Environment.CurrentDirectory, "input.docx")`‑t egy relatív, biztonságosabb megközelítéshez. + +### Why We Use a Warning Callback + +Az Aspose.Words csendben helyettesíti a hiányzó betűtípusokat egy tartalék (általában Arial). Figyelmeztető callback nélkül sosem tudnád, hogy a helyettesítés megtörtént, ami elrendezési hibákhoz vezethet a létrehozott PDF‑ben. Az `IWarningCallback` csatolásával egyértelmű, programozott listát kapunk minden hiányzó betűtípus eseményről – tökéletes naplózáshoz vagy a végfelhasználók értesítéséhez. + +### Detect Missing Fonts – What to Look For + +A program futtatásakor minden hiányzó betűtípus egy konzolos sorban jelenik meg, például: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Ha a lista üres, gratulálunk – a **save word as pdf** sikeresen befejeződött az összes eredeti betűtípussal. + +## Convert Docx to PDF – Customizing the Output + +Néha egy konkrét PDF verzióra, képek minőségére vagy megfelelőségi szintre van szükség. Az Aspose.Words lehetővé teszi a `PdfSaveOptions` objektum testreszabását a `Save` hívása előtt. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Why this matters:** Ha jogi archiváláshoz generálsz PDF‑eket, a `PdfA1b` beállítása biztosítja, hogy a fájl szigorú szabványoknak megfeleljen. Az ugyanaz a konverzió továbbra is tiszteletben tartja a figyelmeztető callback‑ünket, így továbbra is **detect missing fonts**. + +## Aspose Words Font Substitution – Handling Edge Cases + +### Scenario 1: Multiple Missing Fonts + +Ha a forrásdokumentum több egyedi betűtípust használ, a figyelmeztető gyűjtő minden betűtípusra egy bejegyzést tartalmaz. Összegyűjtheted őket: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenario 2: Providing a Fallback Font Directory + +Az Aspose.Words további mappákat is kereshet betűtípusok után. Állítsd be a `FontsFolder` tulajdonságot a `FontSettings`‑en a dokumentum betöltése előtt: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Ezután a könyvtár először a saját mappádat fogja átnézni, csökkentve a nem kívánt helyettesítés esélyét. + +### Scenario 3: Ignoring Substitutions + +Ha inkább azt szeretnéd, hogy a konverzió hibával leálljon, amikor egy betűtípus hiányzik (ahelyett, hogy csendben helyettesítené), dobj kivételt a callback‑ben: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Ez arra kényszerít, hogy a hiányzó betűtípust a folytatás előtt kezeld – hasznos CI pipeline‑okban, ahol a csendes hibák nem elfogadhatóak. + +## Full End‑to‑End Example + +Mindent összerakva, itt egy kompakt verzió, amely bemutatja, **hogyan konvertáljunk Word‑et PDF‑be**, testreszabja a PDF beállításokat, és naplózza a betűtípus‑problémákat: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Expected console output** (ha a Calibri hiányzik): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Ha nincs figyelmeztetés, a **save word as pdf** művelet a forrás DOCX‑ben lévő pontos betűtípusokat használta. + +## Visual Summary + +![save word as pdf workflow diagram](https://example.com/diagram.png "save word as pdf workflow") + +*Image alt text:* **save word as pdf** workflow showing loading, warning collection, and PDF output. + +## Common Questions & Answers + +| Question | Answer | +|----------|--------| +| **Szükségem van licencre az Aspose.Words‑hez?** | Egy ingyenes értékelő licenc elegendő a teszteléshez, de a termelésben fizetős licenc szükséges a vízjel eltávolításához. | +| **Működik ez .NET Core / .NET 6+ környezetben?** | Természetesen – az Aspose.Words a .NET Standard 2.0‑t célozza, így bármely újabb .NET futtatókörnyezet kompatibilis. | +| **Konvertálhatok több DOCX fájlt egy ciklusban?** | Igen, egyszerűen hozz létre egy új `Document`‑et minden fájlhoz, és újrahasználhatod ugyanazt a `WarningInfoCollector`‑t, ha aggregált eredményeket szeretnél. | +| **Mi van, ha a kimeneti mappa nem létezik?** | A `Document.Save` `DirectoryNotFoundException`‑t dob. Hozd létre a mappát előbb, vagy használd a `Directory.CreateDirectory`‑t. | +| **Létezik mód a hiányzó betűtípusok PDF‑be ágyazására?** | Az Aspose.Words automatikusan beágyaz betűtípusokat, ha azok elérhetők a gépen; állítsd be a `PdfSaveOptions.EmbedFullFonts = true`‑t. | + +## Conclusion + +Most már egy stabil, termelés‑kész mintát birtokolsz a **Word PDF‑ként mentésére**, miközben **hiányzó betűtípusok észlelését** és az **Aspose.Words betűtípus‑helyettesítés** különböző forgatókönyveit kezeled. Figyelmeztető callback csatolásával, betűtípus‑mappák testreszabásával és opcionálisan a `PdfSaveOptions` finomhangolásával megbízhatóan **konvertálhatsz docx‑t pdf‑be**, és a felhasználókat tájékoztathatod minden olyan betűtípus‑problémáról, amely befolyásolhatja a megjelenést. + +Készen állsz a következő lépésre? Próbáld ki a PDF‑ek párhuzamos generálását több dokumentumból, vagy fedezd fel a vízjelek és digitális aláírások hozzáadását – mindkettő egyszerű kiterjesztése a most elsajátított kódnak. Boldog kódolást, és legyenek a PDF‑eid mindig úgy, ahogy elvárod! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-loadoptions/_index.md b/words/hungarian/net/programming-with-loadoptions/_index.md index fe92753425..63f2d0438f 100644 --- a/words/hungarian/net/programming-with-loadoptions/_index.md +++ b/words/hungarian/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Ezekben az oktatóanyagokban megtanulod, hogyan használhatod a LoadOptions eszk | [Word dokumentum helyreállítása Aspose.Words használatával C#-ban](./recover-word-document-with-aspose-words-in-c/) | Ismerje meg, hogyan állíthatja helyre a sérült Word dokumentumokat az Aspose.Words for .NET és C# segítségével, lépésről lépésre útmutatóval. | | [Hogyan használjuk a LoadOptions-t az Aspose.Words-ben – Teljes útmutató](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Ismerje meg a LoadOptions összes funkcióját az Aspose.Words használatához részletes, lépésről lépésre útmutatóval. | | [Sérült dokumentum helyreállítása C#-ban – Helyreállítási mód beállítása és felhasználó értesítése](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Ismerje meg, hogyan állíthatja a helyreállítási módot és kérheti a felhasználó megerősítését sérült dokumentumok betöltésekor az Aspose.Words for .NET-ben. | +| [Sérült docx helyreállítása – Teljes útmutató a sérült Word fájlok betöltéséhez C#-ban](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Ismerje meg, hogyan tölthet be és helyreállíthat sérült DOCX fájlokat C#-ban az Aspose.Words for .NET segítségével. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/hungarian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..1f5eaecbae --- /dev/null +++ b/words/hungarian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-01 +description: Gyorsan állítsa helyre a sérült docx fájlokat az Aspose.Words segítségével. + Tanulja meg, hogyan állíthat be helyreállítási módot, hogyan töltheti be biztonságosan + a docx fájlt, és hogyan olvashatja el a sérült Word fájlokat néhány lépésben. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: hu +og_description: Helyreállítsa a sérült docx fájlokat C#-ban. Állítsa be a helyreállítási + módot, biztonságosan töltse be a docx-et, és olvassa be a sérült Word fájlokat az + Aspose.Words segítségével. +og_title: Sérült docx helyreállítása – Gyors C# útmutató +tags: +- Aspose.Words +- C# +- Document Recovery +title: Sérült docx helyreállítása – Teljes útmutató a sérült Word fájlok betöltéséhez + C#‑ban +url: /hu/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Sérült docx helyreállítása – Gyors C# útmutató + +Próbált már megnyitni egy Word fájlt, amely egyszerűen nem töltődött be, és azon tűnődött, hogy a tartalom örökre elveszett-e? Sok valós projektben **recover corrupted docx** fájlokat fog helyreállítani anélkül, hogy a felhasználótól kérné a csatolmány újbóli elküldését. A jó hír, hogy az Aspose.Words ezt gyerekjátékként teszi: egyszerűen beállítja a helyreállítási módot, és hagyja, hogy a könyvtár végezze a nehéz munkát. + +Ebben az útmutatóban végigvezetjük a pontos lépéseken a **recover corrupted docx** fájlok helyreállításához, elmagyarázzuk, miért a `RecoveryMode.AutoRecover` opció a legbiztonságosabb választás, és megmutatjuk, hogyan **how to load docx** fájlokat, amelyek részben sérültek lehetnek. A végére képes lesz beolvasni egy sérült Word fájlt, kinyerni a megmaradt szöveget, és még az eredeti formátumot is naplózni a jövőbeli auditokhoz. Nincs szükség külső eszközökre, csak tiszta C# kód. + +## Amire szüksége lesz + +- **Aspose.Words for .NET** (bármely friss verzió; a használt API a 23.5‑től újabb verziókkal működik). +- Egy .NET fejlesztői környezet (Visual Studio, VS Code vagy Rider). +- A sérült vagy részben károsodott `.docx` fájl, amelyet meg szeretne menteni. + +Nincs különleges engedély, nincs COM interop, és nincs szükség a Microsoft Office telepítésére a szerveren. Egyszerű, ugye? + +## 1. lépés: Állítsa be a helyreállítási módot Auto‑Recover-re + +Ha egy Word fájl sérült, az alapértelmezett betöltési viselkedés kivételt dob és megszakít. A `LoadOptions` objektum konfigurálásával azt mondja az Aspose.Words-nek, hogy **set recovery mode**-t `AutoRecover`-ra állítsa, amely átvizsgálja a zip csomagot, kihagyja a nem olvasható részeket, és visszaadja, amit csak össze tud rakni. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Miért AutoRecover?** +> Megpróbálja a lehető legtöbbet beolvasni, miközben a dokumentumobjektum használható marad. Ha a `RecoveryMode.NoRecovery`-t választja, a betöltés az első sérülésnél meghiúsul, ami aláássa a **recover corrupted docx** forgatókönyvek célját. + +## 2. lépés: Dokumentum betöltése a konfigurált beállításokkal + +Miután a helyreállítási mód be van állítva, biztonságosan megpróbálhatja megnyitni a fájlt. Cserélje le a `"YOUR_DIRECTORY/input.docx"`-t a sérült fájl tényleges elérési útjára. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Ha a fájl csak részben sérült, a `Document` példány továbbra is létrejön. Később ellenőrizheti a `document.IsStructureValid` értéket, ha további validációra van szüksége. + +## 3. lépés: A felismert formátum ellenőrzése + +Az Aspose.Words automatikusan felismeri az eredeti formátumot (DOC, DOCX, ODT, stb.). Ennek az értéknek a kiírása segít megerősíteni, hogy a könyvtár helyesen azonosította a fájlt, ami egy gyors ellenőrzés egy **recover corrupted docx** művelet után. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Tipikus kimenet: + +``` +Loaded with Docx format. +``` + +Még ha egyes részek hiányoztak is, a formátumfelismerés továbbra is sikeres – egy újabb előny a **recover corrupted docx** munkafolyamatokban. + +## 4. lépés: Amit csak ki tud nyerni + +Miután a dokumentum betöltődött, úgy kezelheti, mint bármely egészséges Word fájlt. Az alábbi egy tömör példa, amely kinyeri a sima szöveget és a konzolra írja. Ez azt mutatja, hogy **read damaged word file** tartalmat is ki tud olvasni anélkül, hogy összeomlana. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Ha az eredeti fájl táblázatokat vagy képeket tartalmazott, amelyek sérültek, azok egyszerűen kimaradnak a szövegkimenetből. A dokumentum többi része érintetlen marad. + +## 5. lépés: Tiszta másolat mentése (opcionális) + +Gyakran szeretne a felhasználónak egy új, tiszta verziót adni a fájlból a helyreállítás után. Az azonos formátummal való mentés biztosítja a kompatibilitást minden további folyamatban. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Most már van egy **recover damaged docx** fájlja, amelyet biztonságosan csatolhat egy e‑mailhez vagy átadhat egy másik szolgáltatásnak. + +## Teljes működő példa + +Összegezve, itt van a teljes, azonnal futtatható program. Illessze be egy új konzolprojektbe, állítsa be a fájl útvonalakat, és nyomja le az F5‑öt. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Várható kimenet** (feltételezve, hogy a fájl egyetlen „Hello world!” bekezdést és némi sérült XML-t tartalmaz): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Figyelje meg, hogy a program soha nem omlik össze – annak ellenére, hogy a forrásfájl részben sérült volt. Ez a **recover corrupted docx** lényege az Aspose.Words használatával. + +## Gyakori kérdések és szélhelyzetek + +### Mi van, ha a fájl teljesen olvashatatlan? + +Még az `AutoRecover` is korlátokkal rendelkezik. Ha a zip tároló maga javíthatatlanul sérült, az Aspose.Words `CorruptedFileException`-t dob. Ebben az esetben egy harmadik fél által biztosított zip javító eszközre lehet szükség, mielőtt újra megpróbálná a **recover corrupted docx** műveletet. + +### Helyreállíthatok más formátumokat is (pl. `.doc`, `.odt`)? + +Természetesen. Ugyanaz a `LoadOptions` minden, az Aspose.Words által támogatott formátumra működik. Csak módosítsa a fájl kiterjesztését, és a könyvtár automatikusan felismeri az eredeti formátumot. Ez azt jelenti, hogy **recover damaged docx**‑szerű fájlokat, például `.doc` vagy `.rtf` fájlokat is ugyanazzal a kóddal helyreállíthatja. + +### Hogyan kezeljem a nagy dokumentumokat anélkül, hogy mindent a memóriába töltenék? + +Gigabájt méretű fájlok esetén engedélyezhet **load options**-t, például a `LoadOptions.LoadFormat`-ot, vagy a dokumentumot oldalanként streamelheti. Azonban a helyreállítási algoritmusnak továbbra is be kell olvasnia az egész csomagot, ezért nagyon nagy sérült fájlok esetén számítsa a magasabb memóriahasználatra. + +### Van mód arra, hogy megtudjuk, mely részek hiányoznak? + +Betöltés után ellenőrizheti a `document.GetChildNodes(NodeType.Any, true)`-t, és összehasonlíthatja a számot egy várt alapértékkel. A hiányzó táblázatok, képek vagy fejlécek egyszerűen nem lesznek jelen a csomópontgyűjteményben. Ez lehetővé teszi, hogy pontosan naplózza, mi volt **recover damaged docx**, és tájékoztassa a felhasználót. + +## Pro tippek a megbízható helyreállításhoz + +- **Validate the input file size** betöltés előtt; a null‑bájtos fájl mindig hibát fog eredményezni. +- **Log the `RecoveryMode` result** a `DocumentLoadingException` elkapásával és a kivétel üzenetének tárolásával; gyakran tartalmaz információkat arról, mely részek lettek kihagyva. +- **Run the recovery on a background thread** ha egy webszolgáltatásban dolgozik feltöltésekkel – ez a kérést válaszkész állapotban tartja. +- **Combine with a checksum** (pl. MD5) a helyreállított fájl és az eredeti közti eltérés felismeréséhez; ezután eldöntheti, hogy megtartja-e mindkét verziót. + +## Összegzés + +Most bemutattuk, hogyan **recover corrupted docx** fájlokat lehet C#‑ban **setting recovery mode**‑t `AutoRecover`‑ra állítva, a dokumentumot biztonságosan betöltve, a megmaradt szöveget kinyerve, és opcionálisan egy tiszta másolatot mentve. Ez a megközelítés lehetővé teszi, hogy **how to load docx** fájlokat kezeljen, amelyek egyébként kivételeket dobnának, és megbízható módot biztosít a **read damaged word file** tartalom kiolvasásához külső eszközök nélkül. + +Következő lépések? Próbálja megcserélni a `RecoveryMode.AutoRecover`-t `RecoveryMode.NoRecovery`-re, hogy lássa a különbséget, vagy kísérletezzen a `LoadOptions` tulajdonságokkal, amelyek a jelszókezelést és a betűtípuscsere szabályozzák. A helyreállítási rutin beépíthető egy ASP.NET Core API‑ba is, amely fogadja a feltöltéseket és visszaad egy javított fájlt – tökéletes vállalati dokumentumkezelő csővezetékekhez. + +Van még kérdése a Word dokumentumok helyreállításával kapcsolatban, vagy szeretné látni, hogyan **recover damaged docx** fájlokat egyedi visszahívásokkal lehet kezelni? Hagyjon megjegyzést alább, és jó kódolást! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/_index.md index 27001bd549..641617b48f 100644 --- a/words/hungarian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hungarian/net/programming-with-markdownsaveoptions/_index.md @@ -30,6 +30,7 @@ Ismerje meg, hogyan hozhat létre akadálymentes PDF-et, és konvertálhat Word ### [DOCX konvertálása Markdownba – Lépésről‑lépésre C# útmutató](./convert-docx-to-markdown-step-by-step-c-guide/) Ismerje meg, hogyan konvertálhat DOCX fájlokat Markdownba lépésről‑lépésre C#‑ban az Aspose.Words for .NET segítségével. ### [DOCX mentése Markdownba – Teljes C# útmutató LaTeX egyenletekkel](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) +### [DOCX mentése Markdownba – Word matematikai képletek exportálása LaTeX-be az Aspose.Words segítségével](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) ### [Hogyan exportáljunk LaTeX-et: DOCX konvertálása Markdownba és TXT-be](./how-to-export-latex-convert-docx-to-markdown-txt/) ### [DOCX mentése Markdownba – Teljes C# útmutató képek kinyerésével](./save-docx-as-markdown-full-c-guide-with-image-extraction/) ### [Word képek mentése – Word konvertálása Markdownba Aspose-szal](./save-word-images-convert-word-to-markdown-with-aspose/) @@ -52,6 +53,7 @@ Ismerje meg, hogyan menthet Word dokumentumokat Markdown formátumba C#-ban az A Ismerje meg, hogyan menthet Word dokumentumokat Markdown formátumba az Aspose.Words for .NET segítségével. ### [Hogyan nevezze át a képeket a DOCX‑ből Markdownba konvertáláskor](./how-to-rename-images-when-converting-docx-to-markdown/) Ismerje meg, hogyan nevezheti át a képeket a DOCX‑ből Markdownba történő konvertálás során az Aspose.Words for .NET használatával. +### [Képek feltöltése a felhőbe a Word Markdownba konvertálásakor](./upload-images-to-cloud-when-converting-word-to-markdown/) {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..f2e462e602 --- /dev/null +++ b/words/hungarian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: Mentse a docx-et markdown formátumba az Aspose.Words segítségével – tanulja + meg a Word markdownra konvertálását, az egyenletek LaTeX-be exportálását, és a markdown + képfelbontás beállítását egy gördülékeny munkafolyamatban. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: hu +og_description: mentse a docx-et markdown formátumba az Aspose.Words segítségével. + Ez az útmutató bemutatja, hogyan konvertálhatja a Word dokumentumot markdownra, + exportálhatja a képleteket LaTeX-be, és beállíthatja a markdown képek felbontását. +og_title: docx mentése markdownként – Teljes útmutató a Word matematikai képletek + LaTeX‑be exportálásához +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx mentése markdownként – Word-matematika exportálása LaTeX-be az Aspose.Words + segítségével +url: /hu/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx mentése markdownként – Export Word Math to LaTeX with Aspose.Words + +Valaha szükséged volt **docx mentése markdownként**, de elakadtál abban, hogyan tartsd meg az Office Math egyenletek éles megjelenését? Nem vagy egyedül. A legtöbb fejlesztő szembe ütközik a problémával, amikor az alapértelmezett konverzió elmosódott képekként helyezi el az egyenleteket, ami manuális átírást igényel LaTeX‑ben. + +Jó hír: az Aspose.Words elvégzi a nehéz munkát helyetted. Ebben az útmutatóban **convert word to markdown**, megmondjuk a motornak, hogy **export equations to latex**, és még **set markdown image resolution** a dokumentum többi részére is. A végére egyetlen parancsod lesz, amely tiszta `.md` fájlt hoz létre LaTeX‑kész matematikával és nagy felbontású képekkel. + +## Mit fogsz megtanulni + +- Hogyan tölts be egy `.docx` fájlt, amely Office Math objektumokat tartalmaz. +- Mely `MarkdownSaveOptions` tulajdonságok szabályozzák a **export equations to latex** és a **set markdown image resolution**. +- Egy teljes, futtatható C# kódrészlet, amelyet beilleszthetsz bármely .NET projektbe. +- Tippek a gyakori hibák elhárításához, például hiányzó betűtípusok vagy nem támogatott egyenletfunkciók. + +**Előfeltételek**: .NET 6+ (vagy .NET Framework 4.6+), licenc az Aspose.Words for .NET‑hez, és alapvető C# ismeretek. Ha kényelmesen tudsz konzolalkalmazást létrehozni, már készen állsz. + +--- + +## 1. lépés – docx mentése markdownként: Word fájl betöltése + +Az első dolog, amire szükségünk van, egy `Document` objektum, amely a forrás `.docx` fájlra mutat. Gondolj rá úgy, mint egy könyv megnyitására, mielőtt a fejezeteket másolnád. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Miért fontos*: Ha a dokumentum nem tartalmaz matematikát, a **export equations to latex** lépés nem csinál semmit, de a konverzió többi része mégis lefut. Ez az ellenőrzés megakadályozza, hogy azon tűnődj, miért hiányoznak a LaTeX blokkok a kimeneti Markdownból. + +## 2. lépés – Exportálás beállítása LaTeX‑be + +Az Aspose.Words lehetővé teszi, hogy meghatározd, hogyan legyen megjelenítve az Office Math. Alapértelmezés szerint PNG képekké alakítja őket, ezért sok útmutató egy szemcsés markdown fájllal végződik. Az `OfficeMathExportMode` `LaTeX`‑re állítása tiszta, másolásra és beillesztésre kész egyenleteket eredményez. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Miért `OfficeMathExportMode.LaTeX`?* A LaTeX a tudományos kiadványszerkesztés közös nyelve. Amikor később egy statikus weboldalkészítővel vagy Jupyter notebookkal rendereled a markdown‑t, az egyenletek minden nagyítási szinten élesek lesznek. + +## 3. lépés – Markdown képfelbontás beállítása (nem matematikai tartalomhoz) + +Bár a matematikára fókuszálunk, a legtöbb Word dokumentum képeket, diagramokat vagy beágyazott SVG‑ket is tartalmaz. Az `ImageResolution` tulajdonság szabályozza, hogyan raszterizálja ezeket az Aspose.Words. A **300 DPI** érték jó egyensúlyt biztosít a képernyő és a nyomtatás között. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tipp*: Ha a markdown csak a weben lesz megjelenítve, csökkentheted 150 DPI‑re a fájlméret csökkentése érdekében. Ezzel szemben nyomtatásra kész PDF‑ekhez növeld 600 DPI‑re. + +## 4. lépés – Konverzió futtatása – Word Math konvertálása LaTeX‑be + +Miután minden be van állítva, a tényleges konverzió egyetlen sor. Az Aspose.Words a háttérben végzi a nehéz munkát. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Várható kimenet**: Nyisd meg a generált `.md` fájlt, és valami ilyesmit kell látnod: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Vedd észre a LaTeX blokkokat (`$...$` és `$$...$$`), amelyek helyettesítik a korábbi PNG részleteket. Az alul lévő kép továbbra is PNG, 300 DPI‑n renderelve, ahogy kértük. + +## 5. lépés – Gyakori szélsőséges esetek és megoldásuk + +| Helyzet | Mi történik | Hogyan javítsuk | +|-----------|--------------|------------| +| **Hiányzó betűtípusok** (pl. Cambria Math nincs telepítve) | A LaTeX kimenet ismeretlen szimbólumokat tartalmazhat. | Telepítsd a hiányzó betűtípust a szerverre, vagy ágyazd be a dokumentumba a konverzió előtt. | +| **Komplex egyenletek** (mátrix egyedi határolókkal) | Az Aspose.Words képre vált vissza a `LaTeX` mód ellenére. | Frissíts a legújabb Aspose.Words verzióra; a könyvtár folyamatosan javítja az egyenletek lefedettségét. | +| **Nagy dokumentumok** ( > 50 MB ) | A memória nyomás `OutOfMemoryException`-t okozhat. | Használd a `LoadOptions`-t `LoadFormat.Docx`‑szel és streameld a fájlt, vagy oszd fel a dokumentumot szekciókra a konverzió előtt. | +| **Túl nagy képméret** | A Markdown fájl hatalmas lesz, lelassítva a statikus weboldal építést. | Csökkentsd az `ImageResolution`‑t 150 DPI‑re web‑csak esetekben (lásd a 3. lépést). | + +## 6. lépés – Összeállítás: Teljes működő példa + +Az alábbi *teljes* konzolalkalmazás programot másolhatod és beillesztheted a `Program.cs`‑be. Tartalmazza az összes korábban tárgyalt elemet, plusz egy kis extra hibakezelést. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Futtasd a programot (`dotnet run`), és kapsz egy markdown fájlt, amely **docx mentése markdownként**, miközben minden egyenletet LaTeX‑ben őriz meg. Nincs manuális másolás‑beillesztés, nincs csúnya raszter kép a matematikához. + +## Összegzés + +Áttekintettük a teljes folyamatot a **docx mentése markdownként** Aspose.Words‑szal, a Word fájl betöltésétől a **export equations to latex** és a **set markdown image resolution** beállításáig. A végső kódrészlet készen áll a termelésre, és beilleszthető bármely .NET projektbe, amelynek **convert word to markdown** funkcióra van szüksége valós időben. + +Mi a következő? Próbáld meg a generált `.md`‑t betáplálni egy statikus weboldalkészítőbe, például Hugo vagy Jekyll, és nézd meg, ahogy az egyenletek gyönyörűen renderelődnek. Ha a **convert word math latex**‑t más formátumokra (PDF, HTML) szeretnéd átalakítani, egyszerűen cseréld ki a `MarkdownSaveOptions`‑t `PdfSaveOptions`‑ra vagy `HtmlSaveOptions`‑ra – a `OfficeMathExportMode` zászló mindkettőnél működik. + +Van valami sajátosság a munkafolyamatodban, például Word fájlok letöltése Azure Blob tárolóból vagy streamingelése egy API‑ból? Ugyanaz a minta alkalmazható; csak cseréld le a fájlrendszer `Document` konstruktorát egy stream‑alapúra. + +Nyugodtan kísérletezz, és írd meg a hozzászólásokban, hogyan oldotta meg ez a megközelítés a konverziós problémáidat. Boldog kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..e83c99dc45 --- /dev/null +++ b/words/hungarian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: Tölts fel képeket a felhőbe, miközben egy Word dokumentumot markdown + formátumba konvertálsz. Tanuld meg, hogyan lehet képeket kinyerni a docx‑ből, és + tárolni őket az Azure Blob tárolóban. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: hu +og_description: Tölts fel képeket a felhőbe, miközben egy Word dokumentumot markdown + formátumba konvertálsz. Ez az útmutató bemutatja, hogyan lehet képeket kinyerni + a docx fájlból, és tárolni őket az Azure Blob tárolóban. +og_title: Képek feltöltése a felhőbe Word Markdownra konvertáláskor +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Képek feltöltése a felhőbe Word Markdown formátumba konvertálásakor +url: /hu/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Képek feltöltése a felhőbe Word‑ból Markdown‑ba konvertálás közben + +Volt már, hogy **képeket kell feltölteni a felhőbe**, miközben egy Word‑fájlt markdown‑ná alakítasz? Nem vagy egyedül – a fejlesztők folyamatosan egyensúlyoznak a dokumentumkonverzió és az eszközkezelés között, és mindkettőt egy sima folyamatban megvalósítani olyan, mintha egy mozgó célt próbálnál elkapni. + +A jó hír? Az Aspose.Words segítségével kinyerheted a .docx‑ből minden képet, diagramot vagy ábrát, közvetlenül az Azure Blob Storage‑ba tolhatod, és a generált markdown a felhő‑URL‑eket fogja hivatkozni a helyi fájlok helyett. Ebben az útmutatóban végigvezetünk a teljes folyamaton, a forrásdokumentum betöltésétől egészen egy tiszta markdown‑fájl elkészítéséig, amely az Azure tárolódra mutat. + +A végére **docx‑et markdown‑ná konvertálhatsz**, **képeket nyerhetsz ki a docx‑ből**, és **képeket tárolhatsz Azure Blob‑ban** – mindezt néhány C#‑sorral. Nincs külső eszköz, nincs kézi másolás‑beillesztés, és biztosan nincsenek törött kép hivatkozások. + +## Amire szükséged lesz + +- **.NET 6.0** vagy újabb (a kód .NET Core‑on és .NET Framework‑ön is működik) +- **Aspose.Words for .NET** (NuGet csomag `Aspose.Words`) +- Egy **Azure Storage fiók** egy konténerrel (pl. `images`) és egy megosztott hozzáférési kulccsal – a csatlakozási karakterláncra lesz szükséged a fájlok feltöltéséhez. +- Alapvető C# és async/await ismeretek (opcionális, de hasznos). + +Ha már mindez megvan, nagyszerű – ugorjunk egyenesen a megoldásra. Ha nem, a végén lévő „Előkövetelmények” szekció gyors beállítási lépéseket mutat. + +## 1. lépés: Azure Blob segéd létrehozása (Miért fontos) + +Mielőtt még a Word‑dokumentumhoz nyúlnánk, szükségünk van egy apró segédeszközre, amely tudja, hogyan tolja fel a byte‑tömböt az Azure Blob Storage‑ba, és visszaad egy nyilvános URL‑t. Ez az absztrakció tisztán tartja a konverziós logikát, és később könnyen cserélhetővé teszi a tárolási szolgáltatót. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Miért ez a segéd?** +1. **Felelősségek szétválasztása** – a markdown‑konverzió kódja a dokumentumkezelésre koncentrál, nem pedig a HTTP részletekre. +2. **Újrafelhasználhatóság** – a `UploadAsync`‑t bárhol meghívhatod az alkalmazásodban (pl. felhasználói feltöltött képek esetén). +3. **Jövőbiztos** – ha Amazon S3‑ra vagy Google Cloud Storage‑ra szeretnél váltani, csak egy új implementációra van szükség ugyanazzal a felülettel. + +> **Pro tipp:** Állítsd a konténer hozzáférési szintjét `Blob`‑ra (nyilvános) csak akkor, ha egyetértesz azzal, hogy bárki olvashassa a képeket. Privát esetekben generálj SAS tokeneket feltöltésenként, és ezeket az URL‑eket ágyazd be. + +## 2. lépés: Erőforrás‑mentés visszahívás definiálása (A feltöltés‑konvertálás magja) + +Az Aspose.Words lehetővé teszi, hogy minden erőforrást (kép, diagram stb.) elkapj, amelyet normál esetben a markdown mentésekor a lemezre írna. Egy `ResourceSavingCallback` megadásával minden erőforrást feltölthetünk az Azure Blob‑ra, és a helyi fájlnevet a felhő‑URL‑re cserélhetjük. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Mi történik itt?** + +- **Kinyerés** – az Aspose.Words egy streamet ad minden képhez. +- **Feltöltés** – ezt a streamet átadjuk az `AzureBlobUploader`‑nek. +- **Csere** – a markdown‑író megkapja a nyilvános URL‑t, és azt írja be a markdown kép szintaxisba (`![](https://…)`). + +Mivel `args.AlreadyExists = true`‑t állítunk, nem keletkeznek ideiglenes fájlok a fájlrendszeren – egy tiszta, állapot‑független művelet, amely tökéletes szerver‑lessz függvényekhez. + +## 3. lépés: Markdown mentési beállítások konfigurálása (Mindent összekötve) + +Most beágyazzuk a visszahívást az Aspose.Words `MarkdownSaveOptions`‑ba. A kulcsfontosságú flag-ek: `ExportImagesAsBase64 = false` (hogy külső hivatkozásokat kapjunk) és `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Miért kapcsoljuk ki a Base64‑t?** +Ha az `ExportImagesAsBase64` igaz, az Aspose minden képet közvetlenül a markdown‑ba ágyaz data‑URI‑ként. Ez ellentétes a **képek felhőbe feltöltése** céllal, mert a markdown fájl mérete felrobban, és a képek rejtve maradnak a CDN‑ben. Kikapcsolva tiszta, külső hivatkozásokat kapunk, amelyek az Azure Blob‑ra mutatnak – pontosan, amit egy modern statikus‑site generátor elvár. + +## 4. lépés: Összeállítás – Egy minimális konzolalkalmazás + +Az alábbiakban egy teljes, azonnal futtatható konzolprogram látható. Cseréld ki a helyőrzőket a saját Azure csatlakozási karakterláncodra és konténer nevedre. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Várható kimenet + +A program futtatása `sample.docx`‑szel, amely két képet tartalmaz, a következőt eredményezi: + +- `output.md` markdown kép szintaxissal, például: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-pdfsaveoptions/_index.md b/words/hungarian/net/programming-with-pdfsaveoptions/_index.md index ca72fda6c2..92970585c5 100644 --- a/words/hungarian/net/programming-with-pdfsaveoptions/_index.md +++ b/words/hungarian/net/programming-with-pdfsaveoptions/_index.md @@ -46,9 +46,9 @@ Akár Word dokumentumokat szeretne PDF formátumba konvertálni online terjeszt | [3D DML 3DEffektusok renderelése PDF dokumentumban](./dml-3deffects-rendering/) | Tanulja meg, hogyan jeleníthet meg lenyűgöző 3D DML-effektusokat PDF dokumentumokban az Aspose.Words for .NET használatával ezzel az átfogó, lépésről lépésre szóló útmutatóval. | | [Képek interpolálása egy PDF dokumentumban](./interpolate-images/) | Tanulja meg, hogyan interpolálhat képeket egy PDF dokumentumban az Aspose.Words for .NET használatával lépésről lépésre bemutató útmutatónkkal. Javítsa PDF-je képminőségét könnyedén. | | [Docx mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Lépésről lépésre bemutatja, hogyan konvertálhatja a DOCX fájlokat PDF-be C#-ban az Aspose.Words könyvtárral. | +| [Dokumentum mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Lépésről lépésre útmutató a dokumentum PDF-be mentéséhez az Aspose.Words használatával C# nyelven. | | [Elérhető PDF létrehozása Wordből C#‑val – Lépés‑ről‑lépésre útmutató](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Tanulja meg, hogyan hozhat létre akadálymentes PDF-et Word dokumentumból C#‑ban az Aspose.Words for .NET segítségével. | | [Akadálymentes PDF létrehozása C#-ban – PDF hozzáférhetőségi útmutató](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Ismerje meg, hogyan hozhat létre akadálymentes PDF-et C#-ban az Aspose.Words for .NET segítségével. | - | [Képek interpolálása egy PDF dokumentumban](./interpolate-images/) | Tanulja meg, hogyan interpolálhat képeket egy PDF dokumentumban az Aspose.Words for .NET használatával lépésről lépésre bemutató útmutatóval. Javítsa PDF-je képminőségét könnyedén. | | [Hozzon létre akadálymentes PDF-et Wordből – Teljes útmutató](./create-accessible-pdf-from-word-complete-guide/) | Lépésről lépésre útmutató az akadálymentes PDF-ek létrehozásához Word dokumentumokból az Aspose.Words for .NET használatával. | | [Hozzon létre hozzáférhető PDF-et – Lépésről lépésre útmutató a PDF/UA megfeleléshez](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Tanulja meg, hogyan készíthet PDF/UA szabványú, akadálymentes PDF-et az Aspose.Words for .NET segítségével. | diff --git a/words/hungarian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/hungarian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..4084ffeb88 --- /dev/null +++ b/words/hungarian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Ismerje meg, hogyan menthet dokumentumot PDF formátumba az Aspose.Words + használatával C#-ban. A tutorial emellett lefedi a Word PDF-re konvertálását, a + matematikai LaTeX exportálását és a hiányzó betűtípusok kezelését. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: hu +og_description: Mentse a dokumentumot PDF formátumban könnyedén az Aspose.Words segítségével. + Ez az útmutató bemutatja, hogyan konvertálhatja a Word-et PDF-re, exportálhatja + a matematikai LaTeX-et, és kezelheti a hiányzó betűtípusokat. +og_title: Dokumentum mentése PDF‑be az Aspose.Words segítségével – Teljes C# útmutató +tags: +- Aspose.Words +- C# +- PDF generation +title: Dokumentum mentése PDF‑ként az Aspose.Words segítségével – Teljes C# útmutató +url: /hu/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Dokumentum mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató + +Gondolkodtál már azon, **hogyan mentheted el a dokumentumot PDF‑ként** közvetlenül egy Word‑fájlból anélkül, hogy elveszítenéd a hozzáférhetőségi funkciókat? Nem vagy egyedül – a fejlesztők folyamatosan keresik a megbízható módot a Word‑PDF konvertálásra, miközben megőrzik a matematikai egyenleteket és elegánsan kezelik a hiányzó betűtípusokat. + +Ebben az útmutatóban lépésről‑lépésre bemutatunk egy megoldást, amely nem csak **save document as pdf**, hanem demonstrálja a **convert word to pdf**, **export math latex**, és **handle missing fonts** funkciókat a legújabb Aspose.Words for .NET segítségével. A végére egy kész‑C# programod lesz, amely PDF/UA‑2 kompatibilis fájlokat állít elő, tökéletesen alkalmas hozzáférhetőségi auditokra. + +## What You’ll Need + +- .NET 6 vagy újabb (a kód .NET Core‑dal és .NET Framework‑kel is működik) +- Aspose.Words for .NET 25.10 vagy újabb – ingyenes próbaverziót a Aspose weboldaláról tölthetsz le +- Egy egyszerű Word‑dokumentum (`input.docx`), amely legalább egy lebegő alakzatot és egy matematikai egyenletet tartalmaz (a **export‑math‑latex** funkció megtekintéséhez) +- Visual Studio 2022 (vagy bármely kedvelt IDE) + +> **Pro tip:** Ha CI/CD pipeline‑t használsz, add hozzá az Aspose.Words NuGet csomagot a projektfájlodhoz: + +```xml + +``` + +Most merüljünk el a kódban. + +## Step 1: Load the Source Document with Automatic Recovery + +Valós Word‑fájlok esetén előfordulhatnak sérült szakaszok vagy hiányzó erőforrások. Az automatikus helyreállítás engedélyezése biztosítja, hogy a betöltés soha ne dobjon kivételt. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Miért fontos:** +`RecoveryMode.AutoRecover` megvédi a pipeline‑t a hibás bemenetek miatti összeomlástól, ami különösen hasznos, ha **convert word to pdf** tömegesen végzed. + +## Step 2: Set Up PDF Save Options for Full Accessibility + +A PDF/UA‑2 az ISO szabvány az akadálymentes PDF‑ekhez. Néhány jelző beállításával olyan fájlt kapunk, amelyet a képernyőolvasók navigálni tudnak, és biztosítjuk, hogy a matematikai egyenletek rejtett LaTeX‑ként legyenek exportálva. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Főbb pontok:** + +- **ExportFloatingShapesAsInlineTag** – biztosítja, hogy a létrejövő PDF megőrizze az eredeti elrendezést, miközben szemantikus szempontból helyes marad. +- **OfficeMathExportMode.LaTeX** – teljesíti a **export math latex** követelményt, lehetővé téve, hogy a downstream eszközök kinyerjék az egyenleteket, ha szükséges. + +## Step 3: Capture Warnings (e.g., Missing Fonts) + +A hiányzó betűtípusok gyakori fejfájás a dokumentumok konvertálásakor. Az Aspose.Words egy `WarningCallback`‑en keresztül jelentheti ezeket a problémákat. Összegyűjtjük őket, hogy később naplózhassuk vagy kezelhessük őket. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Miért érdekel:** +Ha a forrás olyan betűtípust használ, amely nincs telepítve a szerveren, a PDF alapértelmezett betűtípusra vált, ami esetleg tönkreteheti az elrendezést. **handle missing fonts** segítségével felhívhatjuk a felhasználó figyelmét, vagy beágyazhatunk egy helyettesítőt. + +## Step 4: Save the Document as an Accessible PDF + +Itt jön a döntő pillanat – a tényleges konvertálás. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Ha minden rendben megy, egy PDF/UA‑2 fájlt kapsz, amely rejtett LaTeX‑et tartalmaz minden egyenlethez, és megfelelő címkézést a lebegő alakzatokhoz. + +## Step 5: Review Captured Warnings (Optional but Recommended) + +A mentés után végigiterálhatunk a gyűjtött figyelmeztetéseken és naplózhatjuk őket. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +A tipikus kimenet például így nézhet ki: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Ezeknek az üzeneteknek a korai megtekintése segít **handle missing fonts** még azelőtt, hogy a végfelhasználókat érintenék. + +## Full Working Example + +Mindent egy helyen, itt a teljes, futtatható program. Cseréld ki a helyőrző útvonalakat a sajátjaidra. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Várható eredmény:** +- `output.pdf` megfelel a PDF/UA‑2 szabványnak. +- Minden lebegő alakzat inline ábraként van címkézve. +- Minden Office Math objektum rejtett LaTeX‑ként jelenik meg (látható, ha a PDF struktúráját vizsgálod). +- Bármely betűtípussal kapcsolatos probléma a konzolra kerül kiírásra, így **handle missing fonts** még a fájl kiadása előtt. + +![Diagram showing the flow from Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flow diagram for saving document as pdf") + +*Image alt text:* **Diagram of how to save document as pdf using Aspose.Words** + +## Common Questions & Edge Cases + +### What if I’m using an older Aspose.Words version? + +Az `OfficeMathExportMode.LaTeX` jelző a 25.10‑es verzióban került bevezetésre. Régebbi kiadásoknál is **convert word to pdf** lehetséges, de a matematika raszteres lesz a LaTeX exportálása helyett. A legjobb hozzáférhetőségért frissíts. + +### Can I embed custom fonts to avoid fallback? + +Igen. Állítsd be a `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` értéket a `Save` hívása előtt. Ez szintén segít **handle missing fonts**, mivel a PDF tartalmazni fogja a szükséges glifeket. + +### How do I verify the PDF/UA‑2 compliance? + +Nyisd meg a fájlt az Adobe Acrobat Pro‑ban → “Print Production” → “Preflight”. Válaszd a “PDF/A‑2b” vagy “PDF/UA‑2” profilt; az Acrobat jelenteni fog minden esetleges megsértést. + +### What about password‑protected Word files? + +Töltsd be a dokumentumot egy `LoadOptions`‑szal, amely tartalmazza a `Password`‑t. Példa: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +A pipeline többi része változatlan marad. + +## Conclusion + +Mindent lefedtünk, ami ahhoz kell, hogy **save document as pdf** használatával Aspose.Words‑ben C#‑ban dolgozz. Az útmutató bemutatta, hogyan **convert word to pdf**, **export math latex**, és **handle missing fonts**, miközben egy hozzáférhető PDF/UA‑2 fájlt állít elő. + +Próbáld ki a kódot, kísérletezz különböző `PdfSaveOptions`‑okkal (pl. képtömörítés, PDF/A‑2b), és integráld a dokumentum‑feldolgozó szolgáltatásodba. Ha tovább szeretnél menni, nézd meg az Aspose PDF‑specifikus könyvtárát a poszt‑feldolgozáshoz vagy digitális aláírásokhoz. + +Van még olyan szituáció, amit szeretnél megoldani? Nyugodtan írj kommentet, vagy nézd meg a többi útmutatónkat a **PDF manipulation**, **image extraction**, és **batch conversion** témakörökben. Boldog kódolást! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-shapes/_index.md b/words/hungarian/net/programming-with-shapes/_index.md index e44b22cb00..c3badc2991 100644 --- a/words/hungarian/net/programming-with-shapes/_index.md +++ b/words/hungarian/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Az Aspose.Words for .NET használatával és az alábbi oktatóanyagok követés | [Téglalap alakzat létrehozása Word-ben C#-ban – Lépésről lépésre útmutató](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Tanulja meg, hogyan hozhat létre téglalap alakzatot Word dokumentumban C# segítségével lépésről lépésre. | | [Aspose.Words alakzat árnyék tutorial – Árnyék hozzáadása Word alakzathoz C#-ban](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Tanulja meg, hogyan adhat árnyékot a Word alakzatokhoz C#-ban az Aspose.Words segítségével. | | [Üres Word dokumentum létrehozása árnyékolt téglalap alakzattal – Lépésről lépésre útmutató](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Tanulja meg, hogyan hozhat üres Word dokumentumot árnyékolt téglalap alakzattal az Aspose.Words for .NET használatával. | +| [Hogyan mozgassuk az árnyékot az Aspose.Words-ben – Teljes C# útmutató](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Tanulja meg, hogyan helyezheti át az árnyékot Word alakzatokban C#-ban az Aspose.Words segítségével. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/hungarian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..63337d3874 --- /dev/null +++ b/words/hungarian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-05-01 +description: Hogyan mozgassuk az árnyékot egy alakzaton az Aspose.Words segítségével + C#-ban. Tanulja meg, hogyan adjon árnyékot az alakzathoz, módosítsa a elmosódást, + állítsa be az átlátszóságot, és forgassa el az árnyékot percek alatt. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: hu +og_description: Hogyan mozgassuk az árnyékot egy alakzaton az Aspose.Words-ben C#-al. + Ez az útmutató megmutatja, hogyan adhatunk árnyékot az alakzathoz, módosíthatjuk + a elmosódást, beállíthatjuk az átlátszóságot, és elforgathatjuk az árnyékot. +og_title: Hogyan mozgassuk a árnyékot az Aspose.Words-ben – Teljes C# útmutató +tags: +- Aspose.Words +- C# +- Document Automation +title: Hogyan mozgassuk az árnyékot az Aspose.Words-ben – Teljes C# útmutató +url: /hu/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan mozgassuk az árnyékot az Aspose.Words‑ben – Teljes C# útmutató + +Gondolkodtál már azon, **how to move shadow** egy alakzaton belül egy Word dokumentumban anélkül, hogy manuálisan megnyitnád a Word‑et? A mindennapi munkám során gyakran kellett programozottan finomhangolni egy alakzat árnyékát – legyen szó egy kifinomult jelentésről vagy egy dinamikus sablonról. A jó hír? Az Aspose.Words‑szal néhány sorban megteheted, és megtanulod a **add shadow to shape**, **how to change blur**, **how to set transparency**, és **how to rotate shadow** kifejezéseket is egy lépésben. + +Ebben az útmutatóban egy valós példán keresztül vezetünk végig: betöltünk egy meglévő DOCX‑et, amely már tartalmaz egy alakzatot, beállítjuk az árnyék pozícióját, lágyaságát, átlátszóságát és irányát, majd elmentjük az eredményt. A végére egy újrahasználható kódrészletet kapsz, amelyet bármely .NET projektbe beilleszthetsz, és megérted, miért fontos minden egyes tulajdonság. + +## Előkövetelmények – Amire szükséged van a kezdéshez + +- **Aspose.Words for .NET** (version 23.12 vagy újabb). Letöltheted a NuGet‑ről a `Install-Package Aspose.Words` paranccsal. +- .NET 6+ fejlesztői környezet (Visual Studio, VS Code, Rider – bármi, amit kedvelsz). +- Bemeneti Word fájl (`input.docx`), amely már tartalmaz legalább egy alakzatot (egy téglalap, kör vagy kép is megfelel). +- Alapvető ismeretek a C# szintaxisról – semmi különös. + +Ha valamelyik hiányzik, állj meg egy pillanatra és telepítsd a könyvtárat; a további útmutató feltételezi, hogy a csomag már hivatkozásként szerepel. + +## 1. lépés: Dokumentum betöltése és a cél alakzat lekérése – **How to Move Shadow** itt kezdődik + +Az első lépés a forrásdokumentum betöltése és a módosítani kívánt alakzat megtalálása. Az Aspose.Words minden objektumot (bekezdések, táblázatok, alakzatok) egy fa csomópontjaként kezel, így közvetlenül lekérdezhetjük. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Miért fontos ez:** A dokumentum egyszeri betöltése és ugyanazon `Document` példány újrahasználata hatékony. A `GetChild` hívás biztonságos, mivel `null`‑t ad vissza, ha az index a tartományon kívül van, így hiányzó alakzatokat elegánsan kezelhetjük. + +## 2. lépés: A BlurRadius beállítása – Master **How to Change Blur** + +A lágy árnyék professzionális hatást kölcsönöz, míg a kemény él olcsónak tűnhet. A `BlurRadius` tulajdonság a lágyaságot pontokban szabályozza (1 pt ≈ 1/72 inch). Emeljük 8 pt‑re. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** Az alapértelmezett blur 0.5 pt. Az 5 pt‑nél nagyobb érték általában észrevehető, de vigyázz, hogy ne legyen túl nagy – ez elválasztja az alakzatot az oldaltól. + +## 3. lépés: Átlátszóság beállítása – A válasz a **How to Set Transparency**-re + +Az átlátszóság határozza meg, mennyire látható az árnyék. A `0` érték teljesen átlátszatlan, az `1` pedig teljesen láthatatlan. Egy finom hatáshoz `0.3`‑at (30 % átlátszó) használunk. + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Miért lehet ez fontos:** Ha az alakzat sötét, egy teljesen átlátszatlan árnyék elnyomhatja a mögöttes szöveget. Az átlátszóság beállítása olvashatóvá teszi a dokumentumot, miközben mélységet ad. + +## 4. lépés: Árnyék mozgatása – A **How to Move Shadow** lényege + +A `Distance` tulajdonság határozza meg, milyen távolságra helyezkedik el az árnyék az alakzattól, pontokban mérve. Nagyobb távolság esetén az árnyék távolabb helyezkedik el, drámaibb hatást keltve. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Mi van, ha apró eltolásra van szükség?** A `Distance` `0`‑ra állítása azt eredményezi, hogy az árnyék közvetlenül az alakzat mögött helyezkedik el, ami domborítási hatáshoz hasznos lehet. + +## 5. lépés: A fényforrás forgatása – Megoldás a **How to Rotate Shadow**-ra + +Az árnyékok nem csak egyenes lefele esnek; a fényforrás szögét követik. Az `Angle` tulajdonság (fokban) elforgatja az árnyékot az alakzat körül. Hajtsuk 45°‑ra. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Gyors kísérlet:** Próbáld `90`‑et a jobb oldali árnyékhoz vagy `-30`‑at a balra dőlőhöz. A vizuális változás azonnali. + +## 6. lépés: Dokumentum mentése – Az **Add Shadow to Shape** eredményének megtekintése + +Miután finomhangoltuk az árnyékot, visszaírjuk a dokumentumot a lemezre. Felülírhatod az eredetit vagy létrehozhatsz egy új fájlt; a példában egy új kimeneti fájlt használunk. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Várható kimenet:** Nyisd meg a `output.docx`‑et. Az alakzat árnyéka lágyabb, enyhén eltolódott, félig átlátszó és 45°‑os szögben lesz. Ha oldalról oldalra összehasonlítod a `input.docx`‑el, a különbség egyértelmű. + +### Teljes működő példa (másolás-beillesztés kész) + +Az alábbiakban az egész program egy blokkban látható. Illeszd be egy új konzolos projektbe, cseréld le a `YOUR_DIRECTORY`‑t egy valós mappára, és futtasd. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Gyakori kérdések és szélhelyzetek + +### Mi van, ha a dokumentumnak több alakzata van? + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Hozzáadhatok-e árnyékot egy olyan alakzathoz, amelynek eddig nincs? + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Működik ez képekkel és SmartArt‑tal? + +Igen. Bármely, a `Shape`‑ből származó csomópont – beleértve a képeket, diagramokat és a SmartArt‑ot – rendelkezik `ShadowFormat`‑tal. Ugyanazok a tulajdonságok érvényesek. + +### Hogyan szabályozhatom az árnyék színét? + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Kompatibilitási aggályok? + +Az Aspose.Words 23.12+ támogatja a .NET 6, .NET Core 3.1 és a .NET Framework 4.6.2+ verziókat. A bemutatott API stabil ezen verziók között. + +## Összegzés + +Most megtanultuk, hogyan **move shadow** egy alakzaton az Aspose.Words segítségével, és közben bemutattuk a **add shadow to shape**, **how to change blur**, **how to set transparency**, és **how to rotate shadow** funkciókat is. A teljes, futtatható példa lehetővé teszi, hogy néhány másodperc alatt módosítsd bármely alakzat árnyékát, így dokumentumaid kifinomult, professzionális megjelenést kapnak anélkül, hogy megnyitnád a Word‑et. + +Készen állsz a következő lépésre? Próbáld meg kombinálni ezeket az árnyékbeállításokat **conditional formatting**‑gal – például csak a címsorokra vagy a bizonyos méretet meghaladó diagramokra alkalmazz mélyebb árnyékot. Vagy fedezd fel a **gradient fills**‑t az alakzaton, hogy igazán figyelemfelkeltő dizájnt hozz létre. + +Ha bármilyen problémába ütközöl, hagyj egy megjegyzést alább. Boldog kódolást, és legyenek az árnyékaid mindig ott, ahol szeretnéd! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/basic-conversions/_index.md b/words/indonesian/net/basic-conversions/_index.md index 5daed8920b..481e0ffd22 100644 --- a/words/indonesian/net/basic-conversions/_index.md +++ b/words/indonesian/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Cara Mengekspor LaTeX dari Word – Panduan Langkah‑demi‑Langkah](./how-to-export-latex-from-word-step-by-step-guide/) | Pelajari cara mengekspor dokumen Word ke format LaTeX dengan Aspose.Words untuk .NET dalam panduan langkah demi langkah. | | [Mengonversi Word ke PDF dalam C# menggunakan Aspose.Words – Panduan](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Panduan langkah demi langkah mengonversi dokumen Word ke PDF menggunakan Aspose.Words dalam C#. Bahasa Indonesia: | | [Simpan docx sebagai pdf dengan Aspose.Words – Panduan Lengkap C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Panduan langkah demi langkah menyimpan file DOCX sebagai PDF menggunakan Aspose.Words dalam C#. Cocok untuk pengembang. | +| [Simpan Word sebagai PDF dengan Aspose.Words – Panduan Lengkap](./save-word-as-pdf-with-aspose-words-complete-guide/) | Panduan lengkap langkah demi langkah menyimpan dokumen Word ke PDF menggunakan Aspose.Words. Cocok untuk pengembang .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/indonesian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index afa39fadd8..cbda0ab686 100644 --- a/words/indonesian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/indonesian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Cara mengekspor LaTeX dari Word menggunakan Aspose.Words – pelajari cara - mengonversi Word ke LaTeX, menyimpan file docx sebagai txt, dan menangani persamaan - dalam teks biasa. +date: 2026-05-01 +description: Pelajari cara mengekspor LaTeX dari file Word, mengonversi Word ke txt, + dan mempertahankan tabel menggunakan Aspose.Words dalam C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: id -og_description: Cara mengekspor LaTeX dari Word dengan Aspose.Words. Panduan ini menunjukkan - cara mengonversi Word ke LaTeX, menyimpan docx sebagai txt, dan menjaga persamaan - tetap utuh. -og_title: Cara Mengekspor LaTeX dari Word – Tutorial C# Cepat +og_description: Temukan cara mengekspor LaTeX dari Word, mengonversi Word ke teks + biasa, dan menjaga tata letak tabel tetap utuh dengan Aspose.Words. +og_title: Cara Mengekspor LaTeX dari Word – Tutorial C# Lengkap tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Cara Mengekspor LaTeX dari Word – Panduan Langkah demi Langkah url: /id/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,158 +26,215 @@ url: /id/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Cara Mengekspor LaTeX dari Word – Panduan Langkah‑per‑Langkah +# Cara Mengekspor LaTeX dari Word – Tutorial C# Lengkap -Pernah bertanya-tanya **bagaimana cara mengekspor LaTeX dari Word** tanpa kehilangan persamaan Office Math yang rumit? Anda bukan satu-satunya. Banyak pengembang menemui kendala ketika mereka mencoba *mengonversi Word ke LaTeX* untuk makalah akademik, laporan ilmiah, atau pipeline penerbitan otomatis. +Pernah bertanya-tanya **cara mengekspor LaTeX** dari dokumen Word tanpa kehilangan persamaan matematika? Anda tidak sendirian. Banyak pengembang perlu mengubah .docx yang berisi Office Math menjadi LaTeX bersih sekaligus **mengonversi Word ke txt** untuk pemrosesan lanjutan. Dalam panduan ini kami akan membahas solusi praktis yang siap dijalankan, yang **mempertahankan tabel**, memberikan file teks biasa, dan menjaga markup LaTeX tepat di tempat yang Anda butuhkan. -Dalam tutorial ini kami akan membahas contoh C# lengkap yang siap dijalankan yang menunjukkan **cara mengekspor LaTeX** menggunakan Aspose.Words, menjelaskan **cara menyimpan txt** dengan markup LaTeX, dan bahkan membahas nuansa **convert word equations latex** sehingga tidak ada yang hilang dalam proses konversi. - -> **Pro tip:** Pendekatan yang sama bekerja untuk file .docx apa pun yang Anda miliki—cukup arahkan kode ke jalur file yang berbeda. +Kami akan membahas semuanya mulai dari memuat file sumber hingga menyesuaikan `TxtSaveOptions` sehingga outputnya ramah manusia dan mesin. Pada akhir tutorial Anda akan dapat **menyimpan docx sebagai txt**, **mengonversi Word ke teks biasa**, dan mengetahui **cara mempertahankan tabel** selama proses ekspor. Tanpa skrip eksternal, tanpa menyalin‑tempel manual—hanya kode C# murni yang dapat Anda masukkan ke proyek .NET mana pun. ## Apa yang Anda Butuhkan -| Prerequisite | Mengapa penting | -|--------------|-----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words menargetkan runtime .NET modern. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | Perpustakaan ini melakukan pekerjaan berat dalam memparsing Word dan menghasilkan LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Untuk melihat konversi LaTeX secara langsung. | -| **Visual Studio 2022** (or any IDE you like) | Memudahkan proses debugging dan menjalankan contoh. | - -Jika Anda belum menginstal paket NuGet, jalankan: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (versi terbaru, 2024.x atau lebih baru). Paket NuGet‑nya adalah `Aspose.Words`. +- Lingkungan pengembangan .NET (Visual Studio, VS Code, Rider—semua dapat). +- File Word (`.docx`) yang berisi persamaan Office Math dan setidaknya satu tabel (agar kita dapat melihat keajaiban preservasi tabel). -Itu saja—tidak ada DLL tambahan, tidak ada interop COM, hanya perpustakaan terkelola yang bersih. +Itu saja. Jika Anda sudah memiliki semua itu, lanjutkan membaca; jika belum, unduh paket NuGet dan contoh DOCX sebelum kita melangkah lebih jauh. -## Cara Mengekspor LaTeX dari Word – Gambaran Umum - -Berikut adalah gambaran besar apa yang akan kami capai: +--- -1. **Muat** dokumen Word sumber (`.docx`). -2. **Konfigurasikan** `TxtSaveOptions` sehingga semua objek Office Math dikeluarkan sebagai kode LaTeX. -3. **Simpan** dokumen sebagai file teks biasa (`.txt`) yang dapat Anda berikan langsung ke kompiler LaTeX mana pun. +## Cara Mengekspor LaTeX dari Dokumen Word -![Contoh cara mengekspor LaTeX dari Word](image.png "Cara mengekspor LaTeX dari Word") +Berikut inti tutorial—tiga langkah singkat yang menjawab pertanyaan **cara mengekspor latex** sekaligus menangani tujuan sekunder **mengonversi word ke txt**, **mengonversi word ke teks biasa**, **menyimpan docx sebagai txt**, dan **cara mempertahankan tabel**. -## Langkah 1: Muat Dokumen Word +### Langkah 1: Muat File DOCX -Pertama-tama—buka .docx yang ingin Anda konversi. Kelas `Document` mengabstraksi semua XML di baliknya, memberikan Anda model objek yang ramah. +Pertama kita harus membaca dokumen Word ke dalam objek `Aspose.Words.Document`. Langkah ini sama apakah Anda nanti **mengonversi word ke txt** atau **menyimpan docx sebagai txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Mengapa ini penting:** -Muat file lebih awal memungkinkan kami memeriksa isinya (mis., menghitung persamaan) sebelum memutuskan cara menserialisasikannya. Jika file rusak, `Document` akan melemparkan pengecualian yang jelas, menyelamatkan Anda dari output yang misterius nanti. +> **Mengapa ini penting:** Memuat file membuat representasi dalam memori dari semua elemen Word—paragraf, tabel, dan objek Office Math. Tanpa objek ini Anda tidak dapat memanipulasi opsi ekspor. + +### Langkah 2: Konfigurasikan `TxtSaveOptions` untuk LaTeX dan Tata Letak Tabel -## Langkah 2: Konfigurasikan TxtSaveOptions untuk Ekspor LaTeX +Kelas `TxtSaveOptions` memungkinkan Anda mengontrol secara tepat bagaimana file teks biasa dihasilkan. Dua properti penting untuk skenario kita: -Keajaiban terjadi di `TxtSaveOptions`. Dengan mengatur `OfficeMathExportMode` ke `LaTeX`, setiap objek Office Math diubah menjadi representasi LaTeX yang sesuai. +| Properti | Apa yang dilakukannya | Mengapa Anda membutuhkannya | +|----------|-----------------------|-----------------------------| +| `OfficeMathExportMode` | Menentukan cara Office Math dirender. Menyetelnya ke `LaTeX` mengonversi persamaan ke sintaks LaTeX. | Inilah inti **cara mengekspor latex**. | +| `PreserveTableLayout` | Ketika `true`, Aspose menambahkan spasi sehingga tabel tetap tampak seperti grid. | Memenuhi **cara mempertahankan tabel** saat Anda **mengonversi word ke txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Mengapa kami memilih pengaturan ini:** +> **Tip pro:** Jika Anda hanya membutuhkan LaTeX mentah tanpa pemformatan tabel, setel `PreserveTableLayout` ke `false`. File akan lebih kecil, tetapi Anda kehilangan petunjuk visual tabel. + +### Langkah 3: Simpan Dokumen sebagai Teks Biasa + +Sekarang kita menulis dokumen ke file `.txt` menggunakan opsi yang baru saja kita definisikan. Satu baris ini sekaligus melakukan **mengonversi word ke teks biasa**, **menyimpan docx sebagai txt**, dan tentu saja **cara mengekspor latex**. -- `OfficeMathExportMode.LaTeX` adalah satu-satunya mode yang menjamin terjemahan matematika yang akurat. -- `PreserveTableLayout` menjaga tabel tetap terlihat seperti di Word, yang berguna ketika Anda nanti menyisipkan output ke dalam lingkungan LaTeX `tabular`. -- UTF‑8 memastikan karakter seperti “α”, “β”, atau “∑” tetap utuh selama proses. +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -Jika Anda pernah perlu **convert word to latex** tanpa pembungkus teks biasa, Anda dapat beralih ke `SaveFormat.LaTeX`—hanya tip singkat untuk skenario lanjutan. +doc.Save(outputPath, saveOptions); +``` -## Langkah 3: Simpan Dokumen sebagai File Teks +Setelah pemanggilan selesai, buka `output.txt`. Anda akan melihat: -Sekarang kami menulis teks kaya LaTeX ke disk. `.txt` yang dihasilkan dapat diubah namanya menjadi `.tex` nanti, atau langsung dipipe ke kompiler LaTeX. +- Potongan LaTeX seperti `\frac{a}{b}` untuk setiap persamaan Office Math. +- Tabel yang dirender dengan karakter `|` dan `-`, mempertahankan kesejajaran kolom. +- Paragraf reguler sebagai teks biasa, siap untuk parser downstream apa pun. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Contoh Program Lengkap -// Save using the configured options -doc.Save(outputPath, txtOptions); +Menggabungkan semua langkah, berikut program mandiri yang dapat Anda kompilasi dan jalankan hari ini: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Apa yang akan Anda lihat di `output.txt`:** +**Output yang diharapkan** (kutipan): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Semua paragraf lain muncul sebagai teks biasa, sementara setiap persamaan Office Math dibungkus dalam lingkungan LaTeX `equation` `inline` jika berada dalam baris di Word). Ini memenuhi persyaratan **convert word equations latex** dengan sempurna. +Perhatikan bagaimana tabel tetap mempertahankan grid‑nya dan persamaan muncul sebagai LaTeX bersih. Itulah titik optimal ketika Anda **mengonversi word ke txt** dan tetap membutuhkan representasi yang setia dari struktur serta matematika. + +--- -## Kasus Pojok & Pertanyaan Umum +## Tips untuk Mengonversi Word ke TXT dan Mempertahankan Tabel -| Situasi | Apa yang harus dilakukan | -|-----------|--------------------------| -| **No equations in the source** | Konversi tetap berfungsi; Anda hanya akan mendapatkan teks biasa. Tidak ada kode LaTeX tambahan yang ditambahkan. | -| **Very large documents (>100 MB)** | Pertimbangkan untuk streaming output menggunakan `MemoryStream` untuk menghindari penggunaan memori yang tinggi. | -| **Unsupported Math constructs** | Aspose.Words mencakup 99 % dari Office Math. Untuk kasus pojok yang jarang, Anda mungkin perlu memproses LaTeX secara manual. | -| **Need a .tex file instead of .txt** | Ubah `outputPath` agar berakhir dengan `.tex` dan opsional atur `txtOptions.Encoding` ke `Encoding.UTF8`. | -| **Running on Linux/macOS** | Kode yang sama berfungsi—pastikan jalur file menggunakan garis miring maju atau `Path.Combine`. | +Meskipun pendekatan tiga langkah ini bekerja untuk kebanyakan kasus, proyek dunia nyata seringkali menghadirkan tantangan. Berikut saran praktis yang membuat pipeline **mengonversi word ke teks biasa** Anda lebih tangguh. -## Cara Menyimpan TXT dengan Persamaan LaTeX – Ringkasan Cepat +### Gunakan Encoding yang Konsisten -1. **Muat** .docx (`Document`). -2. **Atur** `OfficeMathExportMode = LaTeX` di `TxtSaveOptions`. -3. **Simpan** file (`doc.Save`) dengan opsi tersebut. +`TxtSaveOptions` secara default menggunakan UTF‑8, yang menangani kebanyakan karakter. Jika Anda memerlukan halaman kode lain (misalnya sistem legacy yang mengharapkan Windows‑1252), setel properti `Encoding`: -Itulah seluruh alur kerja untuk **how to save txt** file yang berisi persamaan berformat LaTeX. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -## Bonus: Mengotomatiskan Konversi untuk Banyak File +### Pangkas Spasi Berlebih -Jika Anda memiliki folder berisi banyak dokumen Word, bungkus logika di atas dalam loop sederhana: +Tabel dengan banyak kolom dapat menghasilkan baris yang panjang. Setelah menyimpan, Anda mungkin ingin memproses file untuk mengubah beberapa spasi menjadi satu tab: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Tangani Tabel Bersarang + +Jika DOCX Anda berisi tabel di dalam tabel, `PreserveTableLayout` tetap menjaga hierarki visual, tetapi indentasinya mungkin terlihat aneh. Solusi cepat adalah mengganti spasi di awal dengan penanda khusus (misalnya `>>`) sehingga parser downstream dapat mendeteksi tingkat nesting. - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +### Proses Batch Banyak File + +Ketika Anda perlu **mengonversi word ke txt** untuk puluhan dokumen, bungkus logika dalam loop: + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Sekarang Anda dapat **convert word to latex** secara massal—sempurna untuk kelompok riset yang menerima puluhan manuskrip setiap hari. +Dengan cara ini Anda dapat **menyimpan docx sebagai txt** secara massal tanpa intervensi manual. + +--- + +## Kesalahan Umum dan Cara Menghindarinya + +1. **Mode Ekspor LaTeX Hilang** – Jika Anda lupa menyetel `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, persamaan akan kembali ke teks biasa (misalnya “Equation 1”). Selalu periksa blok opsi. +2. **Tata Letak Tabel Hilang** – `PreserveTableLayout` secara default `false`. Jika output Anda terlihat seperti dinding teks, kemungkinan flag belum diaktifkan. +3. **Path File dengan Spasi** – Menggunakan string mentah (`@"C:\My Folder\input.docx"`) menghindari masalah escape. Jika tidak, Anda akan mendapat `FileNotFoundException`. +4. **Versi Tidak Cocok** – Versi Aspose.Words lama (< 21.9) tidak mendukung `OfficeMathExportMode`. Tingkatkan ke paket terbaru agar **cara mengekspor latex** berfungsi. +5. **Kesalahan Encoding untuk Karakter Non‑ASCII** – Jika Anda melihat simbol �, secara eksplisit setel `options.Encoding` ke UTF‑8 atau halaman kode yang sesuai. + +--- + +## Memperluas Solusi: Dari TXT ke Markdown atau HTML + +Kadang Anda membutuhkan lebih dari teks biasa—misalnya file Markdown yang tetap berisi blok LaTeX. `TxtSaveOptions` yang sama dapat diganti dengan `HtmlSaveOptions` atau `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Perubahan kecil ini memungkinkan Anda menghasilkan output bergaya **mengonversi word ke txt** sambil tetap mempertahankan sintaks markdown yang Anda sukai. + +--- ## Kesimpulan -Kami telah membahas **cara mengekspor LaTeX dari Word** langkah demi langkah, mendemonstrasikan **cara menyimpan txt** file yang mempertahankan setiap persamaan Office Math, dan bahkan menunjukkan cara **convert word equations latex** tanpa kehilangan keakuratan. +Kami telah menelusuri jawaban lengkap dan siap produksi untuk **cara mengekspor latex** dari dokumen Word, sekaligus menunjukkan cara **mengonversi word ke txt**, **mengonversi word ke teks biasa**, **menyimpan docx sebagai txt**, dan **cara mempertahankan tabel**. Poin pentingnya: + +- Muat DOCX dengan `Aspose.Words.Document`. +- Setel `TxtSaveOptions.OfficeMathExportMode = LaTeX` dan `PreserveTableLayout = true`. +- Panggil `doc.Save(outputPath, options)` untuk mendapatkan file teks biasa yang kaya LaTeX. -Dengan hanya beberapa baris C# dan perpustakaan Aspose.Words yang kuat, Anda dapat mengubah .docx apa pun menjadi teks siap LaTeX, siap untuk dimasukkan ke dalam makalah ilmiah, buku teks, atau pipeline penerbitan otomatis. +Cobalah pada file Anda sendiri, bereksperimen dengan penyesuaian encoding, dan jangan ragu memproses folder secara batch. Jika Anda menemui kasus khusus—tabel bersarang, karakter eksotis, atau versi Aspose lama—kembali ke bagian “Tips” dan “Kesalahan Umum” untuk perbaikan cepat. -**Langkah selanjutnya?** Coba berikan `.txt` yang dihasilkan (atau ubah namanya menjadi `.tex`) ke `pdflatex` atau `xelatex` untuk menghasilkan PDF, atau jelajahi opsi `SaveFormat.LaTeX` untuk file `.tex` langsung. Jika Anda perlu **save docx as txt** sambil mempertahankan format, coba eksperimen dengan `PreserveTableLayout` dan penanganan pemutusan baris khusus. +Siap langkah selanjutnya? Coba konversi DOCX yang sama ke Markdown, atau alirkan `.txt` yang dihasilkan ke generator situs statis yang merender LaTeX di web. Kemungkinannya tak terbatas, dan kini Anda memiliki fondasi kuat untuk alur kerja **mengonversi word ke txt** apa pun. -Ada pertanyaan tentang kasus pojok, lisensi, atau penyesuaian kinerja? Tinggalkan komentar di bawah—selamat coding! +Selamat coding, semoga LaTeX Anda selalu berhasil dikompilasi pada percobaan pertama! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/indonesian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/indonesian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..0021c8b078 --- /dev/null +++ b/words/indonesian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-01 +description: Simpan Word sebagai PDF menggunakan Aspose.Words di C#. Pelajari cara + mengonversi docx ke PDF, mendeteksi font yang hilang, dan menangani peringatan substitusi + font secara efisien. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: id +og_description: Simpan Word sebagai PDF menggunakan Aspose.Words. Tutorial langkah + demi langkah ini menunjukkan cara mengonversi docx ke PDF dan mendeteksi font yang + hilang. +og_title: Simpan Word sebagai PDF dengan Aspose.Words – Panduan Lengkap +tags: +- Aspose.Words +- C# +- PDF conversion +title: Simpan Word sebagai PDF dengan Aspose.Words – Panduan Lengkap +url: /id/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Simpan Word sebagai PDF dengan Aspose.Words – Panduan Lengkap + +Pernah perlu **save Word as PDF** secara langsung dan bertanya-tanya apakah Anda akan kehilangan font di sepanjang proses? Anda tidak sendirian—para pengembang terus-menerus berurusan dengan masalah font yang hilang saat mengonversi dokumen. Dalam panduan ini kami akan membahas solusi praktis yang tidak hanya **convert docx to pdf** tetapi juga **detect missing fonts** menggunakan peringatan substitusi font Aspose.Words. + +Kami akan membahas semuanya mulai dari menyiapkan warning collector hingga menafsirkan output, sehingga pada akhirnya Anda akan tahu persis cara **save Word as PDF** tanpa kejutan. Tanpa alat eksternal, tanpa pengaturan yang rumit—hanya kode C# bersih yang dapat Anda masukkan ke dalam proyek .NET apa pun. + +## Apa yang Anda Butuhkan + +- **Aspose.Words for .NET** (versi terbaru, misalnya 24.10) – Anda dapat mengunduhnya via NuGet (`Install-Package Aspose.Words`). +- Lingkungan pengembangan .NET (Visual Studio, Rider, atau VS Code dapat digunakan). +- File DOCX contoh yang mungkin berisi font yang tidak terpasang di mesin target. +Itu saja. Jika Anda sudah memiliki hal‑hal dasar tersebut, kami siap melanjutkan. + +## Simpan Word sebagai PDF – Ikhtisar Langkah‑per‑Langkah + +Berikut adalah program lengkap yang dapat dijalankan. Silakan salin‑tempel ke dalam proyek aplikasi konsol dan tekan **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** Ganti `YOUR_DIRECTORY` dengan path absolut atau gunakan `Path.Combine(Environment.CurrentDirectory, "input.docx")` untuk pendekatan relatif yang lebih aman. + +### Mengapa Kami Menggunakan Warning Callback + +Aspose.Words secara diam-diam menggantikan font yang hilang dengan fallback (biasanya Arial). Tanpa callback Anda tidak akan pernah tahu bahwa substitusi terjadi, yang dapat menyebabkan gangguan tata letak pada PDF yang dihasilkan. Dengan mengaitkan `IWarningCallback`, kami mendapatkan daftar yang jelas dan programatis dari setiap peristiwa font yang hilang—sempurna untuk pencatatan atau memberi tahu pengguna akhir. + +### Deteksi Font yang Hilang – Apa yang Harus Dicari + +Saat Anda menjalankan program, setiap font yang hilang akan menghasilkan baris konsol serupa dengan: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Jika daftar kosong, selamat—**save word as pdf** berhasil dengan semua font asli tetap utuh. + +## Konversi Docx ke PDF – Menyesuaikan Output + +Kadang Anda memerlukan versi PDF tertentu, kualitas gambar, atau tingkat kepatuhan tertentu. Aspose.Words memungkinkan Anda menyesuaikan objek `PdfSaveOptions` sebelum memanggil `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Mengapa ini penting:** Jika Anda menghasilkan PDF untuk arsip hukum, mengatur `PdfA1b` memastikan file memenuhi standar ketat. Konversi yang sama tetap menghormati warning callback kami, sehingga Anda tetap **detect missing fonts**. + +## Substitusi Font Aspose Words – Menangani Kasus Tepi + +### Skenario 1: Banyak Font yang Hilang + +Jika dokumen sumber Anda menggunakan beberapa font khusus, warning collector akan berisi satu entri per font. Anda dapat menggabungkannya: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Skenario 2: Menyediakan Direktori Font Fallback + +Aspose.Words dapat mencari folder tambahan untuk font. Atur properti `FontsFolder` pada `FontSettings` sebelum memuat dokumen: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Sekarang perpustakaan akan mencoba folder khusus Anda terlebih dahulu, mengurangi kemungkinan substitusi yang tidak diinginkan. + +### Skenario 3: Mengabaikan Substitusi + +Jika Anda lebih suka konversi gagal ketika font hilang (daripada menggantinya secara diam-diam), lemparkan pengecualian di dalam callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Ini memaksa Anda menangani font yang hilang sebelum melanjutkan—berguna dalam pipeline CI di mana kegagalan diam tidak dapat diterima. + +## Contoh End‑to‑End Lengkap + +Menggabungkan semuanya, berikut versi ringkas yang menunjukkan **how to convert Word to PDF**, mengatur opsi PDF khusus, dan mencatat masalah font apa pun: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Output konsol yang diharapkan** (jika Calibri tidak ada): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Jika tidak ada peringatan yang muncul, operasi **save word as pdf** Anda menggunakan font yang persis sama dengan DOCX sumber. + +## Ringkasan Visual + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Image alt text:* **save word as pdf** workflow yang menunjukkan pemuatan, pengumpulan peringatan, dan output PDF. + +## Pertanyaan Umum & Jawaban + +| Question | Answer | +|----------|--------| +| **Apakah saya memerlukan lisensi untuk Aspose.Words?** | Lisensi evaluasi gratis dapat digunakan untuk pengujian, tetapi penggunaan produksi memerlukan lisensi berbayar untuk menghapus watermark evaluasi. | +| **Apakah ini akan bekerja di .NET Core / .NET 6+?** | Tentu saja—Aspose.Words menargetkan .NET Standard 2.0, sehingga semua runtime .NET terbaru kompatibel. | +| **Bisakah saya mengonversi banyak file DOCX dalam loop?** | Ya, cukup buat instance `Document` baru untuk setiap file dan gunakan kembali `WarningInfoCollector` yang sama jika Anda menginginkan hasil agregat. | +| **Bagaimana jika folder output tidak ada?** | `Document.Save` akan melempar `DirectoryNotFoundException`. Buat folder terlebih dahulu atau gunakan `Directory.CreateDirectory`. | +| **Apakah ada cara untuk menyematkan font yang hilang ke dalam PDF?** | Aspose.Words dapat menyematkan font secara otomatis jika tersedia di mesin; atur `PdfSaveOptions.EmbedFullFonts = true`. | + +## Kesimpulan + +Anda kini memiliki pola yang solid dan siap produksi untuk **save Word as PDF** sambil **detecting missing fonts** dan menangani skenario **Aspose.Words font substitution**. Dengan menambahkan warning callback, menyesuaikan folder font, dan secara opsional menyesuaikan `PdfSaveOptions`, Anda dapat dengan andal **convert docx to pdf** dan memberi tahu pengguna tentang masalah font apa pun yang mungkin memengaruhi kesetiaan tata letak. + +Siap untuk langkah selanjutnya? Cobalah menghasilkan PDF dari beberapa dokumen secara paralel, atau jelajahi penambahan watermark dan tanda tangan digital—keduanya merupakan ekstensi sederhana dari kode yang baru saja Anda kuasai. Selamat coding, semoga PDF Anda selalu terlihat persis seperti yang diharapkan! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-loadoptions/_index.md b/words/indonesian/net/programming-with-loadoptions/_index.md index bb7defda2d..8abc00195f 100644 --- a/words/indonesian/net/programming-with-loadoptions/_index.md +++ b/words/indonesian/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Cara Memulihkan DOCX – Mengatur Mode Pemulihan & Membuka File Word yang Rusak](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Pelajari cara memulihkan file DOCX dengan mengatur mode pemulihan dan membuka file Word yang rusak menggunakan Aspose.Words. | | [Cara Menggunakan LoadOptions di Aspose.Words – Panduan Lengkap](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Panduan lengkap untuk menggunakan LoadOptions dalam Aspose.Words, termasuk contoh kode dan tips konfigurasi. | | [Pulihkan Dokumen Rusak di C# – Atur Mode Pemulihan & Tampilkan Prompt Pengguna](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) Pelajari cara memulihkan dokumen yang rusak menggunakan Aspose.Words di C# dengan mengatur mode pemulihan dan menampilkan prompt kepada pengguna. | +| [Pulihkan docx yang rusak – Panduan Lengkap Memuat File Word Rusak di C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Pelajari cara memulihkan dan memuat file DOCX yang rusak menggunakan Aspose.Words dalam C# dengan panduan langkah demi langkah. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/indonesian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..0e42abcb9f --- /dev/null +++ b/words/indonesian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-05-01 +description: Pulihkan file docx yang rusak dengan cepat menggunakan Aspose.Words. + Pelajari cara mengatur mode pemulihan, memuat docx dengan aman, dan membaca file + Word yang rusak dalam beberapa langkah saja. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: id +og_description: Pulihkan file docx yang rusak di C#. Atur mode pemulihan, muat docx + dengan aman, dan baca file Word yang rusak dengan Aspose.Words. +og_title: Pulihkan docx yang rusak – Panduan C# Cepat +tags: +- Aspose.Words +- C# +- Document Recovery +title: Pulihkan docx yang rusak – Panduan Lengkap Memuat File Word yang Rusak di C# +url: /id/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pulihkan docx yang rusak – Panduan Cepat C# + +Pernahkah Anda mencoba membuka file Word yang tidak mau dimuat dan bertanya-tanya apakah isinya hilang selamanya? Dalam banyak proyek dunia nyata Anda akan **recover corrupted docx** file tanpa meminta pengguna mengirim ulang lampiran. Kabar baiknya, Aspose.Words membuatnya sangat mudah: Anda cukup mengatur mode pemulihan dan membiarkan perpustakaan melakukan pekerjaan berat. + +Dalam tutorial ini kami akan menjelaskan langkah‑langkah tepat untuk **recover corrupted docx** file, menjelaskan mengapa opsi `RecoveryMode.AutoRecover` adalah pilihan paling aman, dan menunjukkan cara **how to load docx** file yang mungkin sebagian rusak. Pada akhir tutorial Anda akan dapat membaca file Word yang rusak, mengekstrak teks yang masih ada, dan bahkan mencatat format asli untuk audit di masa mendatang. Tanpa alat eksternal, hanya kode C# bersih. + +## Apa yang Anda Butuhkan + +- **Aspose.Words for .NET** (versi terbaru apa pun; API yang kami gunakan bekerja dengan 23.5 dan lebih baru). +- Lingkungan pengembangan .NET (Visual Studio, VS Code, atau Rider). +- File `.docx` yang rusak atau sebagian rusak yang ingin Anda selamatkan. + +Tidak memerlukan izin khusus, tidak ada interop COM, dan tidak perlu menginstal Microsoft Office di server. Sederhana, kan? + +## Langkah 1: Atur Mode Pemulihan ke Auto‑Recover + +Ketika file Word rusak, perilaku pemuatan default akan melempar pengecualian dan menghentikan proses. Dengan mengonfigurasi objek `LoadOptions` Anda memberi tahu Aspose.Words untuk **set recovery mode** ke `AutoRecover`, yang memindai paket zip, melewati bagian yang tidak dapat dibaca, dan mengembalikan apa pun yang dapat disatukan. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Mengapa AutoRecover?** +> Ia berusaha membaca sebanyak mungkin sambil menjaga objek dokumen tetap dapat digunakan. Jika Anda memilih `RecoveryMode.NoRecovery`, pemuatan akan gagal pada korupsi pertama, yang mengalahkan tujuan skenario **recover corrupted docx**. + +## Langkah 2: Muat Dokumen dengan Opsi yang Dikonfigurasi + +Setelah mode pemulihan diatur, Anda dapat dengan aman mencoba membuka file tersebut. Ganti `"YOUR_DIRECTORY/input.docx"` dengan jalur sebenarnya ke file yang rusak. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Jika file hanya sebagian rusak, instance `Document` tetap akan dibuat. Anda dapat memeriksa `document.IsStructureValid` nanti jika memerlukan validasi tambahan. + +## Langkah 3: Verifikasi Format yang Terdeteksi + +Aspose.Words secara otomatis mendeteksi format asli (DOC, DOCX, ODT, dll.). Mencetak nilai ini membantu Anda memastikan bahwa perpustakaan mengenali file dengan benar, yang merupakan pemeriksaan cepat setelah operasi **recover corrupted docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Output tipikal: + +``` +Loaded with Docx format. +``` + +Bahkan jika beberapa bagian hilang, deteksi format tetap berhasil—keuntungan lain untuk alur kerja **recover corrupted docx**. + +## Langkah 4: Ekstrak Apa yang Bisa Anda Dapatkan + +Setelah dokumen dimuat, Anda dapat memperlakukannya seperti file Word yang sehat. Di bawah ini contoh ringkas yang mengekstrak teks biasa dan menuliskannya ke konsol. Ini menunjukkan bahwa Anda dapat **read damaged word file** konten tanpa crash. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Jika file asli memiliki tabel atau gambar yang rusak, mereka akan diabaikan dari output teks. Sisanya tetap utuh. + +## Langkah 5: Simpan Salinan Bersih (Opsional) + +Seringkali Anda ingin memberikan pengguna versi baru yang bersih dari file setelah pemulihan. Menyimpan dengan format yang sama memastikan kompatibilitas dengan proses hilir manapun. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Sekarang Anda memiliki file **recover damaged docx** yang dapat Anda lampirkan ke email atau kirim ke layanan lain dengan aman. + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut program lengkap yang siap dijalankan. Tempelkan ke proyek konsol baru, sesuaikan jalur file, dan tekan F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Output yang diharapkan** (asumsi file berisi satu paragraf “Hello world!” dan beberapa XML yang rusak): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Perhatikan bagaimana program tidak pernah crash—meskipun file sumber sebagian rusak. Itulah inti dari **recover corrupted docx** menggunakan Aspose.Words. + +## Pertanyaan Umum & Kasus Tepi + +### Bagaimana jika file tidak dapat dibaca sama sekali? + +Bahkan `AutoRecover` memiliki batas. Jika kontainer zip itu sendiri rusak parah, Aspose.Words akan melempar `CorruptedFileException`. Dalam kasus itu Anda mungkin memerlukan alat perbaikan zip pihak ketiga sebelum mencoba **recover corrupted docx** lagi. + +### Bisakah saya memulihkan format lain (mis., `.doc`, `.odt`)? + +Tentu saja. `LoadOptions` yang sama bekerja untuk format apa pun yang didukung Aspose.Words. Cukup ubah ekstensi file dan perpustakaan akan mendeteksi format asli secara otomatis. Ini berarti Anda juga dapat **recover damaged docx**‑like file seperti `.doc` atau `.rtf` dengan kode yang sama. + +### Bagaimana cara menangani dokumen besar tanpa memuat semuanya ke memori? + +Untuk file berukuran gigabyte, Anda dapat mengaktifkan **load options** seperti `LoadOptions.LoadFormat` atau men-stream dokumen halaman per halaman. Namun, algoritma pemulihan tetap harus membaca seluruh paket, jadi harapkan penggunaan memori yang lebih tinggi untuk file yang sangat besar dan rusak. + +### Apakah ada cara untuk mengetahui bagian mana yang hilang? + +Setelah memuat, Anda dapat memeriksa `document.GetChildNodes(NodeType.Any, true)` dan membandingkan jumlahnya dengan baseline yang diharapkan. Tabel, gambar, atau header yang hilang akan sederhana tidak ada dalam koleksi node. Ini memungkinkan Anda mencatat secara tepat apa yang **recover damaged docx** dan memberi tahu pengguna. + +## Tips Pro untuk Pemulihan yang Andal + +- **Validasi ukuran file input** sebelum memuat; file berukuran nol byte akan selalu gagal. +- **Catat hasil `RecoveryMode`** dengan menangkap `DocumentLoadingException` dan menyimpan pesan pengecualian; biasanya berisi petunjuk tentang bagian mana yang dilewati. +- **Jalankan pemulihan pada thread latar belakang** jika Anda memproses unggahan di layanan web—ini menjaga responsivitas permintaan. +- **Gabungkan dengan checksum** (mis., MD5) untuk mendeteksi apakah file yang dipulihkan berbeda dari yang asli; Anda kemudian dapat memutuskan apakah menyimpan kedua versi. + +## Kesimpulan + +Kami baru saja menunjukkan cara **recover corrupted docx** file di C# dengan **setting recovery mode** ke `AutoRecover`, memuat dokumen dengan aman, mengekstrak teks yang masih ada, dan secara opsional menyimpan salinan bersih. Pendekatan ini memungkinkan Anda **how to load docx** file yang sebaliknya akan melempar pengecualian, dan memberi Anda cara andal untuk **read damaged word file** konten tanpa alat eksternal. + +Langkah selanjutnya? Coba ganti `RecoveryMode.AutoRecover` dengan `RecoveryMode.NoRecovery` untuk melihat perbedaannya, atau bereksperimen dengan properti `LoadOptions` yang mengontrol penanganan kata sandi dan substitusi font. Anda juga dapat mengintegrasikan rutin pemulihan ke dalam API ASP.NET Core yang menerima unggahan dan mengembalikan file yang diperbaiki—sempurna untuk pipeline manajemen dokumen perusahaan. + +Ada pertanyaan lebih lanjut tentang pemulihan dokumen Word, atau ingin melihat cara **recover damaged docx** file dengan callback khusus? Tinggalkan komentar di bawah, dan selamat coding! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-markdownsaveoptions/_index.md b/words/indonesian/net/programming-with-markdownsaveoptions/_index.md index 469155f3a2..c0330720e4 100644 --- a/words/indonesian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/indonesian/net/programming-with-markdownsaveoptions/_index.md @@ -59,6 +59,8 @@ Pelajari cara mengonversi file DOCX menjadi Markdown menggunakan Aspose.Words de Pelajari cara mengekspor gambar dari dokumen Word saat mengonversinya ke format Markdown menggunakan Aspose.Words. ### [Konversi Word ke Markdown dalam C# – Panduan Lengkap dengan Ekstraksi Gambar](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) Pelajari cara mengonversi dokumen Word ke Markdown dengan ekstraksi gambar lengkap menggunakan C#. +### [Simpan docx sebagai markdown – Ekspor Matematika Word ke LaTeX dengan Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) +Pelajari cara mengekspor persamaan matematika Word ke LaTeX saat menyimpan docx sebagai markdown menggunakan Aspose.Words. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/indonesian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..49a7342a19 --- /dev/null +++ b/words/indonesian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: simpan docx sebagai markdown menggunakan Aspose.Words – pelajari cara + mengonversi Word ke markdown, mengekspor persamaan ke LaTeX, dan mengatur resolusi + gambar markdown dalam satu alur kerja yang mulus. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: id +og_description: simpan docx sebagai markdown dengan Aspose.Words. tutorial ini menunjukkan + cara mengonversi word ke markdown, mengekspor persamaan ke latex, dan mengatur resolusi + gambar markdown. +og_title: Simpan docx sebagai markdown – Panduan Lengkap Mengekspor Matematika Word + ke LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Simpan docx sebagai markdown – Ekspor Matematika Word ke LaTeX dengan Aspose.Words +url: /id/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# simpan docx sebagai markdown – Export Word Math to LaTeX with Aspose.Words + +Pernah membutuhkan untuk **save docx as markdown** tetapi terhambat bagaimana menjaga persamaan Office Math tetap tajam? Anda bukan satu-satunya. Kebanyakan pengembang menemui kendala ketika konversi default mengubah persamaan menjadi gambar buram, memaksa penulisan ulang manual dalam LaTeX. + +Kabar baik: Aspose.Words dapat melakukan pekerjaan berat untuk Anda. Dalam tutorial ini kami akan **convert word to markdown**, memberi tahu engine untuk **export equations to latex**, dan bahkan **set markdown image resolution** untuk sisa dokumen. Pada akhir tutorial Anda akan memiliki satu perintah yang menghasilkan file `.md` bersih dengan matematika siap LaTeX dan gambar beresolusi tinggi. + +## Apa yang Akan Anda Pelajari + +- Cara memuat `.docx` yang berisi objek Office Math. +- Properti `MarkdownSaveOptions` mana yang mengontrol **export equations to latex** dan **set markdown image resolution**. +- Cuplikan C# lengkap yang dapat dijalankan dan dapat Anda tempelkan ke proyek .NET apa pun. +- Tips untuk memecahkan masalah umum, seperti font yang hilang atau fitur persamaan yang tidak didukung. + +**Prerequisites**: .NET 6+ (atau .NET Framework 4.6+), lisensi untuk Aspose.Words for .NET, dan pemahaman dasar tentang C#. Jika Anda nyaman membuat aplikasi console, Anda siap memulai. + +--- + +## Langkah 1 – Save docx as markdown: Muat File Word Anda + +Hal pertama yang kita butuhkan adalah objek `Document` yang menunjuk ke sumber `.docx`. Anggap saja seperti membuka buku sebelum Anda mulai menyalin bab. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Mengapa ini penting*: Jika dokumen tidak mengandung matematika apa pun, langkah **export equations to latex** tidak akan melakukan apa-apa, tetapi sisanya tetap dijalankan. Pemeriksaan ini menyelamatkan Anda dari kebingungan mengapa output Markdown Anda tidak memiliki blok LaTeX. + +## Langkah 2 – Konfigurasi Export Equations to LaTeX + +Aspose.Words memungkinkan Anda menentukan bagaimana Office Math harus dirender. Secara default, ia mengubahnya menjadi gambar PNG, yang menyebabkan banyak tutorial menghasilkan file markdown yang berbutir. Mengubah `OfficeMathExportMode` menjadi `LaTeX` memberikan Anda persamaan yang bersih dan siap disalin. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Mengapa `OfficeMathExportMode.LaTeX`?* LaTeX adalah bahasa universal penerbitan ilmiah. Ketika Anda kemudian merender markdown dengan generator situs statis atau notebook Jupyter, persamaan akan tampak tajam pada tingkat zoom apa pun. + +## Langkah 3 – Set Markdown Image Resolution (untuk Konten Non‑Math) + +Meskipun kami fokus pada matematika, kebanyakan dokumen Word juga berisi gambar, diagram, atau SVG yang disematkan. Properti `ImageResolution` mengontrol bagaimana Aspose.Words meraster aset-aset tersebut. Nilai **300 DPI** merupakan titik optimal untuk layar dan cetak. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Tips pro*: Jika markdown Anda hanya akan ditampilkan di web, Anda dapat menurunkannya menjadi 150 DPI untuk mengurangi ukuran file. Sebaliknya, untuk PDF siap cetak, naikkan menjadi 600 DPI. + +## Langkah 4 – Jalankan Konversi – Convert Word Math LaTeX + +Setelah semuanya dikonfigurasi, konversi sebenarnya hanya satu baris. Aspose.Words melakukan pekerjaan berat di balik layar. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: Buka file `.md` yang dihasilkan dan Anda akan melihat sesuatu seperti: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Perhatikan blok LaTeX (`$...$` dan `$$...$$`) yang menggantikan potongan PNG sebelumnya. Gambar di bagian bawah masih berupa PNG, dirender pada 300 DPI seperti yang kami minta. + +## Langkah 5 – Kasus Pinggiran Umum & Cara Menanganinya + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (mis., Cambria Math tidak terpasang) | Output LaTeX mungkin berisi simbol yang tidak dikenal. | Instal font yang hilang di server atau sematkan dalam dokumen sebelum konversi. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words mungkin kembali ke gambar meskipun dalam mode `LaTeX`. | Upgrade ke versi terbaru Aspose.Words; perpustakaan terus meningkatkan cakupan persamaan. | +| **Large documents** ( > 50 MB ) | Tekanan memori dapat menyebabkan `OutOfMemoryException`. | Gunakan `LoadOptions` dengan `LoadFormat.Docx` dan alirkan file, atau bagi dokumen menjadi beberapa bagian sebelum konversi. | +| **Image size too big** | File Markdown menjadi sangat besar, memperlambat proses build situs statis. | Kurangi `ImageResolution` menjadi 150 DPI untuk skenario hanya web (lihat Langkah 3). | + +## Langkah 6 – Gabungkan Semua: Contoh Lengkap yang Berfungsi + +Berikut adalah program *lengkap* console‑app yang dapat Anda salin‑tempel ke `Program.cs`. Program ini mencakup semua bagian yang kami bahas, plus sedikit penanganan error tambahan. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Jalankan program (`dotnet run`) dan Anda akan mendapatkan file markdown yang **save docx as markdown** sambil mempertahankan setiap persamaan sebagai LaTeX. Tanpa penyalinan manual, tanpa gambar raster yang buruk untuk matematika. + +## Kesimpulan + +Kami telah membahas seluruh proses **saving docx as markdown** dengan Aspose.Words, mulai dari memuat file Word hingga mengkonfigurasi **export equations to latex** dan **set markdown image resolution**. Cuplikan akhir siap produksi, dan Anda dapat memasukkannya ke proyek .NET apa pun yang membutuhkan **convert word to markdown** secara langsung. + +Apa selanjutnya? Cobalah memasukkan `.md` yang dihasilkan ke generator situs statis seperti Hugo atau Jekyll dan saksikan persamaan Anda dirender dengan indah. Jika Anda perlu **convert word math latex** ke format lain (PDF, HTML), cukup ganti `MarkdownSaveOptions` dengan `PdfSaveOptions` atau `HtmlSaveOptions`—flag `OfficeMathExportMode` yang sama berfungsi di semua format. + +Memiliki variasi dalam alur kerja, seperti mengambil file Word dari Azure Blob storage atau mengalirkannya dari API? Pola yang sama berlaku; cukup ganti konstruktor `Document` berbasis file‑system dengan yang berbasis stream. + +Silakan bereksperimen, dan beri tahu kami di komentar bagaimana pendekatan ini menyelesaikan masalah konversi Anda. Selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-pdfsaveoptions/_index.md b/words/indonesian/net/programming-with-pdfsaveoptions/_index.md index a774df41f0..c94970a0b8 100644 --- a/words/indonesian/net/programming-with-pdfsaveoptions/_index.md +++ b/words/indonesian/net/programming-with-pdfsaveoptions/_index.md @@ -44,33 +44,34 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Kompresi Gambar dalam Dokumen PDF](./image-compression/) Pelajari cara mengompres gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk mengoptimalkan ukuran dan kualitas file. Bahasa Indonesia: | [Perbarui Properti Terakhir Dicetak dalam Dokumen PDF](./update-last-printed-property/) | Pelajari cara memperbarui properti cetak terakhir dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Bahasa Indonesia: | [Render 3D DML 3D Effects dalam Dokumen PDF](./dml-3deffects-rendering/) | Pelajari cara membuat efek DML 3D yang menakjubkan dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah yang komprehensif ini. Bahasa Indonesia: -| [Interpolasi Gambar dalam Dokumen PDF](./interpolate-images/) | Pelajari cara menginterpolasi gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Tingkatkan kualitas gambar PDF Anda dengan mudah. | -| [Buat PDF Aksesibel dari Word dengan C# – Panduan Langkah‑per‑Langkah](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Pelajari cara membuat PDF yang dapat diakses dari dokumen Word menggunakan Aspose.Words untuk .NET dengan C# dalam panduan langkah demi langkah ini. Bahasa Indonesia: | +| [Interpolasi Gambar dalam Dokumen PDF](./interpolate-images/) | Pelajari cara menginterpolasi gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Tingkatkan kualitas gambar PDF Anda dengan mudah. Bahasa Indonesia: +| [Buat PDF Aksesibel dari Word dengan C# – Panduan Langkah‑per‑Langkah](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Pelajari cara membuat PDF yang dapat diakses dari dokumen Word menggunakan Aspose.Words untuk .NET dengan C# dalam panduan langkah demi langkah ini. Bahasa Indonesia: | [Simpan docx sebagai PDF dengan Aspose.Words – Panduan Lengkap C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Panduan lengkap langkah demi langkah untuk menyimpan file DOCX menjadi PDF menggunakan Aspose.Words dengan C#. | | [Buat PDF Aksesibel di C# – Tutorial Aksesibilitas PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Pelajari cara membuat PDF yang dapat diakses menggunakan Aspose.Words untuk .NET dengan C#, termasuk menambahkan tag struktural dan teks alternatif. | -| [Menampilkan Judul Dokumen di Bilah Judul Jendela](./display-doc-title-in-window-titlebar/) | Pelajari cara menampilkan judul dokumen di bilah judul jendela PDF Anda menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah ini. Bahasa Indonesia: | -| [Peringatan Render Pdf](./pdf-render-warnings/) | Panduan langkah demi langkah untuk menangani peringatan rendering PDF dengan Aspose.Words untuk .NET. Bahasa Indonesia: | -| [Tambahkan Tanda Tangan Digital ke PDF menggunakan Pemegang Sertifikat](./digitally-signed-pdf-using-certificate-holder/) | Amankan berkas PDF Anda dengan tanda tangan digital menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah ini untuk menambahkan tanda tangan digital ke PDF Anda dengan mudah. Bahasa Indonesia: | -| [Sematkan Font dalam Dokumen PDF](./embedded-all-fonts/) | Sematkan font dalam dokumen PDF dengan mudah menggunakan Aspose.Words untuk .NET dengan panduan terperinci dan langkah demi langkah ini. Pastikan tampilan konsisten di semua perangkat. Bahasa Indonesia: | -| [Sematkan Subset Font dalam Dokumen PDF](./embedded-subset-fonts/) Kurangi ukuran file PDF dengan hanya menyematkan subset font yang diperlukan menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan PDF Anda secara efisien. Bahasa Indonesia: | -| [Kurangi Ukuran PDF dengan Menonaktifkan Font yang Disematkan](./disable-embed-windows-fonts/) | Kurangi ukuran PDF dengan menonaktifkan font yang disematkan menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan dokumen Anda agar dapat disimpan dan dibagikan secara efisien. Bahasa Indonesia: | -| [Optimalkan Ukuran PDF dengan Melewati Font Arial & Times Roman yang Tertanam](./skip-embedded-arial-and-times-roman-fonts/) | Optimalkan ukuran PDF dengan melewati font Arial dan Times Roman yang tertanam menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah ini untuk menyederhanakan file PDF Anda. Bahasa Indonesia: | -| [Kurangi Ukuran File PDF dengan Tidak Menyertakan Font Inti](./avoid-embedding-core-fonts/) | Pelajari cara mengurangi ukuran file PDF dengan tidak menyematkan font inti menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan PDF Anda. Bahasa Indonesia: | -| [Escape URI dalam Dokumen PDF](./escape-uri/) Pelajari cara meloloskan URI dalam PDF menggunakan Aspose.Words untuk .NET. Panduan terperinci ini memandu Anda melalui proses tersebut langkah demi langkah. Bahasa Indonesia: | -| [Ekspor Penanda Header dan Footer Dokumen Word ke Dokumen PDF](./export-header-footer-bookmarks/) | Pelajari cara mengekspor penanda header dan footer dari dokumen Word ke PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Bahasa Indonesia: | -| [Kurangi Ukuran PDF dengan Mengubah Font Wmf Menjadi Ukuran Metafile](./scale-wmf-fonts-to-metafile-size/) | Panduan langkah demi langkah untuk mengurangi ukuran pdf dengan skala font wmf ke ukuran metafile saat mengonversi ke PDF dengan Aspose.Words untuk .NET. Bahasa Indonesia: | -| [Meningkatkan Penempatan Teks PDF dengan Penempatan Teks Tambahan](./additional-text-positioning/) | Pelajari cara meningkatkan posisi teks PDF dengan Aspose.Words untuk .NET dalam beberapa langkah mudah. Tingkatkan tampilan dokumen Anda. Bahasa Indonesia: | -| [Konversi Dokumen Word ke PDF 1.7](./conversion-to-pdf-17/) | Ubah dokumen Word ke PDF 1.7 dengan mudah menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk memastikan dokumen Anda dapat diakses secara universal dan diformat secara profesional. Bahasa Indonesia: | -| [Kurangi Ukuran Dokumen PDF dengan Downsampling Gambar](./downsampling-images/) | Kurangi ukuran dokumen PDF dengan melakukan downsampling gambar menggunakan Aspose.Words untuk .NET. Optimalkan PDF Anda untuk waktu unggah dan unduh yang lebih cepat. Bahasa Indonesia: | -| [Mengatur Opsi Kerangka dalam Dokumen PDF](./set-outline-options/) | Pelajari cara mengatur opsi kerangka dalam dokumen PDF menggunakan Aspose.Words untuk .NET. Tingkatkan navigasi PDF dengan mengonfigurasi level judul dan kerangka yang diperluas. Bahasa Indonesia: | -| [Ekspor Properti Kustom dalam Dokumen PDF](./custom-properties-export/) | Pelajari cara mengekspor properti kustom dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah terperinci kami. Bahasa Indonesia: | -| [Ekspor Struktur Dokumen Word ke Dokumen PDF](./export-document-structure/) | Ekspor struktur dokumen Word ke PDF dengan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mempertahankan tata letak dokumen dan meningkatkan navigasi PDF. Bahasa Indonesia: | -| [Kompresi Gambar dalam Dokumen PDF](./image-compression/) Pelajari cara mengompres gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk mengoptimalkan ukuran dan kualitas file. Bahasa Indonesia: | -| [Perbarui Properti Terakhir Dicetak dalam Dokumen PDF](./update-last-printed-property/) | Pelajari cara memperbarui properti cetak terakhir dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Bahasa Indonesia: | -| [Render 3D DML 3D Effects dalam Dokumen PDF](./dml-3deffects-rendering/) | Pelajari cara membuat efek DML 3D yang menakjubkan dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah yang komprehensif ini. Bahasa Indonesia: | -| [Interpolasi Gambar dalam Dokumen PDF](./interpolate-images/) | Pelajari cara menginterpolasi gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Tingkatkan kualitas gambar PDF Anda dengan mudah. Bahasa Indonesia: | -| [Buat PDF Aksesibel dari Word – Panduan Lengkap](./create-accessible-pdf-from-word-complete-guide/) | Panduan lengkap untuk membuat PDF yang dapat diakses dari dokumen Word menggunakan Aspose.Words untuk .NET. Bahasa Indonesia: | +| [Menampilkan Judul Dokumen di Bilah Judul Jendela](./display-doc-title-in-window-titlebar/) | Pelajari cara menampilkan judul dokumen di bilah judul jendela PDF Anda menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah ini. Bahasa Indonesia: +| [Peringatan Render Pdf](./pdf-render-warnings/) | Panduan langkah demi langkah untuk menangani peringatan rendering PDF dengan Aspose.Words untuk .NET. Bahasa Indonesia: +| [Tambahkan Tanda Tangan Digital ke PDF menggunakan Pemegang Sertifikat](./digitally-signed-pdf-using-certificate-holder/) | Amankan berkas PDF Anda dengan tanda tangan digital menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah ini untuk menambahkan tanda tangan digital ke PDF Anda dengan mudah. Bahasa Indonesia: +| [Sematkan Font dalam Dokumen PDF](./embedded-all-fonts/) | Sematkan font dalam dokumen PDF dengan mudah menggunakan Aspose.Words untuk .NET dengan panduan terperinci dan langkah demi langkah ini. Pastikan tampilan konsisten di semua perangkat. Bahasa Indonesia: +| [Sematkan Subset Font dalam Dokumen PDF](./embedded-subset-fonts/) Kurangi ukuran file PDF dengan hanya menyematkan subset font yang diperlukan menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan PDF Anda secara efisien. Bahasa Indonesia: +| [Kurangi Ukuran PDF dengan Menonaktifkan Font yang Disematkan](./disable-embed-windows-fonts/) | Kurangi ukuran PDF dengan menonaktifkan font yang disematkan menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan dokumen Anda agar dapat disimpan dan dibagikan secara efisien. Bahasa Indonesia: +| [Optimalkan Ukuran PDF dengan Melewati Font Arial & Times Roman yang Tertanam](./skip-embedded-arial-and-times-roman-fonts/) | Optimalkan ukuran PDF dengan melewati font Arial dan Times Roman yang tertanam menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah ini untuk menyederhanakan file PDF Anda. Bahasa Indonesia: +| [Kurangi Ukuran File PDF dengan Tidak Menyertakan Font Inti](./avoid-embedding-core-fonts/) | Pelajari cara mengurangi ukuran file PDF dengan tidak menyematkan font inti menggunakan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mengoptimalkan PDF Anda. Bahasa Indonesia: +| [Escape URI dalam Dokumen PDF](./escape-uri/) Pelajari cara meloloskan URI dalam PDF menggunakan Aspose.Words untuk .NET. Panduan terperinci ini memandu Anda melalui proses tersebut langkah demi langkah. Bahasa Indonesia: +| [Ekspor Penanda Header dan Footer Dokumen Word ke Dokumen PDF](./export-header-footer-bookmarks/) | Pelajari cara mengekspor penanda header dan footer dari dokumen Word ke PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Bahasa Indonesia: +| [Kurangi Ukuran PDF dengan Mengubah Font Wmf Menjadi Ukuran Metafile](./scale-wmf-fonts-to-metafile-size/) | Panduan langkah demi langkah untuk mengurangi ukuran pdf dengan skala font wmf ke ukuran metafile saat mengonversi ke PDF dengan Aspose.Words untuk .NET. Bahasa Indonesia: +| [Meningkatkan Penempatan Teks PDF dengan Penempatan Teks Tambahan](./additional-text-positioning/) | Pelajari cara meningkatkan posisi teks PDF dengan Aspose.Words untuk .NET dalam beberapa langkah mudah. Tingkatkan tampilan dokumen Anda. Bahasa Indonesia: +| [Konversi Dokumen Word ke PDF 1.7](./conversion-to-pdf-17/) | Ubah dokumen Word ke PDF 1.7 dengan mudah menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk memastikan dokumen Anda dapat diakses secara universal dan diformat secara profesional. Bahasa Indonesia: +| [Kurangi Ukuran Dokumen PDF dengan Downsampling Gambar](./downsampling-images/) | Kurangi ukuran dokumen PDF dengan melakukan downsampling gambar menggunakan Aspose.Words untuk .NET. Optimalkan PDF Anda untuk waktu unggah dan unduh yang lebih cepat. Bahasa Indonesia: +| [Mengatur Opsi Kerangka dalam Dokumen PDF](./set-outline-options/) | Pelajari cara mengatur opsi kerangka dalam dokumen PDF menggunakan Aspose.Words untuk .NET. Tingkatkan navigasi PDF dengan mengonfigurasi level judul dan kerangka yang diperluas. Bahasa Indonesia: +| [Ekspor Properti Kustom dalam Dokumen PDF](./custom-properties-export/) | Pelajari cara mengekspor properti kustom dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah terperinci kami. Bahasa Indonesia: +| [Ekspor Struktur Dokumen Word ke Dokumen PDF](./export-document-structure/) | Ekspor struktur dokumen Word ke PDF dengan Aspose.Words untuk .NET. Ikuti panduan langkah demi langkah kami untuk mempertahankan tata letak dokumen dan meningkatkan navigasi PDF. Bahasa Indonesia: +| [Kompresi Gambar dalam Dokumen PDF](./image-compression/) Pelajari cara mengompres gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk mengoptimalkan ukuran dan kualitas file. Bahasa Indonesia: +| [Perbarui Properti Terakhir Dicetak dalam Dokumen PDF](./update-last-printed-property/) | Pelajari cara memperbarui properti cetak terakhir dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Bahasa Indonesia: +| [Render 3D DML 3D Effects dalam Dokumen PDF](./dml-3deffects-rendering/) | Pelajari cara membuat efek DML 3D yang menakjubkan dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah yang komprehensif ini. Bahasa Indonesia: +| [Interpolasi Gambar dalam Dokumen PDF](./interpolate-images/) | Pelajari cara menginterpolasi gambar dalam dokumen PDF menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah kami. Tingkatkan kualitas gambar PDF Anda dengan mudah. Bahasa Indonesia: +| [Buat PDF Aksesibel dari Word – Panduan Lengkap](./create-accessible-pdf-from-word-complete-guide/) | Panduan lengkap untuk membuat PDF yang dapat diakses dari dokumen Word menggunakan Aspose.Words untuk .NET. Bahasa Indonesia: | [Buat PDF yang Aksesibel – Panduan Langkah-demi-Langkah untuk Kepatuhan PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Pelajari cara membuat PDF yang dapat diakses sesuai standar PDF/UA dengan panduan langkah demi langkah menggunakan Aspose.Words untuk .NET. | +| [Simpan Dokumen sebagai PDF dengan Aspose.Words – Panduan Lengkap C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Panduan lengkap langkah demi langkah untuk menyimpan dokumen sebagai PDF menggunakan Aspose.Words dengan C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/indonesian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..7c037e4d12 --- /dev/null +++ b/words/indonesian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Pelajari cara menyimpan dokumen sebagai PDF menggunakan Aspose.Words + di C#. Tutorial ini juga mencakup mengonversi Word ke PDF, mengekspor matematika + LaTeX, dan menangani font yang hilang. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: id +og_description: Simpan dokumen sebagai PDF dengan mudah menggunakan Aspose.Words. + Panduan ini juga menunjukkan cara mengonversi Word ke PDF, mengekspor matematika + LaTeX, dan menangani font yang hilang. +og_title: Simpan Dokumen sebagai PDF dengan Aspose.Words – Panduan Lengkap C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Simpan Dokumen sebagai PDF dengan Aspose.Words – Panduan Lengkap C# +url: /id/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Simpan Dokumen sebagai PDF dengan Aspose.Words – Panduan Lengkap C# + +Pernah bertanya-tanya **bagaimana cara menyimpan dokumen sebagai pdf** langsung dari file Word tanpa kehilangan fitur aksesibilitas? Anda bukan satu-satunya—para pengembang terus-menerus meminta cara yang dapat diandalkan untuk mengonversi Word ke PDF sambil mempertahankan persamaan matematika dan menangani font yang hilang dengan elegan. + +Dalam tutorial ini kami akan membahas solusi langkah‑demi‑langkah yang tidak hanya **save document as pdf** tetapi juga mendemonstrasikan **convert word to pdf**, **export math latex**, dan **handle missing fonts** menggunakan Aspose.Words untuk .NET terbaru. Pada akhir tutorial Anda akan memiliki program C# siap‑jalankan yang menghasilkan file yang mematuhi PDF/UA‑2, sempurna untuk audit aksesibilitas. + +## Apa yang Anda Butuhkan + +- .NET 6 atau lebih baru (kode ini juga berfungsi dengan .NET Core dan .NET Framework) +- Aspose.Words untuk .NET 25.10 atau yang lebih baru – Anda dapat mengambil versi percobaan gratis dari situs web Aspose +- Dokumen Word sederhana (`input.docx`) yang berisi setidaknya satu bentuk mengambang dan satu persamaan matematika (untuk melihat fitur export‑math‑latex beraksi) +- Visual Studio 2022 (atau IDE apa pun yang Anda suka) + +> **Pro tip:** Jika Anda berada di pipeline CI/CD, tambahkan paket NuGet Aspose.Words ke file proyek Anda: + +```xml + +``` + +Sekarang mari kita selami kode. + +## Langkah 1: Muat Dokumen Sumber dengan Pemulihan Otomatis + +Saat menangani file Word dunia nyata, Anda mungkin menemukan bagian yang rusak atau sumber daya yang hilang. Mengaktifkan pemulihan otomatis memastikan proses pemuatan tidak pernah melemparkan pengecualian. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Mengapa ini penting:** +`RecoveryMode.AutoRecover` melindungi pipeline Anda dari crash pada input yang tidak terformat dengan benar, yang sangat berguna ketika Anda **convert word to pdf** secara massal. + +## Langkah 2: Siapkan Opsi Penyimpanan PDF untuk Aksesibilitas Penuh + +PDF/UA‑2 adalah standar ISO untuk PDF yang dapat diakses. Dengan mengkonfigurasi beberapa flag, kami mendapatkan file yang dapat dinavigasi oleh pembaca layar, dan kami juga memastikan persamaan matematika diekspor sebagai LaTeX tersembunyi. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – memastikan PDF yang dihasilkan menghormati tata letak asli sambil tetap secara semantik benar. +- **OfficeMathExportMode.LaTeX** – memenuhi kebutuhan **export math latex**, memungkinkan alat hilir mengekstrak persamaan jika diperlukan. + +## Langkah 3: Tangkap Peringatan (misalnya, Font yang Hilang) + +Font yang hilang adalah masalah umum saat mengonversi dokumen. Aspose.Words dapat melaporkan masalah ini melalui `WarningCallback`. Kami akan mengumpulkannya sehingga Anda dapat mencatat atau menindaklanjuti nanti. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Mengapa ini penting bagi Anda:** +Jika sumber menggunakan font yang tidak terpasang di server, PDF akan kembali ke font default, yang berpotensi merusak tata letak. Dengan **handle missing fonts** kami dapat memberi peringatan kepada pengguna atau menyematkan font pengganti. + +## Langkah 4: Simpan Dokumen sebagai PDF yang Dapat Diakses + +Sekarang saatnya menguji—melakukan konversi sebenarnya. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Jika semuanya berjalan lancar, Anda akan mendapatkan file PDF/UA‑2 yang berisi LaTeX tersembunyi untuk setiap persamaan dan penandaan yang tepat untuk bentuk mengambang. + +## Langkah 5: Tinjau Peringatan yang Ditangkap (Opsional tetapi Disarankan) + +Setelah operasi penyimpanan, Anda dapat mengiterasi peringatan yang dikumpulkan dan mencatatnya. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typical output might look like: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Melihat pesan-pesan ini lebih awal membantu Anda **handle missing fonts** sebelum memengaruhi pengguna akhir. + +## Contoh Kerja Lengkap + +Menggabungkan semuanya, berikut program lengkap yang siap dijalankan. Ganti jalur placeholder dengan milik Anda. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` mematuhi PDF/UA‑2. +- Semua bentuk mengambang ditandai sebagai gambar inline. +- Setiap objek Office Math muncul sebagai LaTeX tersembunyi (terlihat saat Anda memeriksa struktur PDF). +- Semua masalah terkait font dicetak ke konsol, memberi Anda kesempatan untuk **handle missing fonts** sebelum mengirim file. + +![Diagram yang menunjukkan alur dari Word → Aspose.Words → PDF yang Dapat Diakses (save document as pdf)](conversion-diagram.png "Diagram alur untuk menyimpan dokumen sebagai pdf") + +*Teks alt gambar:* **Diagram cara menyimpan dokumen sebagai pdf menggunakan Aspose.Words** + +## Pertanyaan Umum & Kasus Tepi + +### Bagaimana jika saya menggunakan versi Aspose.Words yang lebih lama? + +`OfficeMathExportMode.LaTeX` diperkenalkan pada versi 25.10. Untuk rilis yang lebih lama Anda masih dapat **convert word to pdf**, tetapi matematika akan dirasterisasi alih-alih diekspor sebagai LaTeX. Tingkatkan versi untuk aksesibilitas terbaik. + +### Bisakah saya menyematkan font khusus untuk menghindari fallback? + +Ya. Atur `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` sebelum memanggil `Save`. Ini juga membantu **handle missing fonts** dengan memaksa PDF berisi glif yang diperlukan. + +### Bagaimana cara memverifikasi kepatuhan PDF/UA‑2? + +Buka file di Adobe Acrobat Pro → “Print Production” → “Preflight”. Pilih profil “PDF/A‑2b” atau “PDF/UA‑2”; Acrobat akan melaporkan pelanggaran apa pun. + +### Bagaimana dengan file Word yang dilindungi kata sandi? + +Muat dokumen dengan `LoadOptions` yang mencakup `Password`. Contoh: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Sisa pipeline tetap tidak berubah. + +## Kesimpulan + +Kami telah membahas semua yang Anda perlukan untuk **save document as pdf** menggunakan Aspose.Words dalam C#. Tutorial ini juga mendemonstrasikan cara **convert word to pdf**, **export math latex**, dan **handle missing fonts**—semua sambil menghasilkan file PDF/UA‑2 yang dapat diakses. + +Cobalah kode tersebut, bereksperimen dengan berbagai `PdfSaveOptions` (misalnya, kompresi gambar, PDF/A‑2b), dan integrasikan ke dalam layanan pemrosesan dokumen Anda. Jika Anda ingin melangkah lebih jauh, pertimbangkan untuk menjelajahi pustaka khusus PDF Aspose untuk pemrosesan lanjutan atau tanda tangan digital. + +Apakah ada skenario lain yang ingin Anda tangani? Jangan ragu untuk meninggalkan komentar atau melihat panduan kami lainnya tentang **PDF manipulation**, **image extraction**, dan **batch conversion**. Selamat coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-shapes/_index.md b/words/indonesian/net/programming-with-shapes/_index.md index 73176e5009..e1e6a6f0de 100644 --- a/words/indonesian/net/programming-with-shapes/_index.md +++ b/words/indonesian/net/programming-with-shapes/_index.md @@ -36,8 +36,8 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Buat Bentuk Persegi Panjang di Word dengan Aspose.Words – Panduan langkah demi langkah](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Pelajari cara membuat bentuk persegi panjang di dokumen Word menggunakan Aspose.Words dengan panduan langkah demi langkah. | | [Buat bentuk persegi panjang di Word menggunakan C# – Panduan Langkah demi Langkah](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Pelajari cara membuat bentuk persegi panjang di dokumen Word menggunakan Aspose.Words untuk .NET dengan panduan langkah demi langkah ini. | | [Tutorial Bayangan Bentuk Aspose.Words – Tambahkan Bayangan pada Bentuk Word di C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Pelajari cara menambahkan efek bayangan pada bentuk di dokumen Word menggunakan Aspose.Words untuk .NET dengan contoh kode C#. Bahasa Indonesia: | - | [Buat Dokumen Word Kosong dengan Bentuk Persegi Panjang Berbayang – Panduan Langkah demi Langkah](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Pelajari cara membuat dokumen Word kosong dan menambahkan bentuk persegi panjang berbayang dengan Aspose.Words untuk .NET secara langkah demi langkah. | +| [Cara Memindahkan Bayangan di Aspose.Words – Panduan Lengkap C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Pelajari cara memindahkan bayangan pada bentuk di dokumen Word menggunakan Aspose.Words untuk .NET dengan panduan lengkap dalam C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/indonesian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..2db6164dc0 --- /dev/null +++ b/words/indonesian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Cara memindahkan bayangan pada bentuk di Aspose.Words menggunakan C#. + Pelajari cara menambahkan bayangan ke bentuk, mengubah blur, mengatur transparansi, + dan memutar bayangan dalam hitungan menit. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: id +og_description: Cara memindahkan bayangan pada bentuk di Aspose.Words menggunakan + C#. Tutorial ini menunjukkan cara menambahkan bayangan ke bentuk, mengubah blur, + mengatur transparansi, dan memutar bayangan. +og_title: Cara Memindahkan Bayangan di Aspose.Words – Panduan Lengkap C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Cara Memindahkan Bayangan di Aspose.Words – Panduan Lengkap C# +url: /id/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Memindahkan Bayangan di Aspose.Words – Panduan Lengkap C# + +Pernah bertanya‑tanya **cara memindahkan bayangan** pada sebuah shape di dalam dokumen Word tanpa membuka Word secara manual? Dalam pekerjaan sehari‑hari saya, saya sering harus menyesuaikan bayangan shape secara programatis—baik untuk laporan yang rapi maupun templat yang dinamis. Kabar baiknya? Dengan Aspose.Words Anda dapat melakukannya dalam beberapa baris kode, dan Anda juga akan belajar **menambahkan bayangan ke shape**, **cara mengubah blur**, **cara mengatur transparansi**, serta **cara memutar bayangan** dalam satu langkah. + +Dalam tutorial ini kita akan menelusuri skenario dunia nyata: memuat file DOCX yang sudah ada dan memiliki shape, menyesuaikan posisi bayangan, kelembutan, opasitas, dan arah, lalu menyimpan hasilnya. Pada akhir tutorial Anda akan memiliki potongan kode yang dapat dipakai ulang di proyek .NET mana pun, serta memahami mengapa setiap properti penting. + +## Prasyarat – Apa yang Anda Butuhkan Sebelum Memulai + +- **Aspose.Words for .NET** (versi 23.12 atau lebih baru). Anda dapat mengunduhnya dari NuGet dengan `Install-Package Aspose.Words`. +- Lingkungan pengembangan .NET 6+ (Visual Studio, VS Code, Rider—sesuai pilihan Anda). +- File Word input (`input.docx`) yang sudah berisi setidaknya satu shape (misalnya persegi panjang, lingkaran, atau gambar). +- Familiaritas dasar dengan sintaks C#—tidak perlu hal yang rumit. + +Jika ada yang belum Anda miliki, luangkan waktu sejenak untuk menginstal pustaka tersebut; sisanya mengasumsikan paket sudah direferensikan. + +## Langkah 1: Muat Dokumen dan Dapatkan Shape Target – **Cara Memindahkan Bayangan** Dimulai Di Sini + +Hal pertama yang kita lakukan adalah memuat dokumen sumber dan menemukan shape yang ingin dimodifikasi. Aspose.Words memperlakukan setiap objek (paragraf, tabel, shape) sebagai node dalam sebuah pohon, sehingga kita dapat menanyakannya secara langsung. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Mengapa ini penting:** Memuat dokumen sekali dan menggunakan kembali instance `Document` yang sama lebih efisien. Pemanggilan `GetChild` aman karena mengembalikan `null` bila indeks di luar jangkauan, memungkinkan penanganan shape yang tidak ada dengan elegan. + +## Langkah 2: Sesuaikan Radius Blur – Menguasai **Cara Mengubah Blur** + +Bayangan yang lembut terlihat profesional, sementara tepi yang keras terasa murahan. Properti `BlurRadius` mengontrol kelembutan dalam poin (1 pt ≈ 1/72 inci). Mari naikkan menjadi 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Tips pro:** Blur default adalah 0,5 pt. Nilai di atas 5 pt biasanya terlihat, tetapi hati‑hati jangan terlalu besar—hal itu dapat membuat shape tampak terlepas dari halaman. + +## Langkah 3: Atur Transparansi – Jawaban untuk **Cara Mengatur Transparansi** + +Transparansi menentukan seberapa tembus pandang bayangan. Nilai `0` berarti sepenuhnya opak; `1` berarti benar‑benar tidak terlihat. Untuk efek halus kita gunakan `0.3` (30 % transparan). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Mengapa Anda peduli:** Jika shape berwarna gelap, bayangan yang sepenuhnya opak dapat menenggelamkan teks di bawahnya. Mengatur transparansi menjaga keterbacaan dokumen sambil tetap memberikan kedalaman. + +## Langkah 4: Pindahkan Bayangan – Inti dari **Cara Memindahkan Bayangan** + +Properti `Distance` menentukan seberapa jauh bayangan di-offset dari shape, diukur dalam poin. Jarak yang lebih besar memindahkan bayangan lebih jauh, menciptakan efek yang lebih dramatis. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Bagaimana jika Anda membutuhkan offset yang sangat kecil?** Menetapkan `Distance` ke `0` akan membuat bayangan berada tepat di belakang shape, yang berguna untuk efek emboss. + +## Langkah 5: Putar Sumber Cahaya – Menyelesaikan **Cara Memutar Bayangan** + +Bayangan tidak selalu lurus ke bawah; mereka mengikuti sudut sumber cahaya. Properti `Angle` (dalam derajat) memutar bayangan di sekitar shape. Mari miringkan 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Eksperimen cepat:** Coba `90` untuk bayangan ke kanan atau `-30` untuk bayangan ke kiri. Perubahan visualnya langsung terlihat. + +## Langkah 6: Simpan Dokumen – Melihat Hasil dari **Menambahkan Bayangan ke Shape** + +Setelah menyesuaikan bayangan, kita akan menulis dokumen kembali ke disk. Anda dapat menimpa file asli atau membuat file baru; contoh ini menggunakan file output baru. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Output yang diharapkan:** Buka `output.docx`. Bayangan shape akan tampak lebih lembut, sedikit ter-offset, semi‑transparan, dan berangsur 45°. Jika Anda membandingkannya berdampingan dengan `input.docx`, perbedaannya jelas. + +### Contoh Lengkap yang Siap Pakai (Copy‑Paste) + +Berikut seluruh program dalam satu blok. Tempelkan ke proyek konsol baru, ganti `YOUR_DIRECTORY` dengan jalur folder yang sebenarnya, lalu jalankan. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Pertanyaan Umum & Kasus Khusus + +### Bagaimana jika dokumen memiliki banyak shape? + +Anda dapat melakukan loop pada semua shape: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Bisakah saya menambahkan bayangan ke shape yang belum memiliki bayangan? + +Tentu saja. Objek `ShadowFormat` selalu ada; Anda hanya perlu mengaktifkannya: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Apakah ini bekerja dengan gambar dan SmartArt? + +Ya. Node apa pun yang diturunkan dari `Shape`—termasuk gambar, diagram, dan SmartArt—menyediakan `ShadowFormat`. Properti yang sama dapat diterapkan. + +### Bagaimana cara mengontrol warna bayangan? + +Gunakan properti `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Kekhawatiran kompatibilitas? + +Aspose.Words 23.12+ mendukung .NET 6, .NET Core 3.1, dan .NET Framework 4.6.2+. API yang ditunjukkan stabil di semua versi tersebut. + +## Kesimpulan + +Kita baru saja membahas **cara memindahkan bayangan** pada sebuah shape menggunakan Aspose.Words, dan sekaligus mendemonstrasikan **menambahkan bayangan ke shape**, **cara mengubah blur**, **cara mengatur transparansi**, serta **cara memutar bayangan**. Contoh lengkap yang dapat dijalankan memungkinkan Anda menyesuaikan bayangan shape dalam hitungan detik, memberi dokumen tampilan yang rapi dan profesional tanpa pernah membuka Word. + +Siap melangkah ke tahap berikutnya? Coba gabungkan penyesuaian bayangan ini dengan **formatting bersyarat**—misalnya, hanya terapkan bayangan yang lebih dalam pada heading atau pada chart yang melebihi ukuran tertentu. Atau jelajahi **gradient fill** untuk shape itu sendiri guna menciptakan desain yang benar‑benar menarik. + +Jika Anda menemui kendala, tinggalkan komentar di bawah. Selamat coding, dan semoga bayangan Anda selalu jatuh tepat di tempat yang Anda inginkan! + +![Diagram yang menunjukkan efek memindahkan bayangan pada shape – contoh cara memindahkan bayangan](https://example.com/images/shadow-demo.png "contoh cara memindahkan bayangan") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/basic-conversions/_index.md b/words/italian/net/basic-conversions/_index.md index a9a5ab91b4..159cba6a5c 100644 --- a/words/italian/net/basic-conversions/_index.md +++ b/words/italian/net/basic-conversions/_index.md @@ -34,6 +34,7 @@ | [Salva PDF in formato Word (Docx)](./pdf-to-docx/) | Scopri come convertire un PDF in un documento Word (Docx) utilizzando Aspose.Words per .NET in questa guida dettagliata e passo passo. Perfetta per gli sviluppatori. | | [Come esportare LaTeX da Word – Guida passo‑passo](./how-to-export-latex-from-word-step-by-step-guide/) | Scopri come esportare contenuti LaTeX da documenti Word usando Aspose.Words per .NET, con esempi pratici e istruzioni dettagliate. | | [Convertire Word in PDF in C# usando Aspose.Words – Guida](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Scopri come convertire documenti Word in PDF con C# usando Aspose.Words, con esempi di codice e passaggi dettagliati. | +| [Salva Word come PDF con Aspose.Words – Guida completa](./save-word-as-pdf-with-aspose-words-complete-guide/) | Scopri come salvare documenti Word in PDF usando Aspose.Words con una guida completa. | | [Salva Word come PDF con Aspose.Words – Guida completa C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Scopri come salvare documenti Word in PDF usando Aspose.Words con una guida completa in C#. | | [Salva Docx come PDF con Aspose.Words – Guida completa C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Scopri come salvare i file Docx come PDF usando Aspose.Words con una guida completa in C#. | diff --git a/words/italian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/italian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index e108985b35..4d37705a25 100644 --- a/words/italian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/italian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,24 @@ --- category: general -date: 2025-12-29 -description: Come esportare LaTeX da Word usando Aspose.Words – impara a convertire - Word in LaTeX, salvare docx come txt e gestire le equazioni in testo semplice. +date: 2026-05-01 +description: Scopri come esportare LaTeX da un file Word, convertire Word in txt e + preservare le tabelle usando Aspose.Words in C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: it -og_description: Come esportare LaTeX da Word con Aspose.Words. Questa guida ti mostra - come convertire Word in LaTeX, salvare il docx come txt e mantenere intatte le equazioni. -og_title: Come esportare LaTeX da Word – Rapido tutorial C# +og_description: Scopri come esportare LaTeX da Word, convertire Word in testo semplice + e mantenere intatto il layout delle tabelle con Aspose.Words. +og_title: Come esportare LaTeX da Word – Tutorial completo C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: Come esportare LaTeX da Word – Guida passo‑passo +title: Come esportare LaTeX da Word – Guida passo passo url: /it/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -27,176 +26,215 @@ url: /it/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Come esportare LaTeX da Word – Guida passo‑passo +# Come esportare LaTeX da Word – Tutorial completo in C# -Ti sei mai chiesto **come esportare LaTeX da Word** senza perdere quelle difficili equazioni Office Math? Non sei l'unico. Molti sviluppatori si trovano in difficoltà quando provano a *convertire Word in LaTeX* per articoli accademici, rapporti scientifici o pipeline di pubblicazione automatizzate.orreremo un esempio completo, pronto‑all'uso in C#, che mostra **come esportare LaTeX** usando Aspose.Words, spiega **come salvare file txt** con markup LaTeX, e copre anche le sfumature di **convertire equazioni Word in LaTeX** così nulla si perde nella traduzione. +Ti sei mai chiesto **come esportare LaTeX** da un documento Word senza perdere le equazioni matematiche? Non sei solo. Molti sviluppatori hanno bisogno di trasformare un .docx che contiene Office Math in LaTeX pulito, oltre a **convertire Word in txt** per l'elaborazione successiva. In questa guida percorreremo una soluzione pratica, pronta all'uso, che **preserva le tabelle**, fornisce un file di testo semplice e mantiene il markup LaTeX esattamente dove ti serve. -> **Consiglio:** Lo stesso approccio funziona per qualsiasi .docx tu abbia—basta puntare il codice a un percorso file diverso. +Copriamo tutto, dal caricamento del file sorgente alla configurazione di `TxtSaveOptions` affinché l'output sia sia leggibile dall'uomo sia adatto alle macchine. Alla fine sarai in grado di **salvare docx come txt**, **convertire Word in plain text**, e saprai **come preservare le tabelle** durante l'esportazione. Nessuno script esterno, nessun copia‑incolla manuale—solo puro codice C# che puoi inserire in qualsiasi progetto .NET. + +## Cosa ti serve + +- **Aspose.Words for .NET** (ultima versione, 2024.x o successiva). Il pacchetto NuGet è `Aspose.Words`. +- Un ambiente di sviluppo .NET (Visual Studio, VS Code, Rider—qualsiasi vada bene). +- Un file Word (`.docx`) che contenga equazioni Office Math e almeno una tabella (così possiamo vedere la magia della preservazione delle tabelle). + +Tutto qui. Se hai già tutto, continua a leggere; altrimenti scarica il pacchetto NuGet e un DOCX di esempio prima di approfondire. --- -## Cosa ti servirà +## Come esportare LaTeX da un documento Word + +Di seguito trovi il cuore del tutorial—tre passaggi concisi che rispondono alla domanda **come esportare latex** gestendo anche gli obiettivi secondari di **convertire word in txt**, **convertire word in plain text**, **salvare docx come txt** e **come preservare le tabelle**. -Prima di immergerci, assicurati di avere i seguenti prerequisiti: +### Passo 1: Caricare il file DOCX -| Prerequisito | Perché è importante | -|--------------|----------------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words è destinato a runtime .NET moderni. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | La libreria si occupa della parte pesante di parsing di Word e generazione di LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Per vedere la conversione LaTeX in azione. | -| **Visual Studio 2022** (or any IDE you like) | Rende il debug e l'esecuzione del campione triviale. | +Per prima cosa dobbiamo leggere il documento Word in un oggetto `Aspose.Words.Document`. Questo passaggio è lo stesso sia che tu voglia **convertire word in txt** sia **salvare docx come txt**. -Se non hai ancora installato il pacchetto NuGet, esegui: +```csharp +using Aspose.Words; +using Aspose.Words.Saving; -```bash -dotnet add package Aspose.Words +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -È tutto—nessun DLL extra, nessun interop COM, solo una libreria gestita pulita. +> **Perché è importante:** Il caricamento del file crea una rappresentazione in memoria di tutti gli elementi Word—paragrafi, tabelle e oggetti Office Math. Senza questo oggetto non puoi manipolare le opzioni di esportazione. ---- +### Passo 2: Configurare `TxtSaveOptions` per LaTeX e layout della tabella -## Come esportare LaTeX da Word – Panoramica +La classe `TxtSaveOptions` ti consente di controllare esattamente come viene generato il file di testo semplice. Due proprietà sono fondamentali per il nostro scenario: -Di seguito la panoramica di ciò che realizzeremo: +| Proprietà | Cosa fa | Perché ti serve | +|-----------|----------|-----------------| +| `OfficeMathExportMode` | Determina come viene renderizzato Office Math. Impostandola su `LaTeX` converte le equazioni nella sintassi LaTeX. | È il fulcro di **come esportare latex**. | +| `PreserveTableLayout` | Quando è `true`, Aspose aggiunge spazi bianchi così le tabelle mantengono un aspetto a griglia. | Soddisfa **come preservare le tabelle** mentre **converti word in txt**. | -1. **Carica** il documento Word sorgente (`.docx`). -2. **Configura** `TxtSaveOptions` in modo che tutti gli oggetti Office Math vengano emessi come codice LaTeX. -3. **Salva** il documento come file di testo semplice (`.txt`) che puoi fornire direttamente a qualsiasi compilatore LaTeX. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Esempio di esportazione LaTeX da Word](image.png "Esempio di esportazione LaTeX da Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Consiglio esperto:** Se ti serve solo il LaTeX grezzo senza formattazione della tabella, imposta `PreserveTableLayout` su `false`. Il file sarà più piccolo, ma perderai il suggerimento visivo della tabella. -## Passo 1: Carica il documento Word +### Passo 3: Salvare il documento come testo semplice -Prima di tutto—apri il .docx che desideri convertire. La classe `Document` astrae tutto l'XML sottostante, fornendoti un modello di oggetti intuitivo. +Ora scriviamo il documento in un file `.txt` usando le opzioni appena definite. Questa singola riga realizza **convertire word in plain text**, **salvare docx come txt**, e, naturalmente, **come esportare latex** tutto in una volta. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; - -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Perché è importante:** -Caricare il file in anticipo ci consente di ispezionarne il contenuto (ad es., contare le equazioni) prima di decidere come serializzarlo. Se il file è corrotto, `Document` genererà un'eccezione chiara, salvandoti da output misteriosi in seguito. +Al termine della chiamata, apri `output.txt`. Vedrai: ---- +- Frammenti LaTeX come `\frac{a}{b}` per ogni equazione Office Math. +- Tabelle renderizzate con i caratteri `|` e `-`, preservando l'allineamento delle colonne. +- Paragrafi regolari come testo semplice, pronti per qualsiasi parser successivo. -## Passo 2: Configura TxtSaveOptions per l'esportazione LaTeX +### Esempio completo funzionante -La magia avviene in `TxtSaveOptions`. Impostando `OfficeMathExportMode` su `LaTeX`, ogni oggetto Office Math viene trasformato nella sua corrispondente rappresentazione LaTeX. +Mettendo tutto insieme, ecco un programma autonomo che puoi compilare ed eseguire subito: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} +``` + +**Output previsto** (estratto): + ``` +This is a sample paragraph. -**Perché scegliamo queste impostazioni:** +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | -- `OfficeMathExportMode.LaTeX` è l'unica modalità che garantisce una traduzione matematica fedele. -- `PreserveTableLayout` mantiene le tabelle con l'aspetto di Word, utile quando in seguito incorpori l'output in un ambiente LaTeX `tabular`. -- UTF‑8 assicura che caratteri come “α”, “β” o “∑” sopravvivano al round‑trip. +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Se mai avessi bisogno di **convertire Word in LaTeX** senza il contenitore di testo semplice, potresti passare a `SaveFormat.LaTeX`—un rapido suggerimento per scenari avanzati. +Nota come la tabella mantiene la sua griglia e l'equazione appare come LaTeX pulito. Questo è il punto d'incontro ideale quando **converti word in txt** e hai ancora bisogno di una rappresentazione fedele sia della struttura sia della matematica. --- -## Passo 3: Salva il documento come file di testo +## Suggerimenti per convertire Word in TXT e preservare le tabelle -Ora scriviamo il testo ricco di LaTeX su disco. Il `.txt` risultante può essere rinominato in `.tex` in seguito, o inviato direttamente a un compilatore LaTeX. +Sebbene l'approccio a tre passaggi funzioni nella maggior parte dei casi, i progetti reali spesso lanciano imprevisti. Di seguito trovi suggerimenti pratici per rendere la tua pipeline **convertire word in plain text** più robusta. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Usa una codifica coerente -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` usa UTF‑8 per impostazione predefinita, che gestisce la maggior parte dei caratteri. Se ti serve una pagina di codice diversa (ad esempio sistemi legacy che si aspettano Windows‑1252), imposta la proprietà `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Ciò che vedrai in `output.txt`:** +### Elimina spazi bianchi in eccesso -``` -\begin{equation} -E = mc^{2} -\end{equation} +Le tabelle con molte colonne possono generare linee molto lunghe. Dopo il salvataggio, potresti voler post‑processare il file per comprimere più spazi in un singolo tabulatore: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Tutti gli altri paragrafi appaiono come testo semplice, mentre ogni equazione Office Math è avvolta in un ambiente LaTeX `equation` (o `inline` se era inline in Word). Questo soddisfa perfettamente il requisito **convertire equazioni Word in LaTeX**. +### Gestire tabelle nidificate ---- +Se il tuo DOCX contiene tabelle dentro tabelle, `PreserveTableLayout` manterrà comunque la gerarchia visiva, ma l'indentazione potrebbe apparire strana. Una rapida soluzione è sostituire gli spazi iniziali con un marcatore personalizzato (es. `>>`) così i parser successivi possono rilevare i livelli di nidificazione. -## Casi limite e domande comuni +### Elaborazione batch di più file -| Situazione | Cosa fare | -|------------|-----------| -| **Nessuna equazione nella sorgente** | La conversione funziona comunque; otterrai solo testo semplice. Nessun codice LaTeX aggiuntivo viene inserito. | -| **Documenti molto grandi (>100 MB)** | Considera lo streaming dell'output usando `MemoryStream` per evitare un elevato utilizzo di memoria. | -| **Costrutti matematici non supportati** | Aspose.Words copre il 99 % di Office Math. Per il raro caso limite, potresti dover post‑processare manualmente il LaTeX. | -| **Necessità di un file .tex invece di .txt** | Modifica `outputPath` in modo che termini con `.tex` e opzionalmente imposta `txtOptions.Encoding` su `Encoding.UTF8`. | -| **Esecuzione su Linux/macOS** | Lo stesso codice funziona—basta assicurarsi che i percorsi file usino slash forward o `Path.Combine`. | +Quando devi **convertire word in txt** per decine di documenti, avvolgi la logica in un ciclo: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +In questo modo puoi **salvare docx come txt** in massa senza intervento manuale. -## Come salvare TXT con equazioni LaTeX – Riepilogo rapido +--- -1. **Carica** il .docx (`Document`). -2. **Imposta** `OfficeMathExportMode = LaTeX` in `TxtSaveOptions`. -3. **Salva** il file (`doc.Save`) con quelle opzioni. +## Errori comuni e come evitarli -Questo è l'intero flusso di lavoro per **come salvare file txt** che contengono equazioni formattate in LaTeX. +1. **Modalità di esportazione LaTeX mancante** – Se dimentichi di impostare `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, le equazioni torneranno in testo semplice (es. “Equation 1”). Controlla sempre il blocco delle opzioni. +2. **Layout della tabella perso** – `PreserveTableLayout` è `false` di default. Se il tuo output sembra un muro di testo, probabilmente non hai attivato il flag. +3. **Percorsi di file con spazi** – Usare stringhe verbatim (`@"C:\My Folder\input.docx"`) evita problemi di escape. Altrimenti otterrai una `FileNotFoundException`. +4. **Incompatibilità di versione** – Le versioni più vecchie di Aspose.Words (< 21.9) non supportano `OfficeMathExportMode`. Aggiorna al pacchetto più recente per garantire che **come esportare latex** funzioni. +5. **Errori di codifica per caratteri non ASCII** – Se vedi simboli �, imposta esplicitamente `options.Encoding` a UTF‑8 o alla pagina di codice appropriata. --- -## Bonus: Automatizzare la conversione per più file +## Estendere la soluzione: da TXT a Markdown o HTML -Se hai una cartella piena di documenti Word, avvolgi la logica sopra in un semplice ciclo: +A volte ti serve più di un semplice testo—magari un file Markdown che contenga ancora blocchi LaTeX. La stessa `TxtSaveOptions` può essere sostituita da `HtmlSaveOptions` o `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Ora puoi **convertire Word in LaTeX** in blocco—perfetto per gruppi di ricerca che ricevono decine di manoscritti al giorno. +Questa piccola modifica ti consente di ottenere un output in stile **convertire word in txt** mantenendo la sintassi Markdown che ami. --- ## Conclusione -Abbiamo coperto **come esportare LaTeX da Word** passo‑passo, dimostrato **come salvare file txt** che preservano ogni equazione Office Math, e mostrato come **convertire equazioni Word in LaTeX** senza perdere fedeltà. +Abbiamo percorso una risposta completa e pronta per la produzione a **come esportare latex** da un documento Word, mostrando al contempo come **convertire word in txt**, **convertire word in plain text**, **salvare docx come txt** e **come preservare le tabelle**. I punti chiave sono: + +- Carica il DOCX con `Aspose.Words.Document`. +- Imposta `TxtSaveOptions.OfficeMathExportMode = LaTeX` e `PreserveTableLayout = true`. +- Chiama `doc.Save(outputPath, options)` per ottenere un file di testo semplice ricco di LaTeX. -Con poche righe di C# e la potente libreria Aspose.Words, puoi trasformare qualsiasi .docx in testo pronto per LaTeX, pronto per l'inclusione in articoli scientifici, libri di testo o pipeline di pubblicazione automatizzate. +Provalo sui tuoi file, sperimenta con le impostazioni di codifica e sentiti libero di elaborare in batch intere cartelle. Se incontri casi particolari—tabelle nidificate, caratteri esotici o versioni Aspose più vecchie—riferisciti alle sezioni “Suggerimenti” e “Errori comuni” per soluzioni rapide. -**Passi successivi?** Prova a fornire il `.txt` generato (o rinominalo in `.tex`) a `pdflatex` o `xelatex` per produrre un PDF, o esplora l'opzione `SaveFormat.LaTeX` per un file `.tex` diretto. Se hai bisogno di **salvare docx come txt** preservando la formattazione, sperimenta con `PreserveTableLayout` e la gestione personalizzata delle interruzioni di riga. +Pronto per il passo successivo? Prova a convertire lo stesso DOCX in Markdown, o alimenta il `.txt` generato a un generatore di siti statici che renderizza LaTeX sul web. Le possibilità sono infinite, e ora hai una solida base per qualsiasi workflow **convertire word in txt**. -Hai domande su casi limite, licenze o ottimizzazioni delle prestazioni? Lascia un commento qui sotto—buona programmazione! +Buon coding, e che il tuo LaTeX compili sempre al primo tentativo! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/italian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/italian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..ffd7e27196 --- /dev/null +++ b/words/italian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Salva Word come PDF usando Aspose.Words in C#. Impara a convertire docx + in PDF, rilevare i font mancanti e gestire efficacemente gli avvisi di sostituzione + dei font. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: it +og_description: Salva Word come PDF usando Aspose.Words. Questo tutorial passo‑passo + mostra come convertire docx in pdf e rilevare i caratteri mancanti. +og_title: Salva Word in PDF con Aspose.Words – Guida completa +tags: +- Aspose.Words +- C# +- PDF conversion +title: Salva Word come PDF con Aspose.Words – Guida completa +url: /it/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salva Word come PDF con Aspose.Words – Guida Completa + +Ti è mai capitato di dover **salvare Word come PDF** al volo e chiederti se per strada perderai qualche font? Non sei solo: gli sviluppatori si trovano spesso a lottare con i problemi di font mancanti durante la conversione dei documenti. In questa guida percorreremo una soluzione pratica che non solo **convert docx to pdf** ma rileva anche **font mancanti** grazie agli avvisi di sostituzione dei font di Aspose.Words. + +Copriamo tutto, dalla configurazione del raccoglitore di avvisi all'interpretazione dell'output, così alla fine saprai esattamente come **salvare Word come PDF** senza sorprese. Nessuno strumento esterno, nessuna impostazione oscura—solo codice C# pulito che puoi inserire in qualsiasi progetto .NET. + +## Cosa Ti Serve + +- **Aspose.Words for .NET** (ultima versione, ad es. 24.10) – puoi ottenerlo via NuGet (`Install-Package Aspose.Words`). +- Un ambiente di sviluppo .NET (Visual Studio, Rider o VS Code vanno bene). +- Un file DOCX di esempio che potrebbe contenere font non installati sulla macchina di destinazione. +È tutto. Se hai questi elementi di base, siamo pronti a immergerci. + +## Salva Word come PDF – Panoramica Passo‑Passo + +Di seguito trovi il programma completo, pronto per l'esecuzione. Sentiti libero di copiarlo in un progetto console e premere **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Consiglio:** Sostituisci `YOUR_DIRECTORY` con un percorso assoluto o usa `Path.Combine(Environment.CurrentDirectory, "input.docx")` per un approccio relativo e più sicuro. + +### Perché Utilizziamo un Callback di Avviso + +Aspose.Words sostituisce silenziosamente i font mancanti con un fallback (di solito Arial). Senza un callback non sapresti mai che la sostituzione è avvenuta, il che può provocare difetti di layout nel PDF risultante. Collegando `IWarningCallback`, otteniamo un elenco chiaro e programmatico di ogni evento di font mancante—perfetto per il logging o per avvisare gli utenti finali. + +### Rilevare Font Mancanti – Cosa Cercare + +Quando esegui il programma, ogni font mancante produrrà una riga nella console simile a: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Se l'elenco è vuoto, congratulazioni—**save word as pdf** è riuscito con tutti i font originali intatti. + +## Convert Docx to PDF – Personalizzare l'Output + +A volte è necessario una versione PDF specifica, una certa qualità delle immagini o un livello di conformità. Aspose.Words ti permette di regolare l'oggetto `PdfSaveOptions` prima di chiamare `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Perché è importante:** Se generi PDF per archivi legali, impostare `PdfA1b` garantisce che il file rispetti standard rigorosi. La stessa conversione mantiene il nostro callback di avviso, così continuerai a **detect missing fonts**. + +## Sostituzione Font di Aspose Words – Gestire i Casi Limite + +### Scenario 1: Molti Font Mancanti + +Se il documento di origine utilizza diversi font personalizzati, il raccoglitore di avvisi conterrà una voce per ciascun font. Puoi aggregarli: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenario 2: Fornire una Cartella di Font di Backup + +Aspose.Words può cercare cartelle aggiuntive per i font. Imposta la proprietà `FontsFolder` su `FontSettings` prima di caricare il documento: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Ora la libreria proverà prima la tua cartella personalizzata, riducendo la probabilità di sostituzioni indesiderate. + +### Scenario 3: Ignorare le Sostituzioni + +Se preferisci che la conversione fallisca quando un font è mancante (invece di sostituirlo silenziosamente), lancia un'eccezione all'interno del callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Questo ti costringe a risolvere il problema del font mancante prima di procedere—utile nelle pipeline CI dove i fallimenti silenziosi non sono accettabili. + +## Esempio Completo End‑to‑End + +Mettendo tutto insieme, ecco una versione compatta che dimostra **come convertire Word in PDF**, imposta opzioni PDF personalizzate e registra eventuali problemi di font: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Output console previsto** (se Calibri è mancante): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Se non compaiono avvisi, la tua operazione **save word as pdf** ha usato esattamente gli stessi font del DOCX di origine. + +## Riepilogo Visivo + +![Salva Word come PDF workflow diagram](https://example.com/diagram.png "Salva Word come PDF workflow") + +*Testo alternativo immagine:* **save word as pdf** workflow che mostra il caricamento, la raccolta degli avvisi e l'output PDF. + +## Domande Frequenti + +| Domanda | Risposta | +|----------|----------| +| **È necessaria una licenza per Aspose.Words?** | Una licenza di valutazione gratuita funziona per i test, ma l'uso in produzione richiede una licenza a pagamento per rimuovere la filigrana di valutazione. | +| **Funziona su .NET Core / .NET 6+?** | Assolutamente—Aspose.Words è basato su .NET Standard 2.0, quindi è compatibile con qualsiasi runtime .NET recente. | +| **Posso convertire più file DOCX in un ciclo?** | Sì, basta istanziare un nuovo `Document` per ogni file e riutilizzare lo stesso `WarningInfoCollector` se vuoi risultati aggregati. | +| **Cosa succede se la cartella di destinazione non esiste?** | `Document.Save` lancerà `DirectoryNotFoundException`. Crea prima la cartella o usa `Directory.CreateDirectory`. | +| **È possibile incorporare i font mancanti nel PDF?** | Aspose.Words può incorporare i font automaticamente se sono disponibili sulla macchina; imposta `PdfSaveOptions.EmbedFullFonts = true`. | + +## Conclusione + +Ora disponi di un modello solido, pronto per la produzione, per **salvare Word come PDF** rilevando **font mancanti** e gestendo gli scenari di **sostituzione font di Aspose.Words**. Collegando un callback di avviso, personalizzando le cartelle dei font e, se necessario, modificando `PdfSaveOptions`, puoi convertire in modo affidabile **docx to pdf** e tenere informati gli utenti su eventuali problemi di font che potrebbero influire sulla fedeltà del layout. + +Pronto per il passo successivo? Prova a generare PDF da più documenti in parallelo, o esplora l'aggiunta di filigrane e firme digitali—entrambi sono estensioni semplici del codice che hai appena imparato. Buona programmazione, e che i tuoi PDF siano sempre esattamente come desideri! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-loadoptions/_index.md b/words/italian/net/programming-with-loadoptions/_index.md index 1bb908f5d5..a2513eb0c0 100644 --- a/words/italian/net/programming-with-loadoptions/_index.md +++ b/words/italian/net/programming-with-loadoptions/_index.md @@ -41,6 +41,7 @@ In questi tutorial imparerai come utilizzare LoadOptions per caricare documenti | [Aspose Load Options – Carica DOCX con impostazioni di font personalizzate](./aspose-load-options-load-docx-with-custom-font-settings/) | Scopri come caricare file DOCX specificando impostazioni di font personalizzate con Aspose Load Options. | | [Come utilizzare LoadOptions in Aspose.Words – Guida completa](./how-to-use-loadoptions-in-aspose-words-complete-guide/) Scopri come utilizzare LoadOptions in Aspose.Words per .NET con questa guida completa passo passo. | | [Recupera documento corrotto in C# – Imposta modalità di recupero e avvisa l'utente](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Scopri come recuperare documenti corrotti in C# impostando la modalità di recupero e mostrando un prompt all'utente. | +| [Recupera docx corrotto – Guida completa al caricamento di file Word danneggiati in C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Scopri come caricare e riparare file DOCX danneggiati in C# con Aspose.Words, passo passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/italian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..177b89f3a1 --- /dev/null +++ b/words/italian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Recupera rapidamente i file docx corrotti usando Aspose.Words. Scopri + come impostare la modalità di recupero, caricare i docx in modo sicuro e leggere + i file Word danneggiati in pochi passaggi. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: it +og_description: Recupera file docx corrotti in C#. Imposta la modalità di recupero, + carica i docx in modo sicuro e leggi i file Word danneggiati con Aspose.Words. +og_title: Recupera docx corrotti – Guida rapida C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Recupera docx corrotti – Guida completa al caricamento di file Word danneggiati + in C# +url: /it/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Recuperare docx corrotti – Guida rapida C# + +Hai mai provato ad aprire un file Word che semplicemente non si carica e ti sei chiesto se il contenuto fosse perso per sempre? In molti progetti reali **recupererai docx corrotti** senza chiedere all'utente di reinviare l'allegato. La buona notizia è che Aspose.Words lo rende un gioco da ragazzi: basta impostare la modalità di recupero e lasciare che la libreria faccia il lavoro pesante. + +In questo tutorial percorreremo passo passo le fasi per **recuperare docx corrotti**, spiegheremo perché l'opzione `RecoveryMode.AutoRecover` è la scelta più sicura e ti mostreremo **come caricare docx** file che potrebbero essere parzialmente danneggiati. Alla fine sarai in grado di leggere un file Word danneggiato, estrarre il testo rimasto e persino registrare il formato originale per futuri audit. Nessuno strumento esterno, solo codice C# pulito. + +## Cosa ti serve + +- **Aspose.Words for .NET** (qualsiasi versione recente; l'API che usiamo funziona con la 23.5 e successive). +- Un ambiente di sviluppo .NET (Visual Studio, VS Code o Rider). +- Il `.docx` corrotto o parzialmente danneggiato che vuoi salvare. + +Nessuna autorizzazione speciale, nessun COM interop e nessuna necessità di installare Microsoft Office sul server. Semplice, vero? + +## Passo 1: Imposta la modalità di recupero su Auto‑Recover + +Quando un file Word è rotto, il comportamento di caricamento predefinito lancia un'eccezione e abortisce. Configurando un oggetto `LoadOptions` dici ad Aspose.Words di **impostare la modalità di recupero** su `AutoRecover`, che scandisce il pacchetto zip, salta le parti illeggibili e restituisce tutto ciò che riesce a ricomporre. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Perché AutoRecover?** +> Tenta di leggere il più possibile mantenendo l'oggetto documento utilizzabile. Se scegli `RecoveryMode.NoRecovery`, il caricamento fallirà al primo errore, vanificando lo scopo dei casi **recuperare docx corrotti**. + +## Passo 2: Carica il documento con le opzioni configurate + +Ora che la modalità di recupero è impostata, puoi provare ad aprire il file in sicurezza. Sostituisci `"YOUR_DIRECTORY/input.docx"` con il percorso reale del tuo file danneggiato. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Se il file è solo parzialmente corrotto, l'istanza `Document` verrà comunque creata. Puoi verificare `document.IsStructureValid` in seguito se ti serve una validazione aggiuntiva. + +## Passo 3: Verifica il formato rilevato + +Aspose.Words rileva automaticamente il formato originale (DOC, DOCX, ODT, ecc.). Stampare questo valore ti aiuta a confermare che la libreria abbia riconosciuto correttamente il file, un rapido controllo di sanità dopo un'operazione di **recuperare docx corrotti**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Output tipico: + +``` +Loaded with Docx format. +``` + +Anche se alcune parti mancavano, il rilevamento del formato riesce comunque—un altro vantaggio per i flussi **recuperare docx corrotti**. + +## Passo 4: Estrai ciò che puoi + +Una volta caricato il documento, lo tratti come qualsiasi file Word sano. Di seguito un esempio compatto che estrae il testo semplice e lo scrive sulla console. Dimostra che puoi **leggere file Word danneggiati** senza crash. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Se il file originale conteneva tabelle o immagini corrotte, verranno semplicemente omesse dall'output testuale. Il resto del documento rimane intatto. + +## Passo 5: Salva una copia pulita (opzionale) + +Spesso vorrai fornire all'utente una nuova versione pulita del file dopo il recupero. Salvare con lo stesso formato garantisce la compatibilità con tutti i processi successivi. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Ora hai un file **recuperato da docx danneggiato** che puoi allegare a un'email o passare a un altro servizio in tutta sicurezza. + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco il programma completo, pronto per l'esecuzione. Incollalo in un nuovo progetto console, aggiusta i percorsi dei file e premi F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Output previsto** (supponendo che il file contenga un singolo paragrafo “Hello world!” e qualche XML corrotto): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Nota come il programma non vada in crash—anche se il file sorgente era parzialmente rotto. Questa è l'essenza di **recuperare docx corrotti** usando Aspose.Words. + +## Domande frequenti & casi limite + +### E se il file fosse completamente illeggibile? + +Anche `AutoRecover` ha dei limiti. Se il contenitore zip è corrotto oltre ogni possibile riparazione, Aspose.Words lancerà una `CorruptedFileException`. In tal caso potresti aver bisogno di uno strumento di riparazione zip di terze parti prima di provare di nuovo a **recuperare docx corrotti**. + +### Posso recuperare altri formati (es. `.doc`, `.odt`)? + +Assolutamente. Lo stesso `LoadOptions` funziona per qualsiasi formato supportato da Aspose.Words. Basta cambiare l'estensione del file e la libreria rileverà automaticamente il formato originale. Questo significa che puoi anche **recuperare docx danneggiati**‑like file come `.doc` o `.rtf` con lo stesso codice. + +### Come gestire documenti molto grandi senza caricarli interamente in memoria? + +Per file di dimensioni gigabyte puoi abilitare **opzioni di caricamento** come `LoadOptions.LoadFormat` o streamare il documento pagina per pagina. Tuttavia, l'algoritmo di recupero deve comunque leggere l'intero pacchetto, quindi attenditi un consumo di memoria più elevato per file molto grandi e corrotti. + +### È possibile sapere quali parti sono state perse? + +Dopo il caricamento, puoi ispezionare `document.GetChildNodes(NodeType.Any, true)` e confrontare il conteggio con una baseline attesa. Tabelle, immagini o intestazioni mancanti saranno semplicemente assenti dalla collezione di nodi. Questo ti permette di registrare esattamente cosa è stato **recuperato da docx danneggiato** e informare l'utente. + +## Consigli professionali per un recupero affidabile + +- **Convalida la dimensione del file di input** prima del caricamento; un file di zero byte fallirà sempre. +- **Registra il risultato di `RecoveryMode`** catturando `DocumentLoadingException` e memorizzando il messaggio di eccezione; spesso contiene indizi su quali parti sono state saltate. +- **Esegui il recupero su un thread in background** se stai processando upload in un servizio web—mantiene la risposta reattiva. +- **Combina con un checksum** (es. MD5) per rilevare se il file recuperato differisce dall'originale; così potrai decidere se conservare entrambe le versioni. + +## Conclusione + +Abbiamo appena mostrato come **recuperare docx corrotti** in C# impostando la **modalità di recupero** su `AutoRecover`, caricando il documento in sicurezza, estraendo il testo rimasto e, opzionalmente, salvando una copia pulita. Questo approccio ti consente di **caricare docx** file che altrimenti genererebbero eccezioni e ti offre un modo affidabile per **leggere file Word danneggiati** senza strumenti esterni. + +Prossimi passi? Prova a sostituire `RecoveryMode.AutoRecover` con `RecoveryMode.NoRecovery` per vedere la differenza, o sperimenta con le proprietà di `LoadOptions` che controllano la gestione delle password e la sostituzione dei font. Potresti anche integrare la routine di recupero in un'API ASP.NET Core che accetta upload e restituisce un file riparato—perfetto per pipeline di gestione documentale aziendali. + +Hai altre domande sul recupero di documenti Word, o vuoi vedere come **recuperare docx danneggiati** con callback personalizzate? Lascia un commento qui sotto, e buona programmazione! + +![Illustrazione di un documento recuperato – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-markdownsaveoptions/_index.md b/words/italian/net/programming-with-markdownsaveoptions/_index.md index b439838a1a..9a41cb4dd7 100644 --- a/words/italian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/italian/net/programming-with-markdownsaveoptions/_index.md @@ -35,13 +35,14 @@ | [Come salvare Markdown da DOCX – Guida passo‑passo](./how-to-save-markdown-from-docx-step-by-step-guide/) | Scopri come salvare documenti DOCX in Markdown con una guida passo‑passo completa. | | [Come salvare Markdown da Word – Guida completa C#](./how-to-save-markdown-from-word-complete-c-guide/) | Scopri come salvare documenti Word in formato Markdown con una guida completa in C#. | | [Come salvare Markdown da Word – Guida completa](./how-to-save-markdown-from-word-complete-guide/) | Scopri come salvare documenti Word in formato Markdown con una guida completa. | - | [Come esportare LaTeX da Word: Converti DOCX in Markdown con Aspose](./how-to-export-latex-from-word-convert-docx-to-markdown-with/) | Scopri come esportare equazioni LaTeX da documenti Word convertendoli in Markdown con Aspose.Words per .NET. | +| [Salva docx come markdown – Esporta matematica Word in LaTeX con Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Scopri come esportare equazioni Word in LaTeX durante la conversione di DOCX in Markdown con Aspose.Words. | | [Converti Word in Markdown – Incorpora immagini come Base64](./convert-word-to-markdown-embed-images-as-base64/) | Converti documenti Word in Markdown incorporando le immagini direttamente come stringhe Base64 per un output autonomo. | | [Come esportare LaTeX: Converti DOCX in Markdown e TXT](./how-to-export-latex-convert-docx-to-markdown-txt/) | Scopri come convertire file DOCX in Markdown e TXT mantenendo le equazioni LaTeX con Aspose.Words per .NET. | | [Come rinominare le immagini durante la conversione da DOCX a Markdown](./how-to-rename-images-when-converting-docx-to-markdown/) | Scopri come rinominare le immagini durante la conversione da DOCX a Markdown con Aspose.Words per .NET. | | [Salva docx come markdown con Aspose.Words – Guida completa C#](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Impara a convertire file DOCX in Markdown con Aspose.Words usando C# con una guida completa. | | [Salva immagini Word – Converti Word in Markdown con Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) | Salva le immagini da documenti Word e convertili in Markdown usando Aspose.Words per .NET. | +| [Carica immagini su cloud durante la conversione da Word a Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) | Scopri come caricare le immagini su un servizio cloud durante la conversione di documenti Word in Markdown con Aspose.Words per .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/italian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..d7508b2ec9 --- /dev/null +++ b/words/italian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: Salva docx come markdown usando Aspose.Words – impara a convertire Word + in markdown, esportare le equazioni in LaTeX e impostare la risoluzione delle immagini + markdown in un unico flusso di lavoro fluido. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: it +og_description: Salva docx come markdown con Aspose.Words. Questo tutorial mostra + come convertire Word in markdown, esportare le equazioni in LaTeX e impostare la + risoluzione delle immagini in markdown. +og_title: Salva docx come markdown – Guida completa per esportare le formule di Word + in LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Salva docx come markdown – Esporta le formule Word in LaTeX con Aspose.Words +url: /it/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# salva docx come markdown – Esporta Word Math in LaTeX con Aspose.Words + +Ti è mai capitato di **salvare docx come markdown** ma di restare bloccato su come mantenere le equazioni Office Math nitide? Non sei l'unico. La maggior parte degli sviluppatori si scontra con un muro quando la conversione predefinita trasforma le equazioni in immagini sfocate, costringendo a riscriverle manualmente in LaTeX. + +Buone notizie: Aspose.Words può fare il lavoro pesante per te. In questo tutorial **converteremo word in markdown**, diremo al motore di **export equations to latex** e imposteremo anche **set markdown image resolution** per il resto del documento. Alla fine avrai un unico comando che genera un file `.md` pulito con matematica pronta per LaTeX e immagini ad alta risoluzione. + +## Cosa Imparerai + +- Come caricare un `.docx` che contiene oggetti Office Math. +- Quali proprietà di `MarkdownSaveOptions` controllano **export equations to latex** e **set markdown image resolution**. +- Un frammento C# completo e eseguibile che puoi incollare in qualsiasi progetto .NET. +- Suggerimenti per risolvere problemi comuni, come font mancanti o funzionalità di equazione non supportate. + +**Prerequisiti**: .NET 6+ (o .NET Framework 4.6+), una licenza per Aspose.Words per .NET e una conoscenza di base di C#. Se ti trovi a tuo agio nel creare un'app console, sei pronto a partire. + +--- + +## Passo 1 – Salva docx come markdown: Carica il tuo file Word + +La prima cosa di cui abbiamo bisogno è un oggetto `Document` che punti al `.docx` di origine. Pensalo come aprire il libro prima di iniziare a copiare i capitoli. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Perché è importante*: Se il documento non contiene alcuna matematica, il passo **export equations to latex** sarà un'operazione nulla, ma il resto della conversione verrà comunque eseguito. Il controllo ti evita di chiederti perché il tuo Markdown di output manca dei blocchi LaTeX. + +## Passo 2 – Configura Export Equations to LaTeX + +Aspose.Words ti permette di decidere come rendere Office Math. Per impostazione predefinita le converte in immagini PNG, motivo per cui molti tutorial finiscono con un file markdown granuloso. Cambiare `OfficeMathExportMode` in `LaTeX` ti fornisce equazioni pulite, pronte per il copia‑incolla. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Perché `OfficeMathExportMode.LaTeX`?* LaTeX è la lingua franca della pubblicazione scientifica. Quando renderizzi successivamente il markdown con un generatore di siti statici o un notebook Jupyter, le equazioni appariranno nitide a qualsiasi livello di zoom. + +## Passo 3 – Imposta la risoluzione delle immagini Markdown (per contenuti non‑matematici) + +Anche se ci concentriamo sulla matematica, la maggior parte dei documenti Word contiene anche immagini, grafici o SVG incorporati. La proprietà `ImageResolution` controlla come Aspose.Words rasterizza quegli asset. Un valore di **300 DPI** è un buon compromesso per schermo e stampa. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Consiglio professionale*: Se il tuo markdown verrà visualizzato solo sul web, potresti ridurlo a 150 DPI per diminuire le dimensioni del file. Al contrario, per PDF pronti per la stampa, aumentalo a 600 DPI. + +## Passo 4 – Esegui la conversione – Converti Word Math in LaTeX + +Ora che tutto è configurato, la conversione vera e propria è una singola riga. Aspose.Words fa il lavoro pesante dietro le quinte. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Output previsto**: Apri il file `.md` generato e dovresti vedere qualcosa di simile: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Nota i blocchi LaTeX (`$...$` e `$$...$$`) che sostituiscono i precedenti frammenti PNG. L'immagine in fondo è ancora un PNG, renderizzata a 300 DPI come richiesto. + +## Passo 5 – Casi limite comuni e come gestirli + +| Situazione | Cosa succede | Come risolvere | +|------------|--------------|----------------| +| **Missing fonts** (ad es., Cambria Math non installato) | L'output LaTeX può contenere simboli sconosciuti. | Installa il font mancante sul server o incorporalo nel documento prima della conversione. | +| **Complex equations** (matrice con delimitatori personalizzati) | Aspose.Words potrebbe ricorrere a un'immagine nonostante la modalità `LaTeX`. | Aggiorna alla versione più recente di Aspose.Words; la libreria migliora continuamente la copertura delle equazioni. | +| **Large documents** ( > 50 MB ) | La pressione di memoria può causare `OutOfMemoryException`. | Usa `LoadOptions` con `LoadFormat.Docx` e trasmetti il file in streaming, oppure dividi il documento in sezioni prima della conversione. | +| **Image size too big** | Il file Markdown diventa enorme, rallentando le build del sito statico. | Riduci `ImageResolution` a 150 DPI per scenari solo web (vedi Passo 3). | + +## Passo 6 – Metti tutto insieme: Esempio completo funzionante + +Di seguito trovi il programma *completo* della console‑app che puoi copiare‑incollare in `Program.cs`. Include tutti gli elementi di cui abbiamo parlato, più un po' di gestione degli errori aggiuntiva. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Esegui il programma (`dotnet run`) e otterrai un file markdown che **salva docx come markdown** preservando ogni equazione in LaTeX. Nessun copia‑incolla manuale, nessuna brutta immagine raster per la matematica. + +## Conclusione + +Abbiamo illustrato l'intero processo di **salvare docx come markdown** con Aspose.Words, dal caricamento del file Word alla configurazione di **export equations to latex** e **set markdown image resolution**. Il frammento finale è pronto per la produzione e può essere inserito in qualsiasi progetto .NET che necessita di **convertire word in markdown** al volo. + +Cosa fare dopo? Prova a inserire il `.md` generato in un generatore di siti statici come Hugo o Jekyll e osserva le tue equazioni renderizzate magnificamente. Se devi **convertire word math latex** in altri formati (PDF, HTML), basta sostituire `MarkdownSaveOptions` con `PdfSaveOptions` o `HtmlSaveOptions`—la stessa flag `OfficeMathExportMode` funziona per tutti. + +Hai una variante nel tuo flusso di lavoro, ad esempio prelevare file Word da Azure Blob storage o trasmetterli da un'API? Lo stesso schema si applica; basta sostituire il costruttore `Document` basato su file system con uno basato su stream. + +Sentiti libero di sperimentare e facci sapere nei commenti come questo approccio ha risolto i tuoi problemi di conversione. Buon coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/italian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..33dac743e5 --- /dev/null +++ b/words/italian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: Carica le immagini sul cloud durante la conversione di un documento Word + in markdown. Scopri come estrarre le immagini da un file docx e archiviarle in Azure + Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: it +og_description: Carica le immagini sul cloud mentre converti un documento Word in + markdown. Questa guida mostra come estrarre le immagini da un file docx e archiviarle + in Azure Blob storage. +og_title: Carica le immagini sul cloud durante la conversione da Word a Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Carica le immagini sul cloud durante la conversione da Word a Markdown +url: /it/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Caricare Immagini sul Cloud Durante la Conversione da Word a Markdown + +Ti è mai capitato di **caricare immagini sul cloud** mentre trasformi un file Word in markdown? Non sei l'unico—gli sviluppatori gestiscono costantemente la conversione dei documenti e la gestione delle risorse, e fare entrambe le cose in un flusso fluido può sembrare come inseguire un bersaglio in movimento. + +La buona notizia? Con Aspose.Words puoi estrarre ogni immagine, grafico o diagramma da un .docx, inviarlo direttamente a Azure Blob Storage e far sì che il markdown generato faccia riferimento a quegli URL cloud invece che a file locali. In questo tutorial percorreremo l'intero processo, dal caricamento del documento sorgente fino ad ottenere un file markdown pulito che punta al tuo bucket Azure. + +Alla fine di questa guida sarai in grado di **convertire docx in markdown**, **estrarre immagini da docx** e **memorizzare immagini su Azure Blob**—tutto con poche righe di C#. Nessun tool esterno, nessun copia‑incolla manuale e, soprattutto, nessun link immagine rotto. + +## Cosa Ti Serve + +- **.NET 6.0** o successivo (il codice funziona anche su .NET Core e .NET Framework) +- **Aspose.Words for .NET** (pacchetto NuGet `Aspose.Words`) +- Un **account Azure Storage** con un contenitore (ad es. `images`) e una chiave di accesso condivisa – ti servirà la stringa di connessione per caricare i file. +- Una conoscenza di base di C# e async/await (opzionale ma utile). + +Se hai già tutti questi elementi, ottimo—passiamo subito alla soluzione. Altrimenti, la sezione “Prerequisiti” alla fine ti indirizzerà verso i passaggi rapidi di configurazione. + +## Passo 1: Configurare Azure Blob Helper (Perché è Importante) + +Prima di toccare il documento Word, abbiamo bisogno di un piccolo helper che sappia come inviare un array di byte ad Azure Blob Storage e restituire un URL pubblico. Questa astrazione mantiene pulita la logica di conversione e rende semplice sostituire il provider di storage in futuro. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Perché questo helper?** +1. **Separazione delle responsabilità** – il codice di conversione markdown rimane focalizzato sulla gestione del documento, non sui dettagli HTTP. +2. **Riutilizzabilità** – puoi chiamare `UploadAsync` da qualsiasi altra parte della tua app (ad es. per immagini caricate dagli utenti). +3. **Preparazione al futuro** – passare a Amazon S3 o Google Cloud Storage richiede solo una nuova implementazione della stessa interfaccia. + +> **Consiglio professionale:** Imposta il livello di accesso del contenitore su `Blob` (pubblico) solo se va bene che chiunque possa leggere le immagini. Per scenari privati, genera token SAS per ogni upload e incorpora quegli URL al posto di quelli pubblici. + +## Passo 2: Definire un Callback di Salvataggio delle Risorse (Il Cuore del Caricamento‑Durante‑Conversione) + +Aspose.Words ti permette di intercettare ogni risorsa (immagine, grafico, ecc.) che normalmente verrebbe scritta su disco quando salvi un documento come markdown. Fornendo un `ResourceSavingCallback`, possiamo caricare ogni risorsa su Azure Blob e sostituire il nome file locale con l'URL cloud. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Cosa succede qui?** + +- **Estrazione** – Aspose.Words fornisce uno stream per ogni immagine. +- **Upload** – Passiamo quello stream a `AzureBlobUploader`. +- **Sostituzione** – Il writer markdown riceve l'URL pubblico e lo inserisce nella sintassi immagine markdown (`![](https://…)`). + +Poiché impostiamo `args.AlreadyExists = true`, nessun file temporaneo ingombra il filesystem—un'operazione pulita e senza stato, perfetta per funzioni serverless. + +## Passo 3: Configurare le Opzioni di Salvataggio Markdown (Unire il Tutto) + +Ora integriamo il callback nelle `MarkdownSaveOptions` di Aspose.Words. I flag cruciali sono `ExportImagesAsBase64 = false` (così otteniamo link esterni) e `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Perché disabilitiamo Base64?** +Quando `ExportImagesAsBase64` è true, Aspose incorpora ogni immagine direttamente nel markdown come data URI. Questo vanifica lo scopo di **caricare immagini sul cloud** perché il file markdown diventa ingombrante e le immagini rimangono nascoste al CDN. Disattivandolo otteniamo link esterni puliti che puntano ad Azure Blob—esattamente ciò che si aspetta un generatore di siti statici moderno. + +## Passo 4: Mettere Tutto Insieme – Un’Applicazione Console Minimal + +Di seguito trovi un programma console completo, pronto per l'esecuzione. Sostituisci i segnaposto con la tua stringa di connessione Azure e il nome del contenitore. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Output Atteso + +Eseguendo il programma con `sample.docx` che contiene due immagini otterrai: + +- `output.md` contenente la sintassi immagine markdown come: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-pdfsaveoptions/_index.md b/words/italian/net/programming-with-pdfsaveoptions/_index.md index e2b85d56a3..153fae4ea9 100644 --- a/words/italian/net/programming-with-pdfsaveoptions/_index.md +++ b/words/italian/net/programming-with-pdfsaveoptions/_index.md @@ -46,9 +46,9 @@ Che tu voglia convertire documenti Word in PDF per la distribuzione online, l'ar | [Rendering di effetti 3D DML 3D in un documento PDF](./dml-3deffects-rendering/) | Scopri come ottenere effetti DML 3D sorprendenti nei documenti PDF utilizzando Aspose.Words per .NET con questa guida completa passo dopo passo. | | [Interpolazione delle immagini in un documento PDF](./interpolate-images/) | Scopri come interpolare le immagini in un documento PDF utilizzando Aspose.Words per .NET con la nostra guida passo passo. Migliora facilmente la qualità delle immagini del tuo PDF. | | [Salva DOCX come PDF con Aspose.Words – Guida completa C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Guida completa in C# per convertire documenti DOCX in PDF usando Aspose.Words. | +| [Salva documento come PDF con Aspose.Words – Guida completa C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Guida dettagliata in C# per salvare qualsiasi documento Word come PDF con Aspose.Words. | | [Crea PDF accessibile da Word con C# – Guida passo‑passo](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Scopri come generare PDF accessibili da documenti Word usando Aspose.Words per .NET con C#, includendo tag di accessibilità e struttura semantica. | | [Crea PDF accessibile in C# – Tutorial di accessibilità PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Scopri come generare PDF accessibili in C# con Aspose.Words per .NET, includendo tag di struttura, testo alternativo e impostazioni di lettura. | - | [Crea PDF accessibile da Word – Guida completa](./create-accessible-pdf-from-word-complete-guide/) | Scopri come creare PDF accessibili da documenti Word con questa guida completa, includendo impostazioni di accessibilità e best practice. | | [Crea PDF accessibile – Guida passo passo per la conformità PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Scopri come creare PDF accessibili conformi a PDF/UA con Aspose.Words per .NET in questa guida dettagliata. | diff --git a/words/italian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/italian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..cf0917a4cf --- /dev/null +++ b/words/italian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: Scopri come salvare un documento come PDF usando Aspose.Words in C#. + Il tutorial copre anche la conversione da Word a PDF, l'esportazione di formule + LaTeX e la gestione dei font mancanti. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: it +og_description: Salva il documento in PDF senza sforzo con Aspose.Words. Questa guida + mostra anche come convertire Word in PDF, esportare formule LaTeX e gestire i font + mancanti. +og_title: Salva il documento come PDF con Aspose.Words – Guida completa C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Salva documento come PDF con Aspose.Words – Guida completa C# +url: /it/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salva documento come PDF con Aspose.Words – Guida completa C# + +Ti sei mai chiesto **how to save document as pdf** direttamente da un file Word senza perdere le funzionalità di accessibilità? Non sei l'unico—gli sviluppatori chiedono costantemente un modo affidabile per convertire Word in PDF mantenendo le equazioni matematiche e gestendo i font mancanti in modo elegante. + +In questo tutorial percorreremo una soluzione passo‑passo che non solo **save document as pdf** ma dimostra anche **convert word to pdf**, **export math latex** e **handle missing fonts** usando l'ultima versione di Aspose.Words per .NET. Alla fine avrai un programma C# pronto all'uso che produce file conformi a PDF/UA‑2, perfetti per le verifiche di accessibilità. + +## Cosa ti serve + +- .NET 6 o versioni successive (il codice funziona anche con .NET Core e .NET Framework) +- Aspose.Words per .NET 25.10 o versioni più recenti – puoi scaricare una prova gratuita dal sito di Aspose +- Un semplice documento Word (`input.docx`) che contiene almeno una forma flottante e un'equazione matematica (per vedere la funzionalità export‑math‑latex in azione) +- Visual Studio 2022 (o qualsiasi IDE tu preferisca) + +> **Suggerimento:** Se sei su una pipeline CI/CD, aggiungi il pacchetto NuGet Aspose.Words al file di progetto: + +```xml + +``` + +## Passo 1: Carica il documento sorgente con recupero automatico + +Quando si lavora con file Word del mondo reale potresti incontrare sezioni corrotte o risorse mancanti. Abilitare il recupero automatico garantisce che il processo di caricamento non lanci mai un'eccezione. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Perché è importante:** +`RecoveryMode.AutoRecover` protegge la tua pipeline da crash su input malformati, il che è particolarmente utile quando **convert word to pdf** in blocco. + +## Passo 2: Configura le opzioni di salvataggio PDF per piena accessibilità + +PDF/UA‑2 è lo standard ISO per PDF accessibili. Configurando alcune impostazioni otteniamo un file navigabile dagli screen reader e ci assicuriamo inoltre che le equazioni matematiche vengano esportate come LaTeX nascosto. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Punti chiave:** + +- **ExportFloatingShapesAsInlineTag** – garantisce che il PDF risultante rispetti il layout originale mantenendo la correttezza semantica. +- **OfficeMathExportMode.LaTeX** – soddisfa il requisito **export math latex**, permettendo agli strumenti successivi di estrarre le equazioni se necessario. + +## Passo 3: Cattura gli avvisi (ad es., font mancanti) + +I font mancanti sono un problema comune durante la conversione dei documenti. Aspose.Words può segnalare questi problemi tramite un `WarningCallback`. Li raccoglieremo così potrai registrarli o agire su di essi in seguito. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Perché è importante:** +Se la sorgente utilizza un font non installato sul server, il PDF ricadrà su un font predefinito, potenzialmente rompendo il layout. Con **handle missing fonts** possiamo avvisare l'utente o incorporare un sostituto. + +## Passo 4: Salva il documento come PDF accessibile + +Ora il momento della verità—eseguire effettivamente la conversione. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Se tutto procede senza intoppi, otterrai un file PDF/UA‑2 che contiene LaTeX nascosto per ogni equazione e un corretto tagging per le forme flottanti. + +## Passo 5: Rivedi gli avvisi catturati (Opzionale ma consigliato) + +Dopo l'operazione di salvataggio, puoi iterare sugli avvisi raccolti e registrarli. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Un output tipico potrebbe apparire così: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Vedere questi messaggi in anticipo ti aiuta a **handle missing fonts** prima che influenzino gli utenti finali. + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco il programma completo, pronto all'uso. Sostituisci i percorsi segnaposto con i tuoi. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Risultato atteso:** +- `output.pdf` è conforme a PDF/UA‑2. +- Tutte le forme flottanti sono taggate come figure inline. +- Ogni oggetto Office Math appare come LaTeX nascosto (visibile quando ispezioni la struttura del PDF). +- Qualsiasi problema legato ai font viene stampato sulla console, dandoti la possibilità di **handle missing fonts** prima di distribuire il file. + +![Diagramma che mostra il flusso da Word → Aspose.Words → PDF accessibile (save document as pdf)](conversion-diagram.png "Diagramma di flusso per salvare documento come pdf") + +*Testo alternativo dell'immagine:* **Diagramma di come salvare documento come pdf usando Aspose.Words** + +## Domande frequenti e casi particolari + +### Cosa succede se sto usando una versione più vecchia di Aspose.Words? + +Il flag `OfficeMathExportMode.LaTeX` è stato introdotto nella 25.10. Per versioni più vecchie puoi ancora **convert word to pdf**, ma la matematica verrà rasterizzata invece di essere esportata come LaTeX. Aggiorna per la migliore accessibilità. + +### Posso incorporare font personalizzati per evitare il fallback? + +Sì. Imposta `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` prima di chiamare `Save`. Questo aiuta anche a **handle missing fonts** forzando il PDF a contenere i glifi necessari. + +### Come verifico la conformità PDF/UA‑2? + +Apri il file in Adobe Acrobat Pro → “Print Production” → “Preflight”. Scegli il profilo “PDF/A‑2b” o “PDF/UA‑2”; Acrobat segnalerà eventuali violazioni. + +### E i file Word protetti da password? + +Carica il documento con un `LoadOptions` che includa `Password`. Esempio: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Il resto della pipeline rimane invariato. + +## Conclusione + +Abbiamo coperto tutto ciò di cui hai bisogno per **save document as pdf** usando Aspose.Words in C#. Il tutorial ha anche dimostrato come **convert word to pdf**, **export math latex**, e **handle missing fonts**—tutto mentre si produce un file PDF/UA‑2 accessibile. + +Prova il codice, sperimenta con diverse `PdfSaveOptions` (ad es., compressione immagini, PDF/A‑2b) e integralo nel tuo servizio di elaborazione documenti. Se hai bisogno di andare oltre, considera di esplorare la libreria specifica per PDF di Aspose per il post‑processing o le firme digitali. + +Hai altri scenari che vorresti affrontare? Sentiti libero di lasciare un commento o di consultare le nostre altre guide su **PDF manipulation**, **image extraction**, e **batch conversion**. Buon coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-shapes/_index.md b/words/italian/net/programming-with-shapes/_index.md index 20a8e55555..00892bb22b 100644 --- a/words/italian/net/programming-with-shapes/_index.md +++ b/words/italian/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Utilizzando Aspose.Words per .NET e seguendo questi tutorial, imparerai a manipo | [Crea forma rettangolare in Word usando C# – Guida passo‑passo](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Scopri come creare una forma rettangolare in Word con C# tramite una guida dettagliata passo passo. | | [Tutorial Ombra Forma Aspose.Words – Aggiungi un'ombra a una forma Word in C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Scopri come aggiungere un'ombra alle forme nei documenti Word con Aspose.Words per .NET in C#. | | [Crea documento Word vuoto con forma rettangolare ombreggiata – Guida passo‑passo](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Scopri come creare un documento Word vuoto con una forma rettangolare ombreggiata usando Aspose.Words per .NET, passo dopo passo. | +| [Come spostare l'ombra in Aspose.Words – Guida completa C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Scopri come spostare l'ombra di una forma nei documenti Word usando Aspose.Words per .NET con questa guida passo passo in C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/italian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..13fc83aa0d --- /dev/null +++ b/words/italian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Come spostare l'ombra su una forma in Aspose.Words usando C#. Impara + ad aggiungere l'ombra alla forma, modificare la sfocatura, impostare la trasparenza + e ruotare l'ombra in pochi minuti. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: it +og_description: Come spostare l'ombra su una forma in Aspose.Words usando C#. Questo + tutorial ti mostra come aggiungere l'ombra a una forma, modificare la sfocatura, + impostare la trasparenza e ruotare l'ombra. +og_title: Come spostare l'ombra in Aspose.Words – Guida completa C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Come spostare l'ombra in Aspose.Words – Guida completa C# +url: /it/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come spostare l'ombra in Aspose.Words – Guida completa C# + +Ti sei mai chiesto **how to move shadow** su una forma all'interno di un documento Word senza aprire Word manualmente? Nel mio lavoro quotidiano ho spesso dovuto modificare l'ombra di una forma in modo programmatico—sia per un report curato sia per un modello dinamico. La buona notizia? Con Aspose.Words puoi farlo in poche righe, e imparerai anche **add shadow to shape**, **how to change blur**, **how to set transparency** e **how to rotate shadow** nello stesso passaggio. + +In questo tutorial percorreremo uno scenario reale: caricare un DOCX esistente che contiene già una forma, regolare la posizione, la morbidezza, l'opacità e la direzione dell'ombra, e infine salvare il risultato. Alla fine avrai uno snippet riutilizzabile da inserire in qualsiasi progetto .NET, e comprenderai perché ogni proprietà è importante. + +## Prerequisiti – Cosa ti serve prima di iniziare + +- **Aspose.Words per .NET** (versione 23.12 o successiva). Puoi ottenerlo da NuGet con `Install-Package Aspose.Words`. +- Un ambiente di sviluppo .NET 6+ (Visual Studio, VS Code, Rider—quello che preferisci). +- Un file Word di input (`input.docx`) che contiene già almeno una forma (va bene un rettangolo, un cerchio o un'immagine). +- Familiarità di base con la sintassi C#—nulla di complicato. + +Se ti manca qualcosa, fermati un attimo e installa la libreria; il resto della guida presume che il pacchetto sia già referenziato. + +## Step 1: Load the Document and Grab the Target Shape – **How to Move Shadow** Begins Here + +La prima cosa che facciamo è caricare il documento sorgente e individuare la forma che vogliamo modificare. Aspose.Words tratta ogni oggetto (paragrafi, tabelle, forme) come un nodo in un albero, quindi possiamo interrogarlo direttamente. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Why this matters:** Caricare il documento una sola volta e riutilizzare la stessa istanza `Document` è efficiente. La chiamata `GetChild` è sicura perché restituisce `null` se l'indice è fuori intervallo, consentendoci di gestire le forme mancanti in modo elegante. + +## Step 2: Adjust the Blur Radius – Master **How to Change Blur** + +Un'ombra morbida appare professionale, mentre un bordo duro può sembrare di scarsa qualità. La proprietà `BlurRadius` controlla la morbidezza in punti (1 pt ≈ 1/72 pollice). Incrementiamola a 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** La sfocatura predefinita è 0,5 pt. Qualsiasi valore superiore a 5 pt è solitamente evidente, ma attenzione a non renderla troppo grande—potrebbe far sembrare la forma staccata dalla pagina. + +## Step 3: Set Transparency – The Answer to **How to Set Transparency** + +La trasparenza determina quanto l'ombra è trasparente. Un valore di `0` significa completamente opaco; `1` significa completamente invisibile. Per un effetto delicato useremo `0.3` (30 % trasparente). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Why you might care:** Se la forma è scura, un'ombra completamente opaca può oscurare il testo sottostante. Regolare la trasparenza mantiene il documento leggibile pur aggiungendo profondità. + +## Step 4: Move the Shadow – The Core of **How to Move Shadow** + +La proprietà `Distance` definisce quanto l'ombra è spostata dalla forma, misurata in punti. Una distanza maggiore spinge l'ombra più lontano, creando un effetto più drammatico. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **What if you need a tiny offset?** Impostare `Distance` a `0` farà sì che l'ombra si trovi direttamente dietro la forma, utile per effetti di embossing. + +## Step 5: Rotate the Light Source – Solving **How to Rotate Shadow** + +Le ombre non sono solo verticali; seguono l'angolo della sorgente luminosa. La proprietà `Angle` (in gradi) ruota l'ombra attorno alla forma. Incliniamola di 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Quick experiment:** Prova `90` per un'ombra a destra o `-30` per una inclinata a sinistra. Il cambiamento visivo è immediato. + +## Step 6: Save the Document – Seeing the Result of **Add Shadow to Shape** + +Ora che abbiamo regolato l'ombra, scriveremo il documento su disco. Puoi sovrascrivere l'originale o creare un nuovo file; l'esempio utilizza un nuovo file di output. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Expected output:** Apri `output.docx`. L'ombra della forma apparirà più morbida, leggermente spostata, semi‑trasparente e inclinata a 45°. Se la confronti fianco a fianco con `input.docx`, la differenza è inconfondibile. + +### Full Working Example (Copy‑Paste Ready) + +Di seguito trovi l'intero programma in un unico blocco. Incollalo in un nuovo progetto console, sostituisci `YOUR_DIRECTORY` con un percorso di cartella reale e avvia. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Common Questions & Edge Cases + +### What if the document has multiple shapes? + +Puoi iterare su tutte le forme: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Can I add a shadow to a shape that currently has none? + +Assolutamente. L'oggetto `ShadowFormat` è sempre presente; devi solo abilitarlo: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Does this work with pictures and SmartArt? + +Sì. Qualsiasi nodo che deriva da `Shape`—incluse immagini, grafici e SmartArt—esponi `ShadowFormat`. Le stesse proprietà si applicano. + +### How do I control the shadow color? + +Usa la proprietà `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Compatibility concerns? + +Aspose.Words 23.12+ supporta .NET 6, .NET Core 3.1 e .NET Framework 4.6.2+. L'API mostrata è stabile su queste versioni. + +## Conclusion + +Abbiamo appena coperto **how to move shadow** su una forma usando Aspose.Words, e nel frattempo abbiamo dimostrato **add shadow to shape**, **how to change blur**, **how to set transparency** e **how to rotate shadow**. L'esempio completo e eseguibile ti permette di modificare l'ombra di qualsiasi forma in pochi secondi, conferendo ai tuoi documenti un aspetto curato e professionale senza mai aprire Word. + +Pronto per il passo successivo? Prova a combinare queste regolazioni dell'ombra con **conditional formatting**—ad esempio, applica un'ombra più profonda solo a titoli o a grafici che superano una certa dimensione. Oppure esplora **gradient fills** per la forma stessa per creare un design davvero accattivante. + +Se incontri problemi, lascia un commento qui sotto. Buon coding, e che le tue ombre cadano sempre esattamente dove desideri! + +![Diagramma che mostra l'effetto dello spostamento dell'ombra su una forma – esempio di come spostare l'ombra](https://example.com/images/shadow-demo.png "esempio di come spostare l'ombra") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/basic-conversions/_index.md b/words/japanese/net/basic-conversions/_index.md index 85672c5cb5..4f52e5a238 100644 --- a/words/japanese/net/basic-conversions/_index.md +++ b/words/japanese/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ | [C# で Word を PDF に変換する – ガイド](./convert-word-to-pdf-in-c-using-aspose-words-guide/) Aspose.Words for .NET を使用して C# で Word 文書を PDF に変換する方法を、ステップバイステップで解説します。コード例付きで開発者に最適です。 | | [Aspose.WordsでWordをPDFとして保存 – 完全なC#ガイド](./save-word-as-pdf-with-aspose-words-complete-c-guide/) Aspose.Words for .NET を使用して C# で Word 文書を PDF に変換する完全ガイドです。コード例付きで開発者に最適です。 | | [Aspose.WordsでDocxをPDFとして保存 – 完全なC#ガイド](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) Aspose.Words for .NET を使用して C# で Docx ファイルを PDF に変換する完全ガイドです。コード例付きで開発者に最適です。 | +| [Aspose.WordsでWordをPDFとして保存 – 完全なガイド](./save-word-as-pdf-with-aspose-words-complete-guide/) Aspose.Words for .NET を使用して Word 文書を PDF に変換する完全ガイドです。コード例付きで開発者に最適です。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/japanese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index d4d67dd8a7..9fe0668954 100644 --- a/words/japanese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/japanese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,20 @@ --- category: general -date: 2025-12-29 -description: Aspose.Words を使用して Word から LaTeX をエクスポートする方法 – Word を LaTeX に変換し、docx - を txt として保存し、プレーンテキストで数式を処理する方法を学びましょう。 +date: 2026-05-01 +description: Aspose.Words を使用して C# で Word ファイルから LaTeX をエクスポートし、Word を txt に変換し、テーブルを保持する方法を学びましょう。 draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: ja -og_description: Aspose.Words を使用して Word から LaTeX をエクスポートする方法。このガイドでは、Word を LaTeX - に変換し、docx を txt として保存し、数式をそのまま保持する方法を示します。 -og_title: WordからLaTeXをエクスポートする方法 – 簡単C#チュートリアル +og_description: WordからLaTeXをエクスポートし、Wordをプレーンテキストに変換し、テーブルのレイアウトをそのまま保持する方法をAspose.Wordsでご紹介します。 +og_title: WordからLaTeXをエクスポートする方法 – 完全なC#チュートリアル tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: WordからLaTeXをエクスポートする方法 – ステップバイステップガイド url: /ja/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,159 +24,215 @@ url: /ja/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Word から LaTeX をエクスポートする方法 – ステップバイステップガイド +# Word から LaTeX をエクスポートする方法 – 完全 C# チュートリアル -Word から LaTeX をエクスポートする方法 **how to export LaTeX from Word** を、難しい Office Math の数式を失わずにできるか疑問に思ったことはありませんか? あなただけではありません。学術論文、科学レポート、または自動出版パイプラインのために *convert Word to LaTeX* を試みると、多くの開発者が壁にぶつかります。 +Word 文書から **LaTeX をエクスポート** する方法で、数式を失わずに済むか気になったことはありませんか? あなたは一人ではありません。多くの開発者が Office Math を含む .docx をクリーンな LaTeX に変換し、さらに **Word を txt に変換** して下流処理に利用したいと考えています。このガイドでは、**テーブルを保持**しながらプレーンテキストファイルを取得し、LaTeX マークアップを必要な場所に正確に配置する実用的で実行可能なソリューションをステップバイステップで解説します。 -このチュートリアルでは、Aspose.Words を使用して **how to export LaTeX** を示す完全な実行可能 C# サンプルを順に解説し、LaTeX マークアップ付きの **how to save txt** ファイルの作成方法を説明し、さらに **convert word equations latex** の微妙な点にも触れ、翻訳時に何も失われないようにします。 - -> **Pro tip:** 同じアプローチは任意の .docx に対して機能します—コードが指すファイルパスを別のものに変えるだけです。 +ソースファイルの読み込みから `TxtSaveOptions` の調整まで、出力が人間にも機械にも扱いやすいものになるよう全てを網羅します。最後まで読めば、**docx を txt として保存**、**Word をプレーンテキストに変換**、そして **テーブルを保持する方法** がマスターできます。外部スクリプトや手動コピーは不要です。純粋な C# コードだけで、任意の .NET プロジェクトに組み込めます。 ## 必要なもの -本題に入る前に、以下の前提条件が揃っていることを確認してください。 - -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words は最新の .NET ランタイムを対象としています。 | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | このライブラリは Word の解析と LaTeX の出力という重い処理を担います。 | -| **A sample .docx** containing at least one Office Math equation | LaTeX 変換の動作を確認するためです。 | -| **Visual Studio 2022** (or any IDE you like) | サンプルのデバッグと実行が簡単になります。 | +- **Aspose.Words for .NET**(最新バージョン、2024.x 以降)。NuGet パッケージは `Aspose.Words`。 +- .NET 開発環境(Visual Studio、VS Code、Rider など)。 +- Office Math の数式と少なくとも 1 つのテーブルを含む Word ファイル(`.docx`)。テーブル保持の効果を確認するために必要です。 -まだ NuGet パッケージをインストールしていない場合は、次を実行してください: - -```bash -dotnet add package Aspose.Words -``` +以上です。すでに揃っている方はそのまま読み進めてください。まだの場合は NuGet パッケージとサンプル DOCX を入手してから続行しましょう。 -以上です—余分な DLL や COM 相互運用は不要で、クリーンなマネージド ライブラリだけです。 - -## Word から LaTeX をエクスポートする方法 – 概要 - -以下は、実現する全体像です: +--- -1. **Load** ソースの Word ドキュメント(`.docx`)を読み込みます。 -2. **Configure** `TxtSaveOptions` を設定し、すべての Office Math オブジェクトが LaTeX コードとして出力されるようにします。 -3. **Save** ドキュメントをプレーンテキスト(`.txt`)ファイルとして保存し、任意の LaTeX コンパイラに直接入力できます。 +## Word 文書から LaTeX をエクスポートする方法 -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") +以下はチュートリアルの核心部分です。**LaTeX をエクスポートする方法** と同時に、**Word を txt に変換**、**Word をプレーンテキストに変換**、**docx を txt として保存**、そして **テーブルを保持する方法** を実現する 3 つの簡潔な手順です。 -## 手順 1: Word ドキュメントを読み込む +### 手順 1: DOCX ファイルを読み込む -まず最初に、変換したい .docx を開きます。`Document` クラスは基盤となる XML を抽象化し、使いやすいオブジェクトモデルを提供します。 +まず Word 文書を `Aspose.Words.Document` オブジェクトに読み込みます。この手順は、後で **Word を txt に変換** または **docx を txt として保存** を行う場合でも同じです。 ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Why this matters:** -ファイルを早めに読み込むことで、シリアライズ方法を決める前に内容(例: 数式の数)を検査できます。ファイルが破損している場合、`Document` は明確な例外をスローし、後で不明な出力になるのを防ぎます。 +> **重要ポイント:** ファイルを読み込むことで、段落・テーブル・Office Math オブジェクトを含むすべての Word 要素がメモリ上に表現されます。このオブジェクトがなければエクスポートオプションを操作できません。 -## 手順 2: LaTeX エクスポート用に TxtSaveOptions を設定する +### 手順 2: LaTeX とテーブルレイアウト用に `TxtSaveOptions` を設定する -`TxtSaveOptions` で魔法が起きます。`OfficeMathExportMode` を `LaTeX` に設定することで、すべての Office Math オブジェクトが対応する LaTeX 表現に変換されます。 +`TxtSaveOptions` クラスを使うと、プレーンテキストファイルの生成方法を細かく制御できます。今回のシナリオで重要になるプロパティは次の 2 つです。 + +| プロパティ | 説明 | 必要な理由 | +|----------|------|------------| +| `OfficeMathExportMode` | Office Math のレンダリング方法を決定します。`LaTeX` に設定すると数式が LaTeX 構文に変換されます。 | これが **LaTeX をエクスポートする方法** の核心です。 | +| `PreserveTableLayout` | `true` にすると、Aspose が空白を追加してテーブルがグリッド状に見えるようにします。 | **テーブルを保持する方法** を満たしつつ、**Word を txt に変換** が可能になります。 | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Why we choose these settings:** -- `OfficeMathExportMode.LaTeX` は、正確な数式変換を保証する唯一のモードです。 -- `PreserveTableLayout` はテーブルを Word と同じ見た目に保ち、後で LaTeX の `tabular` 環境に埋め込む際に便利です。 -- UTF‑8 は “α”、 “β”、 “∑” などの文字が往復しても失われないことを保証します。 - -プレーンテキストラッパーなしで **convert word to latex** が必要な場合は、代わりに `SaveFormat.LaTeX` に切り替えることができます—高度なシナリオ向けのちょっとしたヒントです。 +> **プロのコツ:** 生の LaTeX だけが欲しくてテーブルの書式が不要な場合は、`PreserveTableLayout` を `false` に設定してください。ファイルは小さくなりますが、テーブルの視覚的手がかりは失われます。 -## 手順 3: ドキュメントをテキストファイルとして保存する +### 手順 3: ドキュメントをプレーンテキストとして保存する -これで LaTeX が豊富に含まれたテキストをディスクに書き込みます。生成された `.txt` は後で `.tex` にリネームできるか、直接 LaTeX コンパイラにパイプできます。 +ここまでで定義したオプションを使い、`.txt` ファイルに書き出します。この 1 行で **Word をプレーンテキストに変換**、**docx を txt として保存**、そしてもちろん **LaTeX をエクスポートする方法** が一度に実現します。 ```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` + +呼び出しが完了したら `output.txt` を開いてください。次のようになっているはずです。 -// Save using the configured options -doc.Save(outputPath, txtOptions); +- 各 Office Math 数式が `\frac{a}{b}` などの LaTeX スニペットに変換されています。 +- テーブルは `|` と `-` 文字で描画され、列の揃いが保持されています。 +- 通常の段落はプレーンテキストとして出力され、下流パーサーがすぐに利用できます。 -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +### 完全動作サンプル + +すべてをまとめた、今日すぐにコンパイルして実行できる自己完結型プログラムです。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**output.txt に表示される内容:** +**期待される出力**(抜粋): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -他のすべての段落はプレーンテキストとして表示され、Office Math の数式は LaTeX の `equation` 環境(インラインの場合は `inline`)でラップされます。これにより **convert word equations latex** の要件が完全に満たされます。 +テーブルがグリッドを保ち、数式がきれいな LaTeX で出力されているのが分かります。これが **Word を txt に変換** しつつ、構造と数式の両方を忠実に表現できるポイントです。 -## エッジケースとよくある質問 +--- -| 状況 | 対処方法 | -|-----------|------------| -| **No equations in the source** | 変換は依然として機能し、プレーンテキストが得られます。余分な LaTeX コードは追加されません。 | -| **Very large documents (>100 MB)** | `MemoryStream` を使用して出力をストリーミングし、メモリ使用量を抑えることを検討してください。 | -| **Unsupported Math constructs** | Aspose.Words は Office Math の 99 % をカバーしています。稀なエッジケースでは、LaTeX を手動で後処理する必要があるかもしれません。 | -| **Need a .tex file instead of .txt** | `outputPath` を `.tex` で終わるように変更し、必要に応じて `txtOptions.Encoding` を `Encoding.UTF8` に設定してください。 | -| **Running on Linux/macOS** | コードは同じまま動作します—ファイルパスがスラッシュ(/)または `Path.Combine` を使用していることを確認してください。 | +## Word を TXT に変換しテーブルを保持するためのヒント -## LaTeX 数式付き TXT を保存する方法 – クイックまとめ +3 ステップのアプローチは多くの場合で機能しますが、実務では様々な課題が出てきます。以下は **Word をプレーンテキストに変換** パイプラインを堅牢にする実用的な提案です。 -1. **Load** .docx(`Document`)を読み込む。 -2. **Set** `TxtSaveOptions` で `OfficeMathExportMode = LaTeX` を設定する。 -3. **Save** それらのオプションを使用してファイル(`doc.Save`)を保存する。 +### エンコーディングを統一する -これが LaTeX 形式の数式を含む **how to save txt** ファイルを作成する全体のワークフローです。 +`TxtSaveOptions` のデフォルトは UTF‑8 で、ほとんどの文字を扱えます。レガシーシステムが Windows‑1252 など別のコードページを要求する場合は、`Encoding` プロパティを設定してください。 -## ボーナス: 複数ファイルの変換を自動化する +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -Word 文書が入ったフォルダーがある場合、上記のロジックをシンプルなループでラップしてください: +### 余分な空白を削除する + +列数が多いテーブルは長い行になることがあります。保存後に、複数のスペースをタブ 1 つに置き換える後処理を行うと見やすくなります。 ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### 入れ子テーブルに対応する + +DOCX にテーブルの中にテーブルがある場合、`PreserveTableLayout` は視覚的階層を保ちますが、インデントが不自然になることがあります。簡易的な対策として、先頭の空白をカスタムマーカー(例: `>>`)に置き換えると、下流パーサーがネストレベルを検出しやすくなります。 - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +### 複数ファイルを一括処理する + +数十件の文書を **Word を txt に変換** したい場合は、ロジックをループで包みます。 + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -これで **convert word to latex** を一括で実行でき、毎日多数の原稿を受け取る研究グループに最適です。 +これで **docx を txt として保存** を手動作業なしで大量に実行できます。 + +--- + +## よくある落とし穴と回避策 + +1. **LaTeX エクスポートモードの未設定** – `OfficeMathExportMode = OfficeMathExportMode.LaTeX` を忘れると、数式は「Equation 1」などのプレーンテキストにフォールバックします。オプションブロックは必ず確認してください。 +2. **テーブルレイアウトが失われる** – デフォルトは `PreserveTableLayout = false` です。出力が文字の塊になっている場合はフラグがオフになっている可能性があります。 +3. **スペースを含むファイルパス** – 生文字列 (`@"C:\My Folder\input.docx"`) を使うとエスケープ問題を回避できます。さもなくば `FileNotFoundException` が発生します。 +4. **バージョン不一致** – 古い Aspose.Words(21.9 未満)では `OfficeMathExportMode` がサポートされていません。最新パッケージにアップグレードして **LaTeX をエクスポートする方法** を有効にしてください。 +5. **非 ASCII 文字のエンコーディングエラー** – `�` が表示されたら、`options.Encoding` を明示的に UTF‑8 もしくは適切なコードページに設定してください。 + +--- + +## ソリューションの拡張: TXT から Markdown や HTML へ + +時にはプレーンテキスト以上の出力が必要になることがあります。たとえば LaTeX ブロックを保持した Markdown ファイルが欲しい場合です。その際は `TxtSaveOptions` を `HtmlSaveOptions` や `MarkdownSaveOptions` に差し替えるだけです。 + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +この小さな変更で **Word を txt に変換** スタイルの出力を保ちつつ、好きな Markdown 構文で保存できます。 + +--- + +## まとめ -## 結論 +本稿では **Word から LaTeX をエクスポートする方法** を完全に実装した手順を紹介し、同時に **Word を txt に変換**、**Word をプレーンテキストに変換**、**docx を txt として保存**、そして **テーブルを保持する方法** も網羅しました。重要なポイントは次の通りです。 -私たちは **how to export LaTeX from Word** をステップバイステップで解説し、すべての Office Math 数式を保持した **how to save txt** ファイルの作成方法を示し、さらに **convert word equations latex** を忠実に行う方法も紹介しました。 +- `Aspose.Words.Document` で DOCX を読み込む。 +- `TxtSaveOptions.OfficeMathExportMode = LaTeX` と `PreserveTableLayout = true` を設定する。 +- `doc.Save(outputPath, options)` で LaTeX を含むクリーンなプレーンテキストファイルを取得する。 -数行の C# と強力な Aspose.Words ライブラリだけで、任意の .docx を LaTeX 準備済みテキストに変換でき、科学論文、教科書、または自動出版パイプラインに組み込むことができます。 +自分のファイルで試し、エンコーディング調整やバッチ処理を実装してみてください。入れ子テーブルや特殊文字、古い Aspose バージョンといったエッジケースに直面したら、上記「ヒント」や「落とし穴」セクションを参照すればすぐに対処できます。 -**Next steps?** 生成された `.txt`(または `.tex` にリネーム)を `pdflatex` や `xelatex` に入力して PDF を生成してみてください。また、直接 `.tex` ファイルを得るために `SaveFormat.LaTeX` オプションを試すこともできます。書式を保持しながら **save docx as txt** が必要な場合は、`PreserveTableLayout` とカスタム改行処理を実験してみてください。 +次のステップに進みませんか? 同じ DOCX を Markdown に変換したり、生成した `.txt` を LaTeX をウェブ上でレンダリングできる静的サイトジェネレータに流し込んだりしてみましょう。可能性は無限大です。これで **Word を txt に変換** ワークフローの堅実な基盤が手に入りました。 -エッジケース、ライセンス、パフォーマンス調整に関する質問がありますか?以下にコメントを残してください—ハッピーコーディング! +Happy coding, and may your LaTeX always compile on the first try! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/japanese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/japanese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..a98b55c28c --- /dev/null +++ b/words/japanese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-01 +description: C#でAspose.Wordsを使用してWordをPDFとして保存する。docxをPDFに変換し、欠落フォントを検出し、フォント置換の警告を効率的に処理する方法を学びましょう。 +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: ja +og_description: Aspose.Words を使用して Word を PDF に保存します。このステップバイステップのチュートリアルでは、docx を + PDF に変換し、欠落フォントを検出する方法を示します。 +og_title: Aspose.WordsでWordをPDFに保存する完全ガイド +tags: +- Aspose.Words +- C# +- PDF conversion +title: Aspose.WordsでWordをPDFに保存する – 完全ガイド +url: /ja/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.WordsでWordをPDFとして保存 – 完全ガイド + +Word をその場で **PDF に保存** したいとき、フォントが欠けていないか心配したことはありませんか? 開発者はドキュメント変換時にフォント欠損の問題に常に直面しています。このガイドでは、**docx を pdf に変換** するだけでなく、Aspose.Words のフォント置換警告を利用して **欠損フォントを検出** するハンズオンの解決策をご紹介します。 + +警告コレクターの設定から出力の解釈まで、すべてを網羅しますので、最後には **Word を PDF として保存** する際に予期せぬ問題が起きないことを確実に把握できます。外部ツール不要、設定も難解ではありません。任意の .NET プロジェクトに貼り付けられるシンプルな C# コードだけです。 + +## 必要なもの + +- **Aspose.Words for .NET**(最新バージョン、例: 24.10) – NuGet で取得できます(`Install-Package Aspose.Words`)。 +- .NET 開発環境(Visual Studio、Rider、または VS Code で OK)。 +- ターゲットマシンにインストールされていないフォントが含まれる可能性のあるサンプル DOCX ファイル。 +これだけです。上記が揃っていれば、すぐに始められます。 + +## Word を PDF として保存 – 手順概要 + +以下はフルで実行可能なプログラムです。コンソールアプリプロジェクトに貼り付けて **F5** を押すだけで動作します。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **プロのコツ:** `YOUR_DIRECTORY` を絶対パスに置き換えるか、`Path.Combine(Environment.CurrentDirectory, "input.docx")` を使用して相対パスで安全に指定してください。 + +### なぜ Warning Callback を使うのか + +Aspose.Words は欠損フォントを自動的にフォールバック(通常は Arial)に置き換えます。コールバックがなければ置換が行われたことに気付かず、生成された PDF のレイアウトが崩れる原因になります。`IWarningCallback` をフックすることで、欠損フォントが発生したすべてのイベントをプログラム的に取得でき、ログ出力やエンドユーザーへの通知に最適です。 + +### 欠損フォントの検出 – 確認ポイント + +プログラムを実行すると、欠損フォントがある場合はコンソールに次のような行が出力されます。 + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +リストが空であれば、**Word を PDF として保存** がすべての元フォントを保持した状態で成功したことになります。 + +## Docx を PDF に変換 – 出力のカスタマイズ + +PDF のバージョン、画像品質、コンプライアンスレベルを指定したいことがあります。Aspose.Words では `PdfSaveOptions` オブジェクトを `Save` 呼び出し前に調整できます。 + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **重要ポイント:** 法的アーカイブ用に PDF を生成する場合、`PdfA1b` を設定すると厳格な規格に準拠したファイルになります。この変換でも警告コールバックは機能し続けるため、**欠損フォントの検出** はそのまま行えます。 + +## Aspose Words フォント置換 – エッジケースの対処 + +### シナリオ 1: 複数の欠損フォント + +ソース文書で複数のカスタムフォントが使用されている場合、警告コレクターにはフォントごとにエントリが作られます。これらを集計する例です。 + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### シナリオ 2: フォールバックフォントディレクトリの指定 + +Aspose.Words は追加フォルダーからフォントを検索できます。`FontSettings` の `FontsFolder` プロパティを文書読み込み前に設定します。 + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +これにより、ライブラリはまずカスタムフォルダーを検索し、不要な置換が起きる可能性を減らします。 + +### シナリオ 3: 置換を無視する + +フォントが欠損している場合に変換を失敗させたい(静かに置換されるのを防ぎたい)場合は、コールバック内で例外をスローします。 + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +これにより、フォント欠損を解消してからでなければ処理が進まないようにでき、CI パイプラインなどでサイレント失敗を防げます。 + +## エンドツーエンドの完全例 + +すべてをまとめたコンパクト版です。**Word を PDF に変換** し、カスタム PDF オプションを設定し、フォント問題をログに記録します。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**期待されるコンソール出力**(Calibri が欠損している場合): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +警告が出なければ、**Word を PDF として保存** が元の DOCX と同一フォントで実行されたことになります。 + +## ビジュアルサマリー + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*画像代替テキスト:* **save word as pdf** ワークフロー(ロード、警告収集、PDF 出力)を示す図。 + +## よくある質問 & 回答 + +| 質問 | 回答 | +|----------|--------| +| **Aspose.Words のライセンスは必要ですか?** | 無料の評価ライセンスでテストは可能ですが、本番環境では評価透かしを除去するために有料ライセンスが必要です。 | +| **.NET Core / .NET 6+ でも動作しますか?** | はい。Aspose.Words は .NET Standard 2.0 を対象としているため、最新の .NET ランタイムでも問題なく動作します。 | +| **複数の DOCX ファイルをループで変換できますか?** | できます。各ファイルごとに新しい `Document` をインスタンス化し、必要なら同じ `WarningInfoCollector` を再利用して結果を集約してください。 | +| **出力フォルダーが存在しない場合はどうなりますか?** | `Document.Save` は `DirectoryNotFoundException` をスローします。事前にフォルダーを作成するか、`Directory.CreateDirectory` を使用してください。 | +| **欠損フォントを PDF に埋め込む方法はありますか?** | 利用可能なフォントがマシンにあれば、`PdfSaveOptions.EmbedFullFonts = true` を設定するだけで自動的に埋め込まれます。 | + +## 結論 + +これで **Word を PDF として保存** しながら **欠損フォントを検出** し、**Aspose.Words のフォント置換** シナリオに対応できる、実務レベルのパターンが手に入りました。警告コールバックの設定、フォントフォルダーのカスタマイズ、必要に応じた `PdfSaveOptions` の調整により、**docx を pdf に変換** しつつレイアウト忠実度に関する問題をユーザーに確実に通知できます。 + +次のステップに進みませんか?複数文書を並列で PDF に変換したり、透かしやデジタル署名の追加に挑戦してみましょう。どちらも今回習得したコードをベースに簡単に拡張できます。コーディングを楽しんで、PDF が常に意図した通りに表示されますように! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-loadoptions/_index.md b/words/japanese/net/programming-with-loadoptions/_index.md index cdd84e53cd..83725b3c86 100644 --- a/words/japanese/net/programming-with-loadoptions/_index.md +++ b/words/japanese/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Aspose.Words for .NET チュートリアルは、LoadOptions を用いた Words | [C# で Aspose.Words を使用して Word 文書を復元する](./recover-word-document-with-aspose-words-in-c/) Aspose.Words for .NET を使用し、C# で破損した Word 文書を復元する手順をステップバイステップで解説します。 | | [Aspose.Words で LoadOptions を使用する方法 – 完全ガイド](./how-to-use-loadoptions-in-aspose-words-complete-guide/) Aspose.Words の LoadOptions を活用して、文書読み込みや設定を詳細に解説する包括的なステップバイステップガイドです。 | | [C# で破損した文書を復元 – 復元モードを設定しユーザーに促す](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) Aspose.Words for .NET の LoadOptions を使用し、破損した文書を復元モードで読み込み、ユーザーに復元を促す手順を解説します。 | +| [破損したdocxの復元 – C#で損傷したWordファイルを読み込む完全ガイド](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) Aspose.Words for .NET を使用して、破損した docx ファイルを C# で安全に読み込み、復元する手順をステップバイステップで解説します。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/japanese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..96b91c46d1 --- /dev/null +++ b/words/japanese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words を使用して破損した docx ファイルを迅速に復元します。復元モードの設定方法、docx の安全な読み込み方法、そして数ステップで損傷した + Word ファイルを読む方法を学びましょう。 +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: ja +og_description: C#で破損したdocxファイルを復元します。リカバリモードを設定し、docxを安全にロードし、Aspose.Wordsで損傷したWordファイルを読み取ります。 +og_title: 破損したdocxの復元 – 簡単C#ガイド +tags: +- Aspose.Words +- C# +- Document Recovery +title: 破損したdocxを復元 – C#で損傷したWordファイルを読み込む完全ガイド +url: /ja/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Corrupted docx の復元 – 簡単 C# ガイド + +Word ファイルが開けず、内容が永遠に失われたのではないかと不安になったことはありませんか?実務では、ユーザーに添付ファイルを再送させることなく **recover corrupted docx** ファイルを復元することがよくあります。嬉しいことに Aspose.Words を使えばそれがとても簡単です。リカバリーモードを設定し、ライブラリに任せるだけです。 + +このチュートリアルでは、**recover corrupted docx** ファイルを復元する具体的な手順を解説し、`RecoveryMode.AutoRecover` オプションが最も安全な選択である理由を説明し、部分的に破損した **how to load docx** ファイルの読み込み方法を示します。最後まで読めば、破損した Word ファイルを読み取り、残っているテキストを抽出し、将来の監査用に元の形式をログに残すことができます。外部ツールは不要、純粋な C# コードだけです。 + +## 必要なもの + +- **Aspose.Words for .NET**(最新バージョンならどれでも可;本チュートリアルの API は 23.5 以降で動作します) +- .NET 開発環境(Visual Studio、VS Code、Rider のいずれか) +- 復元したい破損または部分的に損傷した `.docx` ファイル + +特別な権限や COM インターロップは不要ですし、サーバーに Microsoft Office をインストールする必要もありません。シンプルですよね? + +## 手順 1: リカバリーモードを Auto‑Recover に設定 + +Word ファイルが壊れていると、デフォルトの読み込み動作では例外がスローされて処理が中断します。`LoadOptions` オブジェクトを構成して Aspose.Words に **set recovery mode** を `AutoRecover` に設定させると、ZIP パッケージを走査し、読めない部分をスキップして可能な限りのデータを組み立て直します。 + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **なぜ AutoRecover か?** +> 可能な限り多くの情報を読み取りつつ、ドキュメントオブジェクトを使用可能な状態に保ちます。`RecoveryMode.NoRecovery` を選択すると、最初の破損箇所で読み込みが失敗し、**recover corrupted docx** シナリオの目的が失われます。 + +## 手順 2: 設定したオプションでドキュメントを読み込む + +リカバリーモードを設定したら、安心してファイルを開くことができます。`"YOUR_DIRECTORY/input.docx"` を実際の破損ファイルへのパスに置き換えてください。 + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +ファイルが部分的にしか破損していなければ、`Document` インスタンスは依然として生成されます。追加の検証が必要な場合は、後で `document.IsStructureValid` を確認できます。 + +## 手順 3: 検出されたフォーマットを確認 + +Aspose.Words は自動的に元のフォーマット(DOC、DOCX、ODT など)を検出します。この値を出力すると、**recover corrupted docx** 後にライブラリが正しくファイルを認識したかをすぐに確認でき、簡易的なサニティチェックになります。 + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +典型的な出力例: + +``` +Loaded with Docx format. +``` + +たとえ一部が欠落していても、フォーマット検出は成功します—**recover corrupted docx** ワークフローにとってもう一つの利点です。 + +## 手順 4: 取得できるものを抽出 + +ドキュメントが読み込めたら、通常の Word ファイルと同様に扱えます。以下はプレーンテキストを抽出しコンソールに出力するコンパクトな例です。これにより、**read damaged word file** の内容をクラッシュせずに取得できることが示せます。 + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +元のファイルにテーブルや画像があり、それらが破損していた場合はテキスト出力から除外されます。残りの本文はそのまま残ります。 + +## 手順 5: クリーンなコピーを保存(任意) + +復元後にユーザーへ新しいクリーン版ファイルを提供したいことが多いでしょう。同じフォーマットで保存すれば、下流のプロセスとの互換性が保たれます。 + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +これで **recover damaged docx** ファイルが完成し、メールに添付したり別サービスに渡したりできるようになります。 + +## 完全動作サンプル + +すべてをまとめた、すぐに実行可能なプログラムです。新しいコンソールプロジェクトに貼り付け、ファイルパスを調整して F5 キーで実行してください。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**期待される出力**(ファイルに単一段落「Hello world!」と一部破損した XML が含まれる場合): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +ソースファイルが部分的に壊れていても、プログラムは決してクラッシュしません。これが Aspose.Words を使った **recover corrupted docx** の本質です。 + +## よくある質問とエッジケース + +### ファイルが完全に読めない場合は? + +`AutoRecover` でも限界があります。ZIP コンテナ自体が修復不能なほど破損している場合、Aspose.Words は `CorruptedFileException` をスローします。その際は、**recover corrupted docx** を再試行する前にサードパーティ製の ZIP 修復ツールを使用する必要があります。 + +### 他のフォーマット(例: `.doc`, `.odt`)も復元できる? + +もちろんです。同じ `LoadOptions` が Aspose.Words がサポートするすべてのフォーマットで機能します。拡張子を変更すれば、ライブラリが自動的に元のフォーマットを検出します。したがって、`.doc` や `.rtf` といった **recover damaged docx** に似たファイルも同一コードで復元可能です。 + +### 大容量ドキュメントをメモリに全部読み込まずに処理したい場合は? + +ギガバイト級のファイルでは、`LoadOptions.LoadFormat` などのオプションを有効にしたり、ページ単位でストリーミングしたりできます。ただし、リカバリーアルゴリズム自体はパッケージ全体を読む必要があるため、非常に大きな破損ファイルではメモリ使用量が増加する点に留意してください。 + +### 失われた部分を把握する方法は? + +読み込み後、`document.GetChildNodes(NodeType.Any, true)` を調べて期待されるノード数と比較できます。テーブル、画像、ヘッダーなどが欠落していればノードコレクションに存在しません。これにより、**recover damaged docx** で失われた要素を正確にログに記録し、ユーザーに通知できます。 + +## 信頼性の高い復元のためのプロティップ + +- 読み込む前に **入力ファイルサイズを検証** してください。0 バイトのファイルは必ず失敗します。 +- `DocumentLoadingException` をキャッチし、例外メッセージを保存して **RecoveryMode** の結果をログに残すと、どの部分がスキップされたかの手がかりが得られます。 +- Web サービスでアップロードを処理する場合は、**バックグラウンドスレッドで復元を実行** し、リクエストの応答性を保ちましょう。 +- 復元後のファイルと元ファイルのハッシュ(例: MD5)を比較する **チェックサム** を組み合わせれば、差分があるかどうかを判定でき、必要に応じて両方のバージョンを保持できます。 + +## 結論 + +C# で **recover corrupted docx** ファイルを **set recovery mode** を `AutoRecover` に設定し、安全にドキュメントを読み込み、残存テキストを抽出し、必要に応じてクリーンコピーを保存する方法をご紹介しました。この手法により、**how to load docx** で例外が発生するようなファイルでも安全に処理でき、外部ツールに頼らず **read damaged word file** の内容を取得できます。 + +次のステップは?`RecoveryMode.AutoRecover` を `RecoveryMode.NoRecovery` に差し替えて挙動の違いを確認したり、パスワード処理やフォント置換を制御する `LoadOptions` のプロパティを試したりしてください。また、アップロードを受け取り修復済みファイルを返す ASP.NET Core API に組み込めば、エンタープライズ向け文書管理パイプラインに最適です。 + +Word 文書の復元についてさらに質問がある、あるいはカスタムコールバックで **recover damaged docx** ファイルを実装したい方は、下のコメント欄にご投稿ください。Happy coding! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-markdownsaveoptions/_index.md b/words/japanese/net/programming-with-markdownsaveoptions/_index.md index 353fd34e79..14bcaa0ec1 100644 --- a/words/japanese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/japanese/net/programming-with-markdownsaveoptions/_index.md @@ -41,6 +41,7 @@ MarkdownSaveOptions を使用した Words Processing は、Aspose.Words for .NET | [DOCX を Markdown に変換する際の画像リネーム方法](./how-to-rename-images-when-converting-docx-to-markdown/) Aspose.Words for .NET を使用して、DOCX から Markdown へ変換する際に画像ファイル名を自動的に変更する手順を解説します。 | | [Aspose.Words を使用して docx を Markdown に保存 – 完全 C# ガイド](./save-docx-as-markdown-with-aspose-words-full-c-guide/) Aspose.Words for .NET を使い、docx ファイルを Markdown 形式に変換して保存する完全な C# 手順を解説します。 | | [Word 画像を保存 – Aspose を使用して Word を Markdown に変換](./save-word-images-convert-word-to-markdown-with-aspose/) Aspose.Words for .NET を使用して、Word 文書の画像を抽出し、Markdown 形式に変換する方法をステップバイステップで解説します。 | +| [docx を Markdown に保存 – Aspose.Words で Word の数式を LaTeX にエクスポート](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) Aspose.Words for .NET を使用して、docx 内の数式を LaTeX にエクスポートし、Markdown に保存する手順を解説します。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/japanese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..e6aefbd716 --- /dev/null +++ b/words/japanese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words を使用して docx を markdown に保存 – Word を markdown に変換し、数式を LaTeX + にエクスポートし、markdown の画像解像度を設定するスムーズなワークフローを学びましょう。 +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: ja +og_description: Aspose.Wordsでdocxをmarkdownとして保存します。このチュートリアルでは、Wordをmarkdownに変換する方法、数式をLaTeXにエクスポートする方法、そしてmarkdown画像の解像度を設定する方法を示します。 +og_title: docx を markdown に保存 – Word の数式を LaTeX にエクスポートする完全ガイド +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx を markdown として保存 – Aspose.Words で Word の数式を LaTeX にエクスポート +url: /ja/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx を markdown として保存 – Aspose.Words で Word Math を LaTeX にエクスポート + +Office Math の数式を鮮明に保ったまま **docx を markdown として保存** したいことはありませんか? あなただけではありません。多くの開発者が、既定の変換で数式がぼやけた画像として落ち込み、手作業で LaTeX に書き直すという壁にぶつかります。 + +良いニュースです:Aspose.Words がその重い作業を代行してくれます。このチュートリアルでは **word を markdown に変換** し、エンジンに **数式を LaTeX にエクスポート** させ、さらに文書全体の **markdown 画像解像度を設定** します。最後には、LaTeX 対応の数式と高解像度画像を含むクリーンな `.md` ファイルを出力する単一コマンドが手に入ります。 + +## 学べること + +- Office Math オブジェクトを含む `.docx` の読み込み方法。 +- **数式を LaTeX にエクスポート** と **markdown 画像解像度を設定** を制御する `MarkdownSaveOptions` プロパティ。 +- 任意の .NET プロジェクトに貼り付け可能な、完全に実行可能な C# スニペット。 +- フォントが欠如している、またはサポート外の数式機能があるといった一般的な落とし穴のトラブルシューティングのコツ。 + +**前提条件**:.NET 6+(または .NET Framework 4.6+)、Aspose.Words for .NET のライセンス、C# の基本的な知識。コンソールアプリの作成に慣れていればすぐに始められます。 + +--- + +## Step 1 – Save docx as markdown: Load Your Word File + +最初に必要なのは、ソースとなる `.docx` を指す `Document` オブジェクトです。本の章をコピーし始める前に本を開くイメージです。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*なぜ重要か*:文書に数式が含まれていない場合、**数式を LaTeX にエクスポート** のステップは何もしませんが、残りの変換は実行されます。このチェックにより、出力された Markdown に LaTeX ブロックが欠けている原因をすぐに特定できます。 + +--- + +## Step 2 – Configure Export Equations to LaTeX + +Aspose.Words では Office Math のレンダリング方法を選択できます。既定では PNG 画像に変換されるため、多くのチュートリアルで粒状の markdown ファイルが生成されます。`OfficeMathExportMode` を `LaTeX` に切り替えると、クリーンでコピー&ペースト可能な数式が得られます。 + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*なぜ `OfficeMathExportMode.LaTeX` か*:LaTeX は科学出版の共通言語です。後で静的サイトジェネレータや Jupyter Notebook で markdown をレンダリングすると、数式は任意のズームレベルで鮮明に表示されます。 + +--- + +## Step 3 – Set Markdown Image Resolution (for Non‑Math Content) + +数式に注目していますが、ほとんどの Word 文書には画像、チャート、埋め込み SVG も含まれます。`ImageResolution` プロパティは Aspose.Words がこれらのアセットをラスタライズする解像度を制御します。**300 DPI** が画面表示と印刷のバランスの取れた設定です。 + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*プロのコツ*:markdown をウェブ上だけで表示する場合は、ファイルサイズ削減のために 150 DPI に下げても構いません。逆に印刷用 PDF を作成する場合は、600 DPI に上げると良いでしょう。 + +--- + +## Step 4 – Run the Conversion – Convert Word Math LaTeX + +すべての設定が完了したら、実際の変換はたった一行です。Aspose.Words が裏で重い処理を行います。 + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**期待される出力**:生成された `.md` ファイルを開くと、次のようになっているはずです。 + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +PNG スニペットが置き換えられ、LaTeX ブロック(`$...$` と `$$...$$`)が表示されます。下部の画像は依然として PNG ですが、要求通り 300 DPI でレンダリングされています。 + +--- + +## Step 5 – Common Edge Cases & How to Handle Them + +| 状況 | 発生すること | 対処方法 | +|-----------|--------------|------------| +| **フォントが欠如**(例:Cambria Math がインストールされていない) | LaTeX 出力に不明な記号が含まれる可能性があります。 | サーバーに欠如フォントをインストールするか、変換前に文書に埋め込んでください。 | +| **複雑な数式**(カスタム区切り子を持つ行列など) | `LaTeX` モードでも画像にフォールバックすることがあります。 | 最新の Aspose.Words バージョンにアップグレードしてください。ライブラリは継続的に数式カバレッジを改善しています。 | +| **大容量文書**(> 50 MB) | メモリ圧迫により `OutOfMemoryException` が発生することがあります。 | `LoadOptions` に `LoadFormat.Docx` を指定してストリームで読み込むか、変換前に文書をセクションに分割してください。 | +| **画像サイズが大きすぎる** | Markdown ファイルが巨大化し、静的サイトのビルドが遅くなります。 | ウェブ専用シナリオでは `ImageResolution` を 150 DPI に下げてください(Step 3 参照)。 | + +--- + +## Step 6 – Put It All Together: Full Working Example + +以下は **Program.cs** にそのまま貼り付け可能な *完全版* コンソールアプリです。これまで説明したすべての要素に加えて、簡単なエラーハンドリングも含んでいます。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +プログラムを実行(`dotnet run`)すると、**docx を markdown として保存** しつつ、すべての数式が LaTeX として保持された markdown ファイルが生成されます。手動でのコピー&ペーストや、数式用の醜いラスタ画像は不要です。 + +--- + +## Conclusion + +Aspose.Words を使って **docx を markdown として保存** する一連の手順を、Word ファイルの読み込みから **数式を LaTeX にエクスポート**、**markdown 画像解像度を設定** するまで解説しました。最終スニペットは本番環境でも使用でき、**word を markdown に変換** したい任意の .NET プロジェクトにすぐ組み込めます。 + +次のステップは? 生成された `.md` を Hugo や Jekyll といった静的サイトジェネレータに流し込み、数式が美しくレンダリングされる様子を確認してください。**word math latex を他フォーマット(PDF、HTML)に変換**したい場合は、`MarkdownSaveOptions` を `PdfSaveOptions` や `HtmlSaveOptions` に置き換えるだけで、同じ `OfficeMathExportMode` フラグが機能します。 + +Word ファイルを Azure Blob ストレージから取得したり、API からストリームで受け取ったりするようなワークフローでも、同様のパターンが適用できます。`Document` コンストラクタをストリーム版に差し替えるだけです。 + +ぜひ色々試してみて、コメントでこの手法がどのように変換の悩みを解決したか教えてください。Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-pdfsaveoptions/_index.md b/words/japanese/net/programming-with-pdfsaveoptions/_index.md index df73038206..3e68f50ec3 100644 --- a/words/japanese/net/programming-with-pdfsaveoptions/_index.md +++ b/words/japanese/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ Word文書をPDFに変換してオンライン配信、アーカイブ、印刷 | [PDF ドキュメントで 3D DML 3DEffects をレンダリングする](./dml-3deffects-rendering/) この包括的なステップバイステップ ガイドでは、Aspose.Words for .NET を使用して PDF ドキュメントで魅力的な 3D DML 効果をレンダリングする方法を学習します。 | | [PDF文書内の画像を補間する](./interpolate-images/) Aspose.Words for .NET を使用してPDFドキュメント内の画像を補間する方法を、ステップバイステップガイドで学びましょう。PDFの画像品質を簡単に向上させることができます。 | | [Aspose.Words を使用して docx を PDF に保存する完全な C# ガイド](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) Aspose.Words を使用して docx を PDF に変換する完全な C# ガイドです。ステップバイステップで実装方法を解説します。 | +| [Aspose.Words を使用してドキュメントを PDF として保存する – 完全な C# ガイド](./save-document-as-pdf-with-aspose-words-complete-c-guide/) Aspose.Words for .NET を使用して、任意のドキュメントを PDF に変換する完全な C# ガイドです。ステップバイステップで実装方法を解説します。 | | [C#でWordからアクセシブルPDFを作成する – ステップバイステップ ガイド](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) Aspose.Words for .NET を使用して、Word 文書からアクセシブルな PDF を作成する方法をステップバイステップで学びます。 | | [C#でアクセシブルPDFを作成 – PDFアクセシビリティチュートリアル](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) Aspose.Words for .NET を使用して、C# でアクセシブルな PDF を作成し、タグ付けや代替テキストを設定する方法を学びます。 | | [Word からアクセシブル PDF を作成する – 完全ガイド](./create-accessible-pdf-from-word-complete-guide/) Aspose.Words for .NET を使用して、Word 文書からアクセシブルな PDF を作成し、アクセシビリティ基準に準拠させる方法をステップバイステップで解説します。 | diff --git a/words/japanese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/japanese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..00234632a2 --- /dev/null +++ b/words/japanese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-05-01 +description: C# で Aspose.Words を使用してドキュメントを PDF として保存する方法を学びます。このチュートリアルでは、Word を + PDF に変換する方法、数式 LaTeX のエクスポート、そしてフォントが欠落している場合の対処方法も取り上げています。 +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: ja +og_description: Aspose.Wordsで文書を簡単にPDFとして保存できます。このガイドでは、WordをPDFに変換する方法、数式をLaTeXでエクスポートする方法、そしてフォントが欠落している場合の対処方法も紹介しています。 +og_title: Aspose.Wordsで文書をPDFとして保存 – 完全なC#ガイド +tags: +- Aspose.Words +- C# +- PDF generation +title: Aspose.WordsでドキュメントをPDFとして保存 – 完全なC#ガイド +url: /ja/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words でドキュメントを PDF として保存 – 完全 C# ガイド + +Ever wondered **ドキュメントを PDF として保存する方法** directly from a Word file without losing accessibility features? You're not the only one—developers constantly ask for a reliable way to convert Word to PDF while preserving math equations and handling missing fonts gracefully. + +In this tutorial we’ll walk through a step‑by‑step solution that not only **save document as pdf** but also demonstrates **convert word to pdf**, **export math latex**, and **handle missing fonts** using the latest Aspose.Words for .NET. By the end you’ll have a ready‑to‑run C# program that produces PDF/UA‑2 compliant files, perfect for accessibility audits. + +## 必要なもの + +- .NET 6 or later (the code works with .NET Core and .NET Framework as well) +- Aspose.Words for .NET 25.10 or newer – you can grab a free trial from the Aspose website +- A modest Word document (`input.docx`) that contains at least one floating shape and a math equation (to see the export‑math‑latex feature in action) +- Visual Studio 2022 (or any IDE you like) + +> **Pro tip:** If you’re on a CI/CD pipeline, add the Aspose.Words NuGet package to your project file: + +```xml + +``` + +Now let’s dive into the code. + +## ステップ 1: 自動リカバリでソース ドキュメントをロード + +When dealing with real‑world Word files you might encounter corrupt sections or missing resources. Enabling automatic recovery ensures the loading process never throws an exception. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**この点が重要な理由:** +`RecoveryMode.AutoRecover` protects your pipeline from crashing on malformed input, which is especially handy when you **convert word to pdf** in bulk. + +## ステップ 2: 完全なアクセシビリティのために PDF 保存オプションを設定 + +PDF/UA‑2 is the ISO standard for accessible PDFs. By configuring a few flags we get a file that screen readers can navigate, and we also make sure math equations are exported as hidden LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**重要ポイント:** + +- **ExportFloatingShapesAsInlineTag** – makes sure the resulting PDF respects the original layout while staying semantically correct. +- **OfficeMathExportMode.LaTeX** – satisfies the **export math latex** requirement, letting downstream tools extract the equations if needed. + +## ステップ 3: 警告をキャプチャ (例: フォントが見つからない場合) + +Missing fonts are a common headache when converting documents. Aspose.Words can report these issues via a `WarningCallback`. We’ll collect them so you can log or act on them later. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**なぜ重要か:** +If the source uses a font that isn’t installed on the server, the PDF will fall back to a default font, potentially breaking the layout. By **handle missing fonts** we can alert the user or embed a substitute. + +## ステップ 4: アクセシブルな PDF としてドキュメントを保存 + +Now the moment of truth—actually performing the conversion. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +If everything goes smoothly, you’ll end up with a PDF/UA‑2 file that contains hidden LaTeX for each equation and proper tagging for floating shapes. + +## ステップ 5: キャプチャした警告を確認 (任意だが推奨) + +After the save operation, you can iterate over the collected warnings and log them. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typical output might look like: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Seeing these messages early helps you **handle missing fonts** before they affect end‑users. + +## 完全な動作例 + +Putting everything together, here’s the complete, ready‑to‑run program. Replace the placeholder paths with your own. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**期待される結果:** +- `output.pdf` complies with PDF/UA‑2. +- All floating shapes are tagged as inline figures. +- Every Office Math object appears as hidden LaTeX (visible when you inspect the PDF’s structure). +- Any font‑related issues are printed to the console, giving you a chance to **handle missing fonts** before shipping the file. + +![Word → Aspose.Words → アクセシブル PDF (ドキュメントを PDF として保存) のフローを示す図](conversion-diagram.png "ドキュメントを PDF として保存するフローダイアグラム") + +*Image alt text:* **Aspose.Words を使用してドキュメントを PDF として保存する方法の図** + +## よくある質問とエッジケース + +### What if I’m using an older Aspose.Words version? + +The `OfficeMathExportMode.LaTeX` flag was introduced in 25.10. For older releases you can still **convert word to pdf**, but the math will be rasterized instead of exported as LaTeX. Upgrade for best accessibility. + +### Can I embed custom fonts to avoid fallback? + +Yes. Set `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` before calling `Save`. This also helps **handle missing fonts** by forcing the PDF to contain the required glyphs. + +### How do I verify the PDF/UA‑2 compliance? + +Open the file in Adobe Acrobat Pro → “Print Production” → “Preflight”. Choose the “PDF/A‑2b” or “PDF/UA‑2” profile; Acrobat will report any violations. + +### What about password‑protected Word files? + +Load the document with a `LoadOptions` that includes `Password`. Example: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +The rest of the pipeline stays unchanged. + +## 結論 + +We’ve covered everything you need to **save document as pdf** using Aspose.Words in C#. The tutorial also demonstrated how to **convert word to pdf**, **export math latex**, and **handle missing fonts**—all while producing an accessible PDF/UA‑2 file. + +Give the code a spin, experiment with different `PdfSaveOptions` (e.g., image compression, PDF/A‑2b), and integrate it into your document‑processing service. If you need to go further, consider exploring Aspose’s PDF‑specific library for post‑processing or digital signatures. + +Got more scenarios you’d like to tackle? Feel free to drop a comment or check out our other guides on **PDF manipulation**, **image extraction**, and **batch conversion**. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-shapes/_index.md b/words/japanese/net/programming-with-shapes/_index.md index e8d791fe97..fa234a4d02 100644 --- a/words/japanese/net/programming-with-shapes/_index.md +++ b/words/japanese/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Aspose.Words for .NET を使い、これらのチュートリアルに従うこ | [C# を使用して Word に長方形の図形を作成 – ステップバイステップ ガイド](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) Aspose.Words for .NET と C# を使い、Word 文書に長方形の図形を作成する手順を段階的に解説します。 | | [Aspose.Words 図形の影チュートリアル – C# で Word 図形に影を追加](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) このチュートリアルでは、Aspose.Words for .NET を使用して C# で Word 図形に影効果を適用する方法をステップバイステップで解説します。 | | [影付き長方形シェイプで空白の Word 文書を作成 – ステップバイステップ ガイド](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) Aspose.Words for .NET を使用して、影付き長方形シェイプを持つ空白の Word 文書を作成する手順を解説します。 | +| [Aspose.Words で影を移動する方法 – 完全 C# ガイド](./how-to-move-shadow-in-aspose-words-complete-c-guide/) Aspose.Words for .NET と C# を使用して、Word 文書内の図形の影位置を変更する手順をステップバイステップで解説します。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/japanese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..867edf4272 --- /dev/null +++ b/words/japanese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-01 +description: C# を使用して Aspose.Words で図形の影を移動する方法。数分で図形に影を追加し、ぼかしを変更し、透明度を設定し、影を回転させる方法を学びましょう。 +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: ja +og_description: C# を使用して Aspose.Words でシェイプの影を移動する方法。このチュートリアルでは、シェイプに影を追加し、ぼかしを変更し、透明度を設定し、影を回転させる方法を示します。 +og_title: Aspose.Wordsで影を移動する方法 – 完全なC#ガイド +tags: +- Aspose.Words +- C# +- Document Automation +title: Aspose.Wordsで影を移動する方法 – 完全なC#ガイド +url: /ja/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words で影を移動する方法 – 完全な C# ガイド + +Word ドキュメント内のシェイプの **影の移動方法** を、手動で Word を開かずに知りたくありませんか?日常業務で、レポートを洗練させるためや動的テンプレートのために、シェイプの影をプログラムで微調整する必要が頻繁にありました。良いニュースは、Aspose.Words を使えば数行のコードで実現でき、**add shadow to shape**、**how to change blur**、**how to set transparency**、**how to rotate shadow** も同時に学べます。 + +このチュートリアルでは、既にシェイプが含まれている既存の DOCX を読み込み、影の位置、柔らかさ、不透明度、方向を調整し、最終的に保存する実践的シナリオを解説します。最後まで読めば、任意の .NET プロジェクトに貼り付け可能な再利用可能なスニペットが手に入り、各プロパティの重要性も理解できます。 + +## 前提条件 – 開始前に必要なもの + +- **Aspose.Words for .NET**(バージョン 23.12 以降)。`Install-Package Aspose.Words` で NuGet から取得できます。 +- .NET 6+ 開発環境(Visual Studio、VS Code、Rider など、お好みのもの)。 +- 既に少なくとも 1 つのシェイプ(矩形、円、または画像)が含まれている入力 Word ファイル(`input.docx`)。 +- 基本的な C# 文法に慣れていること—特別な知識は不要です。 + +これらが揃っていない場合は、一度止めてライブラリをインストールしてください。以降の手順はパッケージが参照済みであることを前提としています。 + +## ステップ 1: ドキュメントをロードし対象シェイプを取得 – **How to Move Shadow** がここから始まります + +最初に行うのは、ソースドキュメントをロードし、変更したいシェイプを特定することです。Aspose.Words はすべてのオブジェクト(段落、テーブル、シェイプ)をツリー上のノードとして扱うため、直接クエリできます。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Why this matters:** ドキュメントを一度だけロードし、同じ `Document` インスタンスを再利用することで効率的です。`GetChild` 呼び出しはインデックスが範囲外の場合 `null` を返すため、シェイプが存在しないケースも安全に処理できます。 + +## ステップ 2: ぼかし半径を調整 – Master **How to Change Blur** + +柔らかい影はプロフェッショナルに見え、ハードなエッジは安っぽく感じられます。`BlurRadius` プロパティはポイント単位で柔らかさを制御します(1 pt ≈ 1/72 インチ)。ここでは 8 pt に上げてみましょう。 + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** デフォルトのぼかしは 0.5 pt です。5 pt を超えるとほとんどの場合目立ちますが、あまり大きくしすぎるとシェイプがページから浮き上がって見えるので注意してください。 + +## ステップ 3: 透明度を設定 – The Answer to **How to Set Transparency** + +透明度は影の透過度を決めます。`0` は完全に不透明、`1` は完全に見えなくなります。さりげない効果として `0.3`(30 % 透明)を使用します。 + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Why you might care:** シェイプが濃い色の場合、完全に不透明な影は下のテキストを埋もれさせてしまいます。透明度を調整すれば、文書の可読性を保ちつつ奥行きを演出できます。 + +## ステップ 4: 影を移動 – The Core of **How to Move Shadow** + +`Distance` プロパティは影がシェイプからどれだけ離れるかをポイントで指定します。距離が大きいほど影が遠くにずれ、ドラマチックな効果が得られます。 + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **What if you need a tiny offset?** `Distance` を `0` に設定すると、影がシェイプのすぐ背後に重なります。エンボス効果などに便利です。 + +## ステップ 5: 光源を回転 – Solving **How to Rotate Shadow** + +影は単に下向きだけでなく、光源の角度に従います。`Angle` プロパティ(度単位)で影をシェイプの周りに回転させます。ここでは 45° に傾けます。 + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Quick experiment:** `90` にすると右側に影ができ、`-30` にすると左側に傾いた影になります。変化はすぐに視覚で確認できます。 + +## ステップ 6: ドキュメントを保存 – Seeing the Result of **Add Shadow to Shape** + +影の調整が完了したら、ドキュメントをディスクに書き戻します。元ファイルを上書きするか新しいファイルを作成するかは自由です。例では新しい出力ファイルを使用します。 + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Expected output:** `output.docx` を開くと、シェイプの影がより柔らかく、少しオフセットされ、半透明で、45° に傾いていることが確認できます。`input.docx` と並べて比較すれば違いは一目瞭然です。 + +### 完全動作サンプル(コピー&ペースト用) + +以下は 1 つのブロックにまとめた全プログラムです。新しいコンソールプロジェクトに貼り付け、`YOUR_DIRECTORY` を実際のフォルダー パスに置き換えて実行してください。 + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## よくある質問とエッジケース + +### ドキュメントに複数のシェイプがある場合は? + +すべてのシェイプをループで処理できます: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### 現在影が設定されていないシェイプに影を追加できますか? + +もちろんです。`ShadowFormat` オブジェクトは常に存在しますので、有効化するだけです: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### 画像や SmartArt でも動作しますか? + +はい。`Shape` を継承するノード(画像、チャート、SmartArt など)すべてが `ShadowFormat` を公開しています。同じプロパティが使用可能です。 + +### 影の色はどうやって制御しますか? + +`Color` プロパティを使用します: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### 互換性の懸念は? + +Aspose.Words 23.12 以降は .NET 6、.NET Core 3.1、.NET Framework 4.6.2+ をサポートしています。ここで示した API はこれらのバージョン間で安定しています。 + +## 結論 + +Aspose.Words を使ってシェイプの **影の移動方法** を解説しながら、**add shadow to shape**、**how to change blur**、**how to set transparency**、**how to rotate shadow** も同時に実演しました。完全に実行可能なサンプルは、数秒で任意のシェイプの影を調整でき、Word を開かずに文書を洗練されたプロフェッショナルな外観にします。 + +次のステップに進みませんか?たとえば、見出しや一定サイズ以上のチャートにだけ深い影を適用する **conditional formatting** と組み合わせたり、シェイプ自体に **gradient fills** を適用して目を引くデザインを作り出したりしてみてください。 + +問題があればコメントで教えてください。コーディングを楽しみながら、影が思い通りの位置に落ちることを願っています! + +![シェイプ上の影の移動効果を示す図 – 影の移動例](https://example.com/images/shadow-demo.png "影の移動例") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/basic-conversions/_index.md b/words/korean/net/basic-conversions/_index.md index f5dfd1ff0a..caf7dbd20f 100644 --- a/words/korean/net/basic-conversions/_index.md +++ b/words/korean/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ | [C#에서 Aspose.Words를 사용해 Word를 PDF로 변환 – 가이드](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aspose.Words for .NET을 사용하여 C#에서 Word 문서를 PDF로 변환하는 방법을 단계별로 안내합니다. | | [Aspose.Words로 Word를 PDF로 저장 – 완전한 C# 가이드](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words와 C#을 활용해 Word 문서를 PDF로 변환하는 전체 단계별 가이드입니다. | | [Aspose.Words로 Docx를 PDF로 저장 – 완전한 C# 가이드](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words와 C#을 사용해 Docx 파일을 PDF로 변환하는 전체 단계별 가이드입니다. | +| [Aspose.Words로 Word를 PDF로 저장 – 완전한 가이드](./save-word-as-pdf-with-aspose-words-complete-guide/) | Aspose.Words를 사용해 Word 문서를 PDF로 변환하는 전체 단계별 가이드입니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/korean/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 5670ca9105..b13d40afd3 100644 --- a/words/korean/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/korean/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,22 @@ --- category: general -date: 2025-12-29 -description: Aspose.Words를 사용하여 Word에서 LaTeX를 내보내는 방법 – Word를 LaTeX로 변환하고, docx를 txt로 - 저장하며, 일반 텍스트에서 수식을 처리하는 방법을 배워보세요. +date: 2026-05-01 +description: Aspose.Words를 사용하여 C#에서 Word 파일을 LaTeX로 내보내고, Word를 txt로 변환하며, 표를 보존하는 + 방법을 배우세요. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: ko -og_description: Aspose.Words를 사용하여 Word에서 LaTeX를 내보내는 방법. 이 가이드는 Word를 LaTeX로 변환하고, - docx를 txt로 저장하며, 수식을 그대로 유지하는 방법을 보여줍니다. -og_title: Word에서 LaTeX 내보내는 방법 – 빠른 C# 튜토리얼 +og_description: Aspose.Words를 사용하여 Word에서 LaTeX를 내보내고, Word를 일반 텍스트로 변환하며, 표 레이아웃을 + 그대로 유지하는 방법을 알아보세요. +og_title: Word에서 LaTeX 내보내는 방법 – 완전한 C# 튜토리얼 tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Word에서 LaTeX 내보내는 방법 – 단계별 가이드 url: /ko/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,183 +26,217 @@ url: /ko/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Word에서 LaTeX 내보내기 – 단계별 가이드 +# Word에서 LaTeX 내보내기 – 완전 C# 튜토리얼 -Ever wondered **Word에서 LaTeX를 내보내는 방법** without losing any of those tricky Office Math equations? You're not the only one. Many developers hit a wall when they try to *Word를 LaTeX로 변환* for academic papers, scientific reports, or automated publishing pipelines. +Word 문서에서 수식이 손실되지 않게 **LaTeX 내보내는 방법**을 궁금해 본 적 있나요? 혼자가 아닙니다. 많은 개발자들이 Office Math가 포함된 .docx 파일을 깔끔한 LaTeX으로 변환하면서 동시에 **Word를 txt로 변환**해야 합니다. 이 가이드에서는 **테이블 보존**을 포함한 실용적이고 바로 실행 가능한 솔루션을 단계별로 안내하고, 텍스트 파일을 제공하며 LaTeX 마크업을 필요한 위치에 그대로 유지합니다. -In this tutorial we’ll walk through a complete, ready‑to‑run C# example that shows **LaTeX 내보내는 방법** using Aspose.Words, explains **txt 파일 저장 방법** with LaTeX markup, and even covers the nuances of **Word 수식을 LaTeX로 변환** so nothing gets lost in translation. +우리는 파일 로드부터 `TxtSaveOptions` 조정까지 모든 과정을 다룰 것이며, 최종적으로 **docx를 txt로 저장**, **Word를 일반 텍스트로 변환**, 그리고 **테이블 보존 방법**을 알 수 있게 됩니다. 외부 스크립트 없이, 수동 복사‑붙여넣기 없이—그냥 순수 C# 코드만 있으면 .NET 프로젝트 어디에든 바로 넣어 사용할 수 있습니다. -> **팁:** The same approach works for any .docx you have—just point the code at a different file path. +## 필요 사항 + +- **Aspose.Words for .NET** (최신 버전, 2024.x 이상). NuGet 패키지는 `Aspose.Words`입니다. +- .NET 개발 환경 (Visual Studio, VS Code, Rider—어느 것이든 상관없음). +- Office Math 수식과 최소 하나의 테이블을 포함한 Word 파일(`.docx`) (테이블 보존 마법을 확인하기 위해). + +그게 전부입니다. 이미 준비되어 있다면 계속 읽으세요; 그렇지 않다면 NuGet 패키지를 가져오고 샘플 DOCX 파일을 준비한 뒤 아래로 진행하세요. --- -## 필요 사항 +## Word 문서에서 LaTeX 내보내기 -Before we dive in, make sure you have the following prerequisites: +아래는 튜토리얼의 핵심—세 가지 간결한 단계로 **LaTeX 내보내는 방법**을 답변하고, 동시에 **Word를 txt로 변환**, **Word를 일반 텍스트로 변환**, **docx를 txt로 저장**, 그리고 **테이블 보존 방법**을 처리합니다. -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words는 최신 .NET 런타임을 대상으로 합니다. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | 이 라이브러리는 Word를 파싱하고 LaTeX를 생성하는 복잡한 작업을 수행합니다. | -| **A sample .docx** containing at least one Office Math equation | LaTeX 변환이 실제로 어떻게 이루어지는지 확인할 수 있습니다. | -| **Visual Studio 2022** (or any IDE you like) | 샘플을 디버깅하고 실행하는 것이 간단해집니다. | +### 단계 1: DOCX 파일 로드 + +먼저 Word 문서를 `Aspose.Words.Document` 객체로 읽어야 합니다. 이 단계는 나중에 **Word를 txt로 변환**하거나 **docx를 txt로 저장**할 때도 동일합니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; -If you haven’t installed the NuGet package yet, run: +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -```bash -dotnet add package Aspose.Words +Document doc = new Document(inputPath); ``` -That’s it—no extra DLLs, no COM interop, just a clean managed library. +> **왜 중요한가:** 파일을 로드하면 모든 Word 요소—단락, 테이블, Office Math 객체—가 메모리 내에 표현됩니다. 이 객체 없이는 내보내기 옵션을 조작할 수 없습니다. ---- +### 단계 2: LaTeX 및 테이블 레이아웃을 위한 `TxtSaveOptions` 구성 -## Word에서 LaTeX 내보내기 – 개요 +`TxtSaveOptions` 클래스는 일반 텍스트 파일이 어떻게 생성될지를 정확히 제어할 수 있게 해줍니다. 우리 시나리오에 핵심이 되는 두 속성은 다음과 같습니다. -Below is the big picture of what we’ll accomplish: +| Property | What it does | Why you need it | +|----------|--------------|-----------------| +| `OfficeMathExportMode` | Office Math가 어떻게 렌더링되는지를 결정합니다. `LaTeX`로 설정하면 수식이 LaTeX 구문으로 변환됩니다. | 이것이 **LaTeX 내보내는 방법**의 핵심입니다. | +| `PreserveTableLayout` | `true`이면 Aspose가 공백을 추가해 테이블이 격자 형태로 보이게 합니다. | **테이블 보존 방법**을 만족하면서 **Word를 txt로 변환**할 때 유용합니다. | -1. **로드** the source Word document (`.docx`). -2. **구성** `TxtSaveOptions` so that any Office Math objects are emitted as LaTeX code. -3. **저장** the document as a plain‑text (`.txt`) file that you can feed directly into any LaTeX compiler. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Word에서 LaTeX 내보내기 예시](image.png "Word에서 LaTeX 내보내기") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro tip:** 테이블 형식 없이 순수 LaTeX만 필요하면 `PreserveTableLayout`을 `false`로 설정하세요. 파일 크기는 작아지지만 시각적인 테이블 표시가 사라집니다. -## 단계 1: Word 문서 로드 +### 단계 3: 문서를 일반 텍스트로 저장 -First things first—open the .docx you want to convert. The `Document` class abstracts away all the underlying XML, giving you a friendly object model. +이제 정의한 옵션을 사용해 문서를 `.txt` 파일로 저장합니다. 이 한 줄로 **Word를 일반 텍스트로 변환**, **docx를 txt로 저장**, 그리고 물론 **LaTeX 내보내는 방법**을 한 번에 수행합니다. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; - -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**왜 중요한가:** -Loading the file early lets us inspect its contents (e.g., count equations) before we decide how to serialize it. If the file is corrupted, `Document` will throw a clear exception, saving you from mysterious output later. +호출이 끝난 후 `output.txt`를 열어 보면: ---- +- 모든 Office Math 수식에 대해 `\frac{a}{b}`와 같은 LaTeX 스니펫이 표시됩니다. +- `|`와 `-` 문자로 렌더링된 테이블이 열 정렬을 유지합니다. +- 일반 단락은 순수 텍스트로, downstream 파서에서 바로 사용할 수 있습니다. -## 단계 2: LaTeX 내보내기를 위한 TxtSaveOptions 구성 +### 전체 작업 예제 -The magic happens in `TxtSaveOptions`. By setting `OfficeMathExportMode` to `LaTeX`, every Office Math object is transformed into its corresponding LaTeX representation. +모두 합치면 오늘 바로 컴파일하고 실행할 수 있는 독립형 프로그램은 다음과 같습니다: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**왜 이러한 설정을 선택했는가:** +**예상 출력** (발췌): + +``` +This is a sample paragraph. -- `OfficeMathExportMode.LaTeX`는 정확한 수학적 변환을 보장하는 유일한 모드입니다. -- `PreserveTableLayout`은 테이블을 Word와 동일하게 유지해, 나중에 LaTeX `tabular` 환경에 삽입할 때 유용합니다. -- UTF‑8은 “α”, “β”, “∑”와 같은 문자가 라운드‑트립을 통해 손실되지 않도록 합니다. +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | -If you ever need to **Word를 LaTeX로 변환** without the plain‑text wrapper, you could switch to `SaveFormat.LaTeX` instead—just a quick tip for advanced scenarios. +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` + +테이블이 격자를 유지하고 수식이 깔끔한 LaTeX으로 나타나는 것을 확인하세요. 이것이 **Word를 txt로 변환**하면서 구조와 수학을 모두 충실히 표현할 수 있는 최적점입니다. --- -## 단계 3: 문서를 텍스트 파일로 저장 +## Word를 TXT로 변환하고 테이블을 보존하기 위한 팁 -Now we write the LaTeX‑rich text to disk. The resulting `.txt` can be renamed to `.tex` later, or piped directly into a LaTeX compiler. +세 단계 접근법이 대부분의 경우에 잘 작동하지만, 실제 프로젝트에서는 다양한 예외 상황이 발생합니다. 아래는 **Word를 일반 텍스트로 변환** 파이프라인을 견고하게 만드는 실용적인 제안들입니다. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### 일관된 인코딩 사용 -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions`는 기본값이 UTF‑8이며 대부분의 문자를 처리합니다. 다른 코드 페이지가 필요하면(예: 레거시 시스템이 Windows‑1252를 기대하는 경우) `Encoding` 속성을 설정하세요: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**`output.txt`에 표시되는 내용:** +### 불필요한 공백 제거 -``` -\begin{equation} -E = mc^{2} -\end{equation} +열이 많은 테이블은 긴 라인을 생성할 수 있습니다. 저장 후 파일을 후처리해 여러 개의 공백을 하나의 탭으로 축소하면 좋습니다: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -All other paragraphs appear as plain text, while any Office Math equation is wrapped in a LaTeX `equation` environment (or `inline` if it was inline in Word). This satisfies the **Word 수식을 LaTeX로 변환** requirement perfectly. +### 중첩 테이블 처리 ---- +DOCX에 테이블 안에 테이블이 들어 있는 경우, `PreserveTableLayout`은 시각적 계층을 유지하지만 들여쓰기가 어색해 보일 수 있습니다. 빠른 해결책은 선행 공백을 사용자 정의 마커(예: `>>`)로 교체해 downstream 파서가 중첩 수준을 감지하도록 하는 것입니다. -## 엣지 케이스 및 흔히 묻는 질문 +### 다수 파일 일괄 처리 -| Situation | What to do | -|-----------|------------| -| **소스에 수식이 없음** | 변환은 여전히 작동합니다; 단순히 일반 텍스트만 얻습니다. 추가 LaTeX 코드는 삽입되지 않습니다. | -| **매우 큰 문서 (>100 MB)** | `MemoryStream`을 사용해 출력을 스트리밍하면 메모리 사용량을 줄일 수 있습니다. | -| **지원되지 않는 수학 구성** | Aspose.Words는 Office Math의 99 %를 지원합니다. 드문 경우에는 LaTeX를 수동으로 후처리해야 할 수 있습니다. | -| **.txt 대신 .tex 파일이 필요** | `outputPath`를 `.tex`로 끝나게 변경하고, 필요에 따라 `txtOptions.Encoding`을 `Encoding.UTF8`로 설정합니다. | -| **Linux/macOS에서 실행** | 동일한 코드가 작동합니다—파일 경로에 슬래시를 사용하거나 `Path.Combine`을 사용하세요. | +수십 개의 문서에 대해 **Word를 txt로 변환**해야 할 때는 로직을 루프로 감싸세요: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` -## LaTeX 수식이 포함된 TXT 저장 방법 – 빠른 요약 +이렇게 하면 수동 개입 없이 **docx를 txt로 저장**을 대량으로 수행할 수 있습니다. -1. **로드** the .docx (`Document`). -2. **설정** `TxtSaveOptions`에서 `OfficeMathExportMode = LaTeX`. -3. **저장** the file (`doc.Save`) with those options. +--- -That’s the entire workflow to **txt 파일 저장 방법** files that contain LaTeX‑formatted equations. +## 흔히 발생하는 실수와 회피 방법 + +1. **Missing LaTeX Export Mode** – `OfficeMathExportMode = OfficeMathExportMode.LaTeX` 설정을 잊으면 수식이 일반 텍스트(예: “Equation 1”)로 돌아갑니다. 옵션 블록을 항상 재확인하세요. +2. **Table Layout Gets Lost** – `PreserveTableLayout`을 `false`로 두는 것이 기본값입니다. 출력이 텍스트 벽처럼 보이면 플래그를 토글하지 않은 것이 원인일 수 있습니다. +3. **File Paths with Spaces** – 원시 문자열(`@"C:\My Folder\input.docx"`)을 사용하면 이스케이프 문제를 피할 수 있습니다. 그렇지 않으면 `FileNotFoundException`이 발생합니다. +4. **Version Mismatch** – 오래된 Aspose.Words 버전(< 21.9)에서는 `OfficeMathExportMode`를 지원하지 않습니다. 최신 패키지로 업그레이드해 **LaTeX 내보내는 방법**이 정상 작동하도록 하세요. +5. **Encoding Errors for Non‑ASCII Characters** – `�` 기호가 보이면 `options.Encoding`을 UTF‑8 또는 적절한 코드 페이지로 명시적으로 설정하세요. --- -## 보너스: 여러 파일에 대한 변환 자동화 +## 솔루션 확장: TXT에서 Markdown 또는 HTML로 -If you have a folder full of Word docs, wrap the above logic in a simple loop: +때로는 일반 텍스트보다 더 필요할 수 있습니다—예를 들어 LaTeX 블록을 포함한 Markdown 파일이 필요할 때. 동일한 `TxtSaveOptions`를 `HtmlSaveOptions` 또는 `MarkdownSaveOptions`로 교체하면 됩니다: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Now you can **Word를 LaTeX로 대량 변환** in bulk—perfect for research groups that receive dozens of manuscripts daily. +이 작은 변경만으로 **Word를 txt 스타일 출력**을 유지하면서도 원하는 Markdown 구문을 사용할 수 있습니다. --- ## 결론 -We’ve covered **Word에서 LaTeX를 내보내는 방법** step‑by‑step, demonstrated **txt 파일 저장 방법** that preserve every Office Math equation, and even showed you how to **Word 수식을 LaTeX로 변환** without losing fidelity. +우리는 Word 문서에서 **LaTeX 내보내는 방법**에 대한 완전하고 프로덕션 수준의 답변을 살펴보았으며, 동시에 **Word를 txt로 변환**, **Word를 일반 텍스트로 변환**, **docx를 txt로 저장**, 그리고 **테이블 보존 방법**을 보여주었습니다. 핵심 요점은 다음과 같습니다. -With just a few lines of C# and the powerful Aspose.Words library, you can turn any .docx into LaTeX‑ready text, ready for inclusion in scientific papers, textbooks, or automated publishing pipelines. +- `Aspose.Words.Document`로 DOCX를 로드합니다. +- `TxtSaveOptions.OfficeMathExportMode = LaTeX`와 `PreserveTableLayout = true`를 설정합니다. +- `doc.Save(outputPath, options)`를 호출해 LaTeX가 풍부한 깔끔한 일반 텍스트 파일을 얻습니다. -**다음 단계?** Try feeding the generated `.txt` (or rename it to `.tex`) into `pdflatex` or `xelatex` to produce a PDF, or explore the `SaveFormat.LaTeX` option for a direct `.tex` file. If you need to **docx를 txt로 저장** while preserving formatting, experiment with `PreserveTableLayout` and custom line‑break handling. +직접 파일에 적용해 보고, 인코딩 조정을 실험해 보며, 폴더 전체를 일괄 처리해 보세요. 중첩 테이블, 특수 문자, 오래된 Aspose 버전 등 예외 상황이 발생하면 “팁”과 “실수 회피” 섹션을 다시 참고하면 빠르게 해결할 수 있습니다. -Got questions about edge cases, licensing, or performance tweaks? Drop a comment below—happy +다음 단계가 준비됐나요? 동일한 DOCX를 Markdown으로 변환하거나, 생성된 `.txt`를 LaTeX를 웹에서 렌더링하는 정적 사이트 생성기에 연결해 보세요. 가능성은 무한하며, 이제 **Word를 txt로 변환** 워크플로우를 위한 탄탄한 기반을 갖추었습니다. -{{< /blocks/products/pf/tutorial-page-section >}} +행복한 코딩 되시길, 그리고 LaTeX가 첫 시도부터 항상 컴파일되길 바랍니다! +{{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} - {{< /blocks/products/pf/main-wrap-class >}} - {{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/korean/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..675a1b3864 --- /dev/null +++ b/words/korean/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: C#에서 Aspose.Words를 사용하여 Word를 PDF로 저장합니다. docx를 PDF로 변환하고, 누락된 글꼴을 감지하며, + 글꼴 대체 경고를 효율적으로 처리하는 방법을 배워보세요. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: ko +og_description: Aspose.Words를 사용하여 Word를 PDF로 저장합니다. 이 단계별 튜토리얼은 docx를 PDF로 변환하고 누락된 + 글꼴을 감지하는 방법을 보여줍니다. +og_title: Aspose.Words를 사용하여 Word를 PDF로 저장하는 완전 가이드 +tags: +- Aspose.Words +- C# +- PDF conversion +title: Aspose.Words로 Word를 PDF로 저장하기 – 완전 가이드 +url: /ko/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words로 Word를 PDF로 저장 – 완전 가이드 + +실시간으로 **Word를 PDF로 저장**해야 할 때, 중간에 폰트가 누락될까 고민해 본 적 있나요? 당신만 그런 것이 아닙니다—개발자들은 문서를 변환할 때 누락된 폰트 문제와 끊임없이 씨름합니다. 이 가이드에서는 **docx를 pdf로 변환**할 뿐만 아니라 Aspose.Words의 폰트 대체 경고를 사용해 **누락된 폰트 감지**까지 할 수 있는 실전 솔루션을 단계별로 안내합니다. + +경고 콜렉터 설정부터 출력 해석까지 모든 과정을 다루므로, 끝까지 읽으면 **Word를 PDF로 저장**할 때 깜짝 놀랄 일이 없다는 것을 정확히 알게 됩니다. 외부 도구도 없고, 복잡한 설정도 없습니다—그냥 .NET 프로젝트 어디에든 넣어 사용할 수 있는 깔끔한 C# 코드만 있으면 됩니다. + +## 필요 사항 + +- **Aspose.Words for .NET** (최신 버전, 예: 24.10) – NuGet(`Install-Package Aspose.Words`)으로 바로 가져올 수 있습니다. +- .NET 개발 환경 (Visual Studio, Rider, 혹은 VS Code 등) +- 대상 머신에 설치되지 않은 폰트를 포함할 수 있는 샘플 DOCX 파일 + +그게 전부입니다. 위 기본 사항만 갖추면 바로 시작할 준비가 된 것입니다. + +## Word를 PDF로 저장 – 단계별 개요 + +아래는 완전한 실행 가능한 프로그램 예시입니다. 콘솔 앱 프로젝트에 복사‑붙여넣기하고 **F5**만 눌러 실행해 보세요. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** `YOUR_DIRECTORY`를 절대 경로로 바꾸거나 `Path.Combine(Environment.CurrentDirectory, "input.docx")`를 사용해 상대 경로를 지정하면 더 안전합니다. + +### 왜 경고 콜백을 사용하는가 + +Aspose.Words는 누락된 폰트를 자동으로 대체 폰트(보통 Arial)로 교체합니다. 콜백이 없으면 교체가 일어났는지 전혀 알 수 없으며, 이는 최종 PDF에서 레이아웃 오류를 초래할 수 있습니다. `IWarningCallback`을 연결하면 누락된 폰트 이벤트를 프로그램적으로 명확히 리스트업할 수 있어 로깅이나 사용자 알림에 최적입니다. + +### 누락된 폰트 감지 – 확인 포인트 + +프로그램을 실행하면 누락된 폰트마다 다음과 유사한 콘솔 라인이 출력됩니다. + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +리스트가 비어 있으면 축하합니다—**Word를 PDF로 저장**이 모든 원본 폰트를 그대로 유지한 채 성공한 것입니다. + +## Docx를 PDF로 변환 – 출력 맞춤 설정 + +특정 PDF 버전, 이미지 품질, 혹은 규격 준수가 필요할 때가 있습니다. Aspose.Words는 `PdfSaveOptions` 객체를 `Save` 호출 전에 조정할 수 있게 해줍니다. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Why this matters:** 법적 보관용 PDF를 생성한다면 `PdfA1b`를 설정해 파일이 엄격한 표준을 만족하도록 할 수 있습니다. 동일한 변환 과정에서도 경고 콜백은 그대로 동작하므로 **누락된 폰트 감지**는 계속 가능합니다. + +## Aspose Words 폰트 대체 – 엣지 케이스 처리 + +### 시나리오 1: 다중 누락 폰트 + +소스 문서에 여러 사용자 정의 폰트가 사용된 경우, 경고 콜렉터에 폰트당 하나씩 항목이 들어갑니다. 이를 집계할 수 있습니다: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### 시나리오 2: 대체 폰트 디렉터리 제공 + +Aspose.Words는 추가 폰트 폴더를 검색할 수 있습니다. 문서를 로드하기 전에 `FontSettings`의 `FontsFolder` 속성을 설정하세요: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +이제 라이브러리는 먼저 사용자 지정 폴더를 탐색하므로 원치 않는 대체가 발생할 가능성이 줄어듭니다. + +### 시나리오 3: 대체 무시 + +폰트가 누락되었을 때 조용히 대체하는 대신 변환을 실패하게 하고 싶다면, 콜백 내부에서 예외를 발생시킵니다: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +이렇게 하면 진행하기 전에 누락된 폰트를 반드시 해결해야 하므로, 조용한 실패를 허용하지 않는 CI 파이프라인에 유용합니다. + +## 전체 엔드‑투‑엔드 예제 + +모든 요소를 합친 간결한 버전으로 **Word를 PDF로 변환**하는 방법을 보여주며, 사용자 정의 PDF 옵션을 설정하고 폰트 문제를 로그에 기록합니다: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**예상 콘솔 출력** (Calibri가 누락된 경우): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +경고가 전혀 나타나지 않으면 **Word를 PDF로 저장** 작업이 원본 DOCX와 동일한 폰트를 사용한 것입니다. + +## 시각적 요약 + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*이미지 대체 텍스트:* **Word를 PDF로 저장** 워크플로우는 로딩, 경고 수집, PDF 출력 과정을 보여줍니다. + +## 자주 묻는 질문 & 답변 + +| Question | Answer | +|----------|--------| +| **Aspose.Words에 라이선스가 필요합니까?** | 무료 평가 라이선스로 테스트는 가능하지만, 실제 서비스에서는 평가 워터마크를 제거하기 위해 유료 라이선스가 필요합니다. | +| **.NET Core / .NET 6+에서도 동작합니까?** | 물론입니다—Aspose.Words는 .NET Standard 2.0을 타깃으로 하므로 최신 .NET 런타임 어디서든 호환됩니다. | +| **여러 DOCX 파일을 루프에서 변환할 수 있나요?** | 가능합니다. 파일마다 새로운 `Document` 인스턴스를 만들고, 원한다면 동일한 `WarningInfoCollector`를 재사용해 결과를 집계하면 됩니다. | +| **출력 폴더가 존재하지 않으면 어떻게 되나요?** | `Document.Save`는 `DirectoryNotFoundException`을 발생시킵니다. 먼저 폴더를 만들거나 `Directory.CreateDirectory`를 사용하세요. | +| **누락된 폰트를 PDF에 포함시킬 방법이 있나요?** | 머신에 폰트가 존재한다면 Aspose.Words가 자동으로 폰트를 임베드합니다. `PdfSaveOptions.EmbedFullFonts = true`로 설정하면 됩니다. | + +## 결론 + +이제 **Word를 PDF로 저장**하면서 **누락된 폰트 감지**와 **Aspose.Words 폰트 대체** 상황을 처리할 수 있는 견고하고 프로덕션 수준의 패턴을 갖추었습니다. 경고 콜백을 연결하고, 폰트 폴더를 맞춤 설정하며, 필요에 따라 `PdfSaveOptions`를 조정하면 **docx를 pdf로 변환**하면서 레이아웃 정확도에 영향을 줄 수 있는 폰트 문제를 사용자에게 명확히 알릴 수 있습니다. + +다음 단계가 준비되셨나요? 여러 문서를 병렬로 PDF로 생성해 보거나, 워터마크와 디지털 서명 추가 기능을 탐색해 보세요—두 기능 모두 방금 익힌 코드를 기반으로 손쉽게 확장할 수 있습니다. 즐거운 코딩 되시고, 여러분의 PDF가 언제나 의도한 대로 정확히 표시되길 바랍니다! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-loadoptions/_index.md b/words/korean/net/programming-with-loadoptions/_index.md index 4900358976..bd71ab52ea 100644 --- a/words/korean/net/programming-with-loadoptions/_index.md +++ b/words/korean/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Aspose.Words for .NET 튜토리얼은 LoadOptions를 사용하여 워드 프로 | [C#에서 Aspose.Words를 사용한 Word 문서 복구](./recover-word-document-with-aspose-words-in-c/) | Aspose.Words for .NET을 사용하여 손상된 Word 문서를 복구하는 단계별 가이드를 제공합니다. | | [Aspose.Words에서 LoadOptions 사용 방법 – 완전 가이드](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Aspose.Words에서 LoadOptions를 활용해 문서를 로드하고 설정을 맞추는 방법을 단계별로 안내합니다. | | [C#에서 손상된 문서 복구 – 복구 모드 설정 및 사용자에게 알림](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Aspose.Words for .NET을 사용하여 손상된 문서를 복구하고, 복구 모드를 설정하며 사용자에게 복구 옵션을 안내하는 방법을 단계별로 안내합니다. | +| [손상된 docx 복구 – C#에서 손상된 Word 파일 로드 완전 가이드](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Aspose.Words for .NET을 사용하여 손상된 docx 파일을 C#에서 로드하고 복구하는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/korean/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..48ffaeac28 --- /dev/null +++ b/words/korean/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words를 사용하여 손상된 docx 파일을 빠르게 복구하세요. 복구 모드를 설정하고, docx를 안전하게 로드하며, + 손상된 Word 파일을 몇 단계만에 읽는 방법을 배워보세요. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: ko +og_description: C#에서 손상된 docx 파일을 복구합니다. 복구 모드를 설정하고 docx를 안전하게 로드하며 Aspose.Words로 + 손상된 Word 파일을 읽습니다. +og_title: 손상된 docx 복구 – 빠른 C# 가이드 +tags: +- Aspose.Words +- C# +- Document Recovery +title: 손상된 docx 복구 – C#에서 손상된 Word 파일을 로드하는 완전 가이드 +url: /ko/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 손상된 docx 복구 – 빠른 C# 가이드 + +Word 파일을 열려고 했지만 로드되지 않아 내용이 영원히 사라졌는지 궁금해 본 적이 있나요? 많은 실제 프로젝트에서 사용자는 첨부 파일을 다시 보내도록 요구하지 않고도 **recover corrupted docx** 파일을 복구합니다. 좋은 소식은 Aspose.Words가 이를 아주 쉽게 만들어 준다는 것입니다: 복구 모드를 설정하고 라이브러리가 나머지를 처리하도록 하면 됩니다. + +이 튜토리얼에서는 **recover corrupted docx** 파일을 복구하는 정확한 단계들을 살펴보고, `RecoveryMode.AutoRecover` 옵션이 가장 안전한 선택인 이유를 설명하며, 부분적으로 손상된 **how to load docx** 파일을 어떻게 로드하는지 보여드립니다. 끝까지 읽으면 손상된 Word 파일을 읽고, 살아남은 텍스트를 추출하며, 향후 감사를 위해 원본 형식을 로그에 남길 수 있습니다. 외부 도구 없이 깔끔한 C# 코드만으로 가능합니다. + +## 필요한 사항 + +- **Aspose.Words for .NET** (최근 버전이면 모두 가능; 사용한 API는 23.5 이상에서 동작합니다). +- .NET 개발 환경 (Visual Studio, VS Code, 또는 Rider). +- 복구하려는 손상되었거나 부분적으로 손상된 `.docx` 파일. + +특별한 권한도 필요 없고, COM 인터옵도 없으며, 서버에 Microsoft Office를 설치할 필요도 없습니다. 간단하죠? + +## 1단계: 복구 모드를 Auto‑Recover 로 설정 + +Word 파일이 손상되면 기본 로딩 동작은 예외를 발생시키고 중단됩니다. `LoadOptions` 객체를 구성하여 Aspose.Words에 **set recovery mode**를 `AutoRecover`로 지정하면, zip 패키지를 스캔하고 읽을 수 없는 부분을 건너뛰며 가능한 모든 데이터를 조합해 반환합니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Why AutoRecover?** +> 가능한 한 많은 내용을 읽으면서도 문서 객체를 사용할 수 있게 유지합니다. `RecoveryMode.NoRecovery`를 선택하면 첫 번째 손상 지점에서 로드가 실패하므로 **recover corrupted docx** 시나리오의 목적에 맞지 않습니다. + +## 2단계: 구성된 옵션으로 문서 로드 + +복구 모드가 설정되었으니 이제 파일을 안전하게 열어볼 수 있습니다. `"YOUR_DIRECTORY/input.docx"`를 실제 손상 파일 경로로 교체하세요. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +파일이 부분적으로만 손상된 경우에도 `Document` 인스턴스는 생성됩니다. 추가 검증이 필요하면 나중에 `document.IsStructureValid`를 확인하면 됩니다. + +## 3단계: 감지된 형식 확인 + +Aspose.Words는 원본 형식(DOC, DOCX, ODT 등)을 자동으로 감지합니다. 이 값을 출력하면 라이브러리가 파일을 올바르게 인식했는지 빠르게 확인할 수 있으며, **recover corrupted docx** 작업 후의 간단한 sanity check가 됩니다. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +일반적인 출력: + +``` +Loaded with Docx format. +``` + +일부 부분이 누락되었더라도 형식 감지는 성공합니다—이는 **recover corrupted docx** 워크플로우에 또 다른 장점입니다. + +## 4단계: 가능한 내용 추출 + +문서가 로드되면 정상적인 Word 파일처럼 취급할 수 있습니다. 아래는 순수 텍스트를 추출해 콘솔에 출력하는 간결한 예제입니다. 이를 통해 **read damaged word file** 내용을 충돌 없이 읽을 수 있음을 보여줍니다. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +원본 파일에 테이블이나 이미지가 손상돼 있었다면 텍스트 출력에서 해당 부분은 단순히 제외됩니다. 나머지 문서는 그대로 유지됩니다. + +## 5단계: 깨끗한 사본 저장 (선택 사항) + +복구 후 사용자에게 새롭고 깨끗한 파일 버전을 제공하고 싶을 때가 많습니다. 동일한 형식으로 저장하면 이후 프로세스와의 호환성이 보장됩니다. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +이제 **recover damaged docx** 파일을 안전하게 이메일에 첨부하거나 다른 서비스에 전달할 수 있습니다. + +## 전체 작업 예제 + +모두 합치면 다음과 같은 완전한 실행 가능한 프로그램이 됩니다. 새 콘솔 프로젝트에 붙여넣고 파일 경로를 조정한 뒤 F5를 눌러 실행하세요. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**예상 출력** (파일에 단일 문단 “Hello world!”와 일부 손상된 XML이 포함된 경우): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +프로그램이 절대 충돌하지 않는 것을 확인할 수 있습니다—소스 파일이 부분적으로 손상되었음에도 불구하고 말이죠. 이것이 Aspose.Words를 사용한 **recover corrupted docx**의 핵심입니다. + +## 일반적인 질문 및 엣지 케이스 + +### 파일을 완전히 읽을 수 없는 경우는? + +`AutoRecover`에도 한계가 있습니다. zip 컨테이너 자체가 복구 불가능할 정도로 손상된 경우 Aspose.Words는 `CorruptedFileException`을 발생시킵니다. 이때는 **recover corrupted docx**를 다시 시도하기 전에 서드파티 zip 복구 도구가 필요할 수 있습니다. + +### 다른 형식(e.g., `.doc`, `.odt`)을 복구할 수 있나요? + +물론 가능합니다. 동일한 `LoadOptions`가 Aspose.Words가 지원하는 모든 형식에 적용됩니다. 파일 확장자를 바꾸면 라이브러리가 원본 형식을 자동으로 감지합니다. 따라서 `.doc`나 `.rtf`와 같은 **recover damaged docx**‑와 유사한 파일도 동일한 코드로 복구할 수 있습니다. + +### 메모리에 모두 로드하지 않고 큰 문서를 처리하려면 어떻게 해야 하나요? + +기가바이트 규모 파일의 경우 `LoadOptions.LoadFormat` 같은 **load options**를 활성화하거나 페이지 단위로 스트리밍할 수 있습니다. 그러나 복구 알고리즘은 전체 패키지를 읽어야 하므로 매우 큰 손상 파일은 메모리 사용량이 증가할 수 있습니다. + +### 어떤 부분이 손실되었는지 알 수 있는 방법이 있나요? + +로드 후 `document.GetChildNodes(NodeType.Any, true)`를 검사하고 기대되는 기준값과 개수를 비교하면 됩니다. 누락된 테이블, 이미지, 헤더 등은 노드 컬렉션에 나타나지 않으며, 이를 통해 정확히 어떤 부분이 **recover damaged docx** 되었는지 로그에 남겨 사용자에게 알릴 수 있습니다. + +## 신뢰할 수 있는 복구를 위한 전문가 팁 + +- **Validate the input file size**를 로드하기 전에 수행하세요; 0바이트 파일은 항상 실패합니다. +- `DocumentLoadingException`을 잡아 `RecoveryMode` 결과를 로그에 남기고 예외 메시지를 저장하세요; 여기에는 건너뛰어진 부분에 대한 단서가 종종 포함됩니다. +- 웹 서비스에서 업로드를 처리할 때는 **Run the recovery on a background thread**를 사용해 요청 응답성을 유지하세요. +- **Combine with a checksum**(예: MD5)를 사용해 복구된 파일이 원본과 다른지 감지하고, 필요에 따라 두 버전을 모두 보관할지 결정하세요. + +## 결론 + +우리는 **recover corrupted docx** 파일을 C#에서 **setting recovery mode**를 `AutoRecover`로 지정하고, 문서를 안전하게 로드한 뒤 살아남은 텍스트를 추출하고, 필요에 따라 깨끗한 사본을 저장하는 방법을 보여주었습니다. 이 접근 방식으로 **how to load docx** 파일을 예외 없이 로드하고, 외부 도구 없이 **read damaged word file** 내용을 신뢰성 있게 얻을 수 있습니다. + +다음 단계는? `RecoveryMode.AutoRecover`를 `RecoveryMode.NoRecovery`와 교체해 차이를 확인하거나, 비밀번호 처리와 글꼴 대체를 제어하는 `LoadOptions` 속성을 실험해 보세요. 또한 복구 루틴을 업로드를 받아 복구된 파일을 반환하는 ASP.NET Core API에 통합하면 기업 문서 관리 파이프라인에 최적화됩니다. + +Word 문서 복구에 대해 더 궁금한 점이 있거나, 커스텀 콜백으로 **recover damaged docx** 파일을 보는 방법을 알고 싶다면 아래에 댓글을 남겨 주세요. Happy coding! + +![복구된 문서 일러스트 – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "손상된 docx 복구") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-markdownsaveoptions/_index.md b/words/korean/net/programming-with-markdownsaveoptions/_index.md index f1dbf065f8..e3336c016d 100644 --- a/words/korean/net/programming-with-markdownsaveoptions/_index.md +++ b/words/korean/net/programming-with-markdownsaveoptions/_index.md @@ -22,7 +22,7 @@ | 제목 | 설명 | | --- | --- | | [표 내용 정렬을 사용하여 마크다운으로 내보내기](./export-into-markdown-with-table-content-alignment/) | Aspose.Words for .NET을 사용하여 정렬된 표가 있는 Word 문서를 Markdown으로 내보내는 방법을 알아보세요. 완벽한 Markdown 표를 만드는 단계별 가이드를 따라해 보세요. | -| [이미지 폴더 설정](./set-images-folder/) Aspose.Words for .NET을 사용하여 Word 문서를 적절한 표 정렬을 통해 Markdown으로 변환하세요. 완벽한 결과를 얻으려면 자세한 가이드를 따르세요. | +| [이미지 폴더 설정](./set-images-folder/) | Aspose.Words for .NET을 사용하여 Word 문서를 적절한 표 정렬을 통해 Markdown으로 변환하세요. 완벽한 결과를 얻으려면 자세한 가이드를 따르세요. | | [Word를 PDF로 저장하고 손상된 Word 복구 – C#에서 Word를 Markdown으로 변환](./save-word-as-pdf-and-recover-corrupted-word-convert-word-to/) | | | [접근성 PDF 만들기 및 Word를 Markdown으로 변환 – 전체 C# 가이드](./create-accessible-pdf-and-convert-word-to-markdown-full-c-gu/) | Aspose.Words for .NET을 사용하여 접근성 PDF를 생성하고 Word를 Markdown으로 변환하는 전체 C# 가이드 | | [Markdown 사용 방법: LaTeX 수식이 포함된 DOCX를 Markdown으로 변환](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | Aspose.Words for .NET을 사용하여 LaTeX 수식이 포함된 DOCX 파일을 정확히 Markdown으로 변환하는 단계별 가이드 | @@ -41,6 +41,7 @@ | [DOCX를 Markdown으로 변환할 때 이미지 이름 바꾸기](./how-to-rename-images-when-converting-docx-to-markdown/) | Aspose.Words for .NET을 사용하여 DOCX를 Markdown으로 변환하면서 이미지 파일 이름을 원하는 대로 바꾸는 방법을 단계별로 안내합니다. | | [Aspose.Words를 사용하여 docx를 markdown으로 저장 – 전체 C# 가이드](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Aspose.Words for .NET을 사용하여 docx 파일을 markdown 형식으로 저장하는 전체 C# 가이드를 제공합니다. | | [Word 이미지 저장 – Aspose로 Word를 Markdown으로 변환](./save-word-images-convert-word-to-markdown-with-aspose/) | Aspose.Words for .NET을 사용하여 Word 문서의 이미지를 추출하고 Markdown으로 변환하는 방법을 단계별로 안내합니다. | +| [docx를 markdown으로 저장 – Aspose.Words로 Word 수학을 LaTeX로 내보내기](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Aspose.Words for .NET을 사용해 docx를 markdown으로 저장하면서 Word 수학을 LaTeX 형식으로 내보내는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/korean/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..eea7f6eefc --- /dev/null +++ b/words/korean/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words를 사용해 docx를 markdown으로 저장 – 워드를 markdown으로 변환하고, 수식을 LaTeX로 + 내보내며, markdown 이미지 해상도를 한 번에 설정하는 원활한 워크플로우를 배워보세요. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: ko +og_description: Aspose.Words를 사용하여 docx를 markdown으로 저장합니다. 이 튜토리얼에서는 워드를 markdown으로 + 변환하고, 수식을 LaTeX로 내보내며, markdown 이미지 해상도를 설정하는 방법을 보여줍니다. +og_title: docx를 markdown으로 저장 – Word 수식을 LaTeX로 내보내는 완전 가이드 +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx를 markdown으로 저장 – Aspose.Words로 Word 수식을 LaTeX로 내보내기 +url: /ko/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx를 markdown으로 저장 – Aspose.Words로 Word 수학을 LaTeX로 내보내기 + +Ever needed to **save docx as markdown** but got stuck on how to keep those Office Math equations looking sharp? You're not the only one. Most developers hit a wall when the default conversion drops equations as blurry images, forcing a manual rewrite in LaTeX. + +좋은 소식: Aspose.Words가 이 작업을 대신해 줍니다. 이 튜토리얼에서는 **convert word to markdown**하고 엔진에 **export equations to latex**하도록 지시하며, 문서 전체에 대해 **set markdown image resolution**도 설정합니다. 최종적으로는 LaTeX 준비된 수식과 고해상도 이미지를 포함한 깔끔한 `.md` 파일을 한 번의 명령으로 생성할 수 있습니다. + +## 배울 내용 + +- Office Math 객체를 포함한 `.docx`를 로드하는 방법. +- `MarkdownSaveOptions` 중 **export equations to latex**와 **set markdown image resolution**을 제어하는 속성. +- 어떤 .NET 프로젝트에도 붙여넣을 수 있는 완전하고 실행 가능한 C# 코드 스니펫. +- 누락된 폰트나 지원되지 않는 수식 기능 등 일반적인 문제를 해결하기 위한 팁. + +**Prerequisites**: .NET 6+ (or .NET Framework 4.6+), Aspose.Words for .NET 라이선스, 그리고 C#에 대한 기본적인 이해가 필요합니다. 콘솔 앱을 만드는 데 익숙하다면 바로 시작할 수 있습니다. + +--- + +## Step 1 – docx를 markdown으로 저장: Word 파일 로드 + +먼저 필요한 것은 소스 `.docx`를 가리키는 `Document` 객체입니다. 장을 복사하기 전에 책을 여는 것과 같은 개념입니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Why this matters*: 문서에 수식이 없으면 **export equations to latex** 단계는 아무 작업도 하지 않지만 나머지 변환은 계속 진행됩니다. 이 검사는 출력 Markdown에 LaTeX 블록이 없는 이유를 궁금해 하는 상황을 방지해 줍니다. + +--- + +## Step 2 – Export Equations to LaTeX 설정 + +Aspose.Words를 사용하면 Office Math가 어떻게 렌더링될지 결정할 수 있습니다. 기본적으로 PNG 이미지로 변환되기 때문에 많은 튜토리얼에서 거친 markdown 파일이 생성됩니다. `OfficeMathExportMode`를 `LaTeX`로 전환하면 깔끔하고 복사‑붙여넣기 가능한 수식을 얻을 수 있습니다. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Why `OfficeMathExportMode.LaTeX`?* LaTeX는 과학 출판의 공통 언어입니다. 이후 static‑site generator나 Jupyter notebook으로 markdown을 렌더링하면 수식이 어떤 확대 수준에서도 선명하게 표시됩니다. + +--- + +## Step 3 – Markdown 이미지 해상도 설정 (수학 외 콘텐츠용) + +수학에 초점을 맞추고 있지만 대부분의 Word 문서에는 사진, 차트, 임베드된 SVG 등도 포함됩니다. `ImageResolution` 속성은 Aspose.Words가 이러한 자산을 래스터화하는 방식을 제어합니다. **300 DPI** 값은 화면과 인쇄 모두에 적합한 균형점입니다. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: markdown을 웹에서만 표시한다면 파일 크기를 줄이기 위해 150 DPI로 낮출 수 있습니다. 반대로 인쇄용 PDF를 만들 경우 600 DPI로 높이면 좋습니다. + +--- + +## Step 4 – 변환 실행 – Word 수학을 LaTeX로 변환 + +이제 모든 설정이 완료되었으니 실제 변환은 한 줄로 수행됩니다. Aspose.Words가 백그라운드에서 무거운 작업을 처리합니다. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: 생성된 `.md` 파일을 열면 다음과 같은 내용이 표시됩니다: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +LaTeX 블록(`$...$` 및 `$$...$$`)이 이전 PNG 조각을 대체한 것을 확인하세요. 아래쪽 이미지는 여전히 PNG이며, 요청한 대로 300 DPI로 렌더링되었습니다. + +--- + +## Step 5 – 일반적인 엣지 케이스 및 해결 방법 + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (예: Cambria Math가 설치되지 않음) | LaTeX 출력에 알 수 없는 기호가 포함될 수 있습니다. | 서버에 누락된 폰트를 설치하거나 변환 전에 문서에 포함시킵니다. | +| **Complex equations** (사용자 정의 구분자를 가진 행렬) | `LaTeX` 모드에도 불구하고 Aspose.Words가 이미지로 대체할 수 있습니다. | 최신 Aspose.Words 버전으로 업그레이드하세요; 라이브러리는 지속적으로 수식 지원 범위를 개선하고 있습니다. | +| **Large documents** ( > 50 MB ) | 메모리 압박으로 `OutOfMemoryException`이 발생할 수 있습니다. | `LoadOptions`에 `LoadFormat.Docx`를 사용해 파일을 스트리밍하거나, 변환 전에 문서를 섹션으로 나눕니다. | +| **Image size too big** | Markdown 파일이 커져 static‑site 빌드가 느려집니다. | 웹 전용 시나리오에서는 `ImageResolution`을 150 DPI로 낮춥니다 (Step 3 참고). | + +--- + +## Step 6 – 전체 예제 통합 + +아래는 `Program.cs`에 복사‑붙여넣기 할 수 있는 *전체* 콘솔 앱 프로그램입니다. 앞서 논의한 모든 내용과 약간의 추가 오류 처리를 포함하고 있습니다. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +프로그램을 실행(`dotnet run`)하면 모든 수식을 LaTeX로 보존하면서 **save docx as markdown**하는 markdown 파일을 얻을 수 있습니다. 수식을 수동으로 복사‑붙여넣기 할 필요도 없고, 보기 흉한 래스터 이미지도 없습니다. + +--- + +## 결론 + +우리는 Aspose.Words를 사용해 **saving docx as markdown** 전체 과정을 살펴보았습니다. Word 파일 로드부터 **export equations to latex**와 **set markdown image resolution** 설정까지. 최종 스니펫은 프로덕션에 바로 사용할 수 있으며, **convert word to markdown**가 필요한 모든 .NET 프로젝트에 바로 적용할 수 있습니다. + +다음은? 생성된 `.md` 파일을 Hugo나 Jekyll 같은 static‑site generator에 넣어 수식이 아름답게 렌더링되는 것을 확인해 보세요. **convert word math latex**를 다른 형식(PDF, HTML)으로 변환해야 한다면 `MarkdownSaveOptions`를 `PdfSaveOptions` 또는 `HtmlSaveOptions`로 교체하면 됩니다—동일한 `OfficeMathExportMode` 플래그가 모두 적용됩니다. + +워크플로에 Azure Blob 스토리지에서 Word 파일을 가져오거나 API에서 스트리밍하는 등 변형이 있나요? 동일한 패턴을 적용하면 됩니다; 파일 시스템 `Document` 생성자를 스트림 기반 생성자로 교체하면 됩니다. + +자유롭게 실험해 보시고, 댓글에 이 방법이 변환 문제를 어떻게 해결했는지 알려 주세요. 즐거운 코딩 되세요! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-pdfsaveoptions/_index.md b/words/korean/net/programming-with-pdfsaveoptions/_index.md index c438d2c320..986e91aad6 100644 --- a/words/korean/net/programming-with-pdfsaveoptions/_index.md +++ b/words/korean/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ Aspose.Words for .NET 튜토리얼에서는 PDFSaveOptions를 사용한 워드 | [C#에서 접근 가능한 PDF 만들기 – PDF 접근성 튜토리얼](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Aspose.Words for .NET을 사용하여 C#에서 접근성 표준을 충족하는 PDF를 만드는 방법을 단계별로 안내합니다. | | [Word에서 접근 가능한 PDF 만들기 – 완전 가이드](./create-accessible-pdf-from-word-complete-guide/) | Aspose.Words for .NET을 사용하여 Word 문서를 접근성 높은 PDF로 변환하는 전체 단계별 가이드 | | [접근성 PDF 만들기 – PDF/UA 준수를 위한 단계별 가이드](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Aspose.Words for .NET을 사용하여 PDF/UA 표준을 충족하는 접근성 PDF를 만드는 방법을 단계별로 안내합니다. | +| [Aspose.Words를 사용하여 문서를 PDF로 저장 – 완전 C# 가이드](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words와 C#을 활용해 문서를 PDF로 변환하는 전체 단계별 가이드를 확인하세요. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/korean/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..8a82f2a312 --- /dev/null +++ b/words/korean/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: C#에서 Aspose.Words를 사용하여 문서를 PDF로 저장하는 방법을 배웁니다. 이 튜토리얼에서는 Word를 PDF로 + 변환하고, 수학 LaTeX를 내보내며, 누락된 글꼴을 처리하는 방법도 다룹니다. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: ko +og_description: Aspose.Words를 사용하여 문서를 손쉽게 PDF로 저장하세요. 이 가이드는 Word를 PDF로 변환하고, 수학 + LaTeX를 내보내며, 누락된 글꼴을 처리하는 방법도 보여줍니다. +og_title: Aspose.Words를 사용하여 문서를 PDF로 저장 – 완전한 C# 가이드 +tags: +- Aspose.Words +- C# +- PDF generation +title: Aspose.Words를 사용하여 문서를 PDF로 저장하기 – 완전한 C# 가이드 +url: /ko/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words를 사용하여 문서를 PDF로 저장 – 완전 C# 가이드 + +Word 파일에서 접근성 기능을 잃지 않고 **문서를 PDF로 저장하는 방법**이 궁금하신가요? 여러분만 그런 것이 아닙니다—개발자들은 수학 방정식을 보존하고 누락된 글꼴을 우아하게 처리하면서 Word를 PDF로 변환할 수 있는 신뢰할 만한 방법을 지속적으로 찾고 있습니다. + +이 튜토리얼에서는 **문서를 PDF로 저장**할 뿐만 아니라 **Word를 PDF로 변환**, **수학 LaTeX 내보내기**, **누락된 글꼴 처리**를 최신 Aspose.Words for .NET을 사용해 단계별로 구현하는 방법을 안내합니다. 마지막까지 따라오시면 접근성 감사를 위한 PDF/UA‑2 준수 파일을 생성하는 실행 가능한 C# 프로그램을 얻게 됩니다. + +## 필요 사항 + +- .NET 6 이상 (코드는 .NET Core 및 .NET Framework에서도 동작) +- Aspose.Words for .NET 25.10 이상 – Aspose 웹사이트에서 무료 체험판을 받을 수 있습니다 +- 최소 하나의 떠다니는 도형과 수학 방정식을 포함한 간단한 Word 문서 (`input.docx`) – **수학 LaTeX 내보내기** 기능을 확인하려면 필요합니다 +- Visual Studio 2022 (또는 선호하는 IDE) + +> **Pro tip:** CI/CD 파이프라인을 사용 중이라면 프로젝트 파일에 Aspose.Words NuGet 패키지를 추가하세요: + +```xml + +``` + +이제 코드로 들어가 보겠습니다. + +## 1단계: 자동 복구와 함께 원본 문서 로드 + +실제 Word 파일을 다루다 보면 손상된 섹션이나 누락된 리소스를 마주칠 수 있습니다. 자동 복구를 활성화하면 로드 과정에서 예외가 발생하지 않습니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**왜 중요한가:** +`RecoveryMode.AutoRecover`는 형식이 잘못된 입력에서도 파이프라인이 중단되는 것을 방지합니다. 이는 **Word를 PDF로 변환**할 때 대량 처리에 특히 유용합니다. + +## 2단계: 전체 접근성을 위한 PDF 저장 옵션 설정 + +PDF/UA‑2는 접근 가능한 PDF에 대한 ISO 표준입니다. 몇 가지 플래그만 설정하면 스크린 리더가 탐색할 수 있는 파일을 만들 수 있고, 수학 방정식은 숨겨진 LaTeX 형태로 내보내집니다. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**핵심 포인트:** + +- **ExportFloatingShapesAsInlineTag** – 결과 PDF가 원본 레이아웃을 유지하면서 의미적으로 올바르게 표시되도록 합니다. +- **OfficeMathExportMode.LaTeX** – **수학 LaTeX 내보내기** 요구 사항을 만족시켜, 필요 시 다운스트림 도구가 방정식을 추출할 수 있게 합니다. + +## 3단계: 경고 수집 (예: 누락된 글꼴) + +문서를 변환할 때 누락된 글꼴은 흔한 문제입니다. Aspose.Words는 `WarningCallback`을 통해 이러한 문제를 보고할 수 있습니다. 우리는 이를 수집해 나중에 로그를 남기거나 조치를 취할 수 있게 합니다. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**왜 신경 써야 하는가:** +소스 문서가 서버에 설치되지 않은 글꼴을 사용하면 PDF가 기본 글꼴로 대체되어 레이아웃이 깨질 수 있습니다. **누락된 글꼴을 처리**함으로써 사용자에게 경고를 보내거나 대체 글꼴을 포함시킬 수 있습니다. + +## 4단계: 접근 가능한 PDF로 문서 저장 + +이제 변환을 실제로 수행합니다. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +문제가 없으면 숨겨진 LaTeX와 떠다니는 도형에 대한 적절한 태깅이 포함된 PDF/UA‑2 파일이 생성됩니다. + +## 5단계: 수집된 경고 검토 (선택 사항이지만 권장) + +저장 작업이 끝난 후, 수집된 경고를 순회하며 로그에 남길 수 있습니다. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +예시 출력은 다음과 같습니다: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +초기에 이러한 메시지를 확인하면 **누락된 글꼴을 처리**하여 최종 사용자에게 영향을 주기 전에 문제를 해결할 수 있습니다. + +## 전체 작업 예제 + +모든 코드를 하나로 합치면 다음과 같은 완전한 실행 프로그램이 됩니다. 자리표시자 경로를 실제 경로로 교체하세요. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**예상 결과:** +- `output.pdf`가 PDF/UA‑2를 준수합니다. +- 모든 떠다니는 도형이 인라인 그림으로 태깅됩니다. +- 모든 Office Math 객체가 숨겨진 LaTeX 형태로 포함됩니다 (PDF 구조를 검사하면 확인 가능). +- 글꼴 관련 이슈가 콘솔에 출력되어 **누락된 글꼴을 처리**할 기회를 제공합니다. + +![Diagram showing the flow from Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flow diagram for saving document as pdf") + +*이미지 대체 텍스트:* **Aspose.Words를 사용하여 문서를 PDF로 저장하는 흐름도** + +## 자주 묻는 질문 및 예외 상황 + +### 오래된 Aspose.Words 버전을 사용하고 있다면? + +`OfficeMathExportMode.LaTeX` 플래그는 25.10에서 도입되었습니다. 이전 버전에서도 **Word를 PDF로 변환**은 가능하지만 수학 방정식이 라스터화되어 내보내집니다. 최상의 접근성을 위해 최신 버전으로 업그레이드하세요. + +### 글꼴 대체를 위해 커스텀 글꼴을 포함할 수 있나요? + +예. `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll`을 `Save` 호출 전에 설정하면 PDF에 필요한 모든 글리프가 포함됩니다. 이는 **누락된 글꼴을 처리**하는 데도 도움이 됩니다. + +### PDF/UA‑2 준수를 어떻게 확인하나요? + +Adobe Acrobat Pro에서 파일을 열고 → “Print Production” → “Preflight”으로 이동합니다. “PDF/A‑2b” 또는 “PDF/UA‑2” 프로파일을 선택하면 위반 사항이 보고됩니다. + +### 비밀번호로 보호된 Word 파일은 어떻게 처리하나요? + +`Password`를 포함한 `LoadOptions`로 문서를 로드합니다. 예시: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +그 외 파이프라인은 동일하게 유지됩니다. + +## 결론 + +Aspose.Words를 사용해 C#에서 **문서를 PDF로 저장**하는 전체 과정을 살펴보았습니다. 또한 **Word를 PDF로 변환**, **수학 LaTeX 내보내기**, **누락된 글꼴 처리**를 통해 접근성 높은 PDF/UA‑2 파일을 만드는 방법을 시연했습니다. + +코드를 실행해 보고 `PdfSaveOptions`(예: 이미지 압축, PDF/A‑2b) 를 다양하게 실험해 보세요. 그리고 문서 처리 서비스에 통합해 보시기 바랍니다. 더 깊이 들어가고 싶다면 Aspose의 PDF 전용 라이브러리를 활용해 후처리나 디지털 서명을 추가하는 것도 고려해 보세요. + +다루고 싶은 시나리오가 더 있나요? 댓글을 남기시거나 **PDF 조작**, **이미지 추출**, **일괄 변환**에 관한 다른 가이드를 확인해 보세요. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-shapes/_index.md b/words/korean/net/programming-with-shapes/_index.md index 626c61e0e3..dfa560fdfa 100644 --- a/words/korean/net/programming-with-shapes/_index.md +++ b/words/korean/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Aspose.Words for .NET을 사용하고 이 튜토리얼을 따라 하면 Word 문 | [C#를 사용하여 Word에서 사각형 모양 만들기 – 단계별 가이드](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Aspose.Words for .NET을 사용해 C#로 Word 문서에 사각형 도형을 삽입하고 설정하는 방법을 단계별로 안내합니다. | | [Aspose.Words 도형 그림자 튜토리얼 – C#에서 Word 도형에 그림자 추가](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Aspose.Words for .NET을 사용하여 C# 코드로 Word 도형에 그림자를 적용하는 방법을 단계별로 안내합니다. | | [그림자 사각형 모양이 있는 빈 Word 문서 만들기 – 단계별 가이드](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Aspose.Words for .NET을 사용하여 그림자 효과가 있는 사각형 모양을 포함한 빈 Word 문서를 만드는 방법을 단계별로 안내합니다. | +| [Aspose.Words에서 그림자 이동 방법 – 완전 C# 가이드](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Aspose.Words를 사용하여 C# 코드로 도형 그림자를 이동시키는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/korean/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..f38fcab600 --- /dev/null +++ b/words/korean/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-01 +description: C#를 사용하여 Aspose.Words에서 도형의 그림자를 이동하는 방법. 도형에 그림자를 추가하고, 흐림 효과를 조정하며, + 투명도를 설정하고, 몇 분 안에 그림자를 회전시키는 방법을 배워보세요. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: ko +og_description: C#를 사용하여 Aspose.Words에서 도형의 그림자를 이동하는 방법. 이 튜토리얼에서는 도형에 그림자를 추가하고, + 흐림 효과를 변경하며, 투명도를 설정하고, 그림자를 회전하는 방법을 보여줍니다. +og_title: Aspose.Words에서 그림자 이동하기 – 완전 C# 가이드 +tags: +- Aspose.Words +- C# +- Document Automation +title: Aspose.Words에서 그림자를 이동하는 방법 – 완전한 C# 가이드 +url: /ko/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words에서 그림자 이동하기 – 완전한 C# 가이드 + +Word 문서 안의 도형에 **그림자를 이동하는 방법**을 수동으로 Word를 열지 않고도 궁금해 본 적 있나요? 일상 업무에서 도형의 그림자를 프로그래밍으로 조정해야 할 일이 자주 있었습니다—예쁘게 다듬은 보고서든 동적인 템플릿이든 말이죠. 좋은 소식은? Aspose.Words를 사용하면 몇 줄의 코드만으로 가능하고, **도형에 그림자 추가**, **블러 변경 방법**, **투명도 설정 방법**, **그림자 회전 방법**도 한 번에 배울 수 있습니다. + +이 튜토리얼에서는 실제 시나리오를 따라갑니다: 이미 도형이 포함된 기존 DOCX 파일을 로드하고, 그림자의 위치, 부드러움, 불투명도, 방향을 조정한 뒤 결과를 저장합니다. 끝까지 진행하면 .NET 프로젝트 어디에든 삽입할 수 있는 재사용 가능한 코드 조각을 얻고, 각 속성이 왜 중요한지도 이해하게 됩니다. + +## Prerequisites – 시작하기 전에 준비할 것 + +- **Aspose.Words for .NET** (버전 23.12 이상). `Install-Package Aspose.Words` 명령으로 NuGet에서 가져올 수 있습니다. +- .NET 6+ 개발 환경 (Visual Studio, VS Code, Rider 등 원하는 도구). +- 최소 하나의 도형(사각형, 원, 그림 등)이 포함된 입력 Word 파일(`input.docx`). +- 기본적인 C# 문법에 대한 이해—특별한 지식은 필요 없습니다. + +위 항목 중 하나라도 부족하다면 잠시 멈춰 라이브러리를 설치하세요; 이후 가이드는 패키지가 이미 참조된 것으로 가정합니다. + +## Step 1: Load the Document and Grab the Target Shape – **How to Move Shadow** 시작 + +먼저 원본 문서를 로드하고 수정하려는 도형을 찾습니다. Aspose.Words는 모든 객체(단락, 표, 도형)를 트리 구조의 노드로 취급하므로 직접 쿼리할 수 있습니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Why this matters:** 문서를 한 번만 로드하고 같은 `Document` 인스턴스를 재사용하면 효율적입니다. `GetChild` 호출은 인덱스가 범위를 벗어나면 `null`을 반환하므로, 도형이 없을 경우에도 안전하게 처리할 수 있습니다. + +## Step 2: Adjust the Blur Radius – Master **How to Change Blur** + +부드러운 그림자는 전문적인 느낌을 주고, 거친 가장자리는 저렴해 보일 수 있습니다. `BlurRadius` 속성은 포인트 단위(1 pt ≈ 1/72 inch)로 부드러움을 제어합니다. 여기서는 8 pt로 올려보겠습니다. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** 기본 블러는 0.5 pt입니다. 5 pt 이상이면 눈에 띄기 시작하지만, 너무 크게 하면 도형이 페이지에서 떨어진 듯 보일 수 있으니 주의하세요. + +## Step 3: Set Transparency – The Answer to **How to Set Transparency** + +투명도는 그림자가 얼마나 투명한지를 결정합니다. `0`은 완전 불투명, `1`은 완전 투명을 의미합니다. 은은한 효과를 위해 `0.3`(30 % 투명)을 사용합니다. + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Why you might care:** 도형이 어두운 경우 완전 불투명 그림자는 아래 텍스트를 가릴 수 있습니다. 투명도를 조절하면 문서 가독성을 유지하면서 깊이감을 줄 수 있습니다. + +## Step 4: Move the Shadow – The Core of **How to Move Shadow** + +`Distance` 속성은 그림자가 도형으로부터 얼마나 떨어져 있는지를 포인트 단위로 정의합니다. 거리를 크게 하면 그림자가 더 멀리 떨어져 더 극적인 효과를 줍니다. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **What if you need a tiny offset?** `Distance`를 `0`으로 설정하면 그림자가 도형 바로 뒤에 위치해, 엠보싱 효과 등에 활용할 수 있습니다. + +## Step 5: Rotate the Light Source – Solving **How to Rotate Shadow** + +그림자는 단순히 아래로만 떨어지는 것이 아니라 광원의 각도에 따라 달라집니다. `Angle` 속성(도 단위)은 그림자를 도형 주위에 회전시킵니다. 여기서는 45°로 기울여 보겠습니다. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Quick experiment:** `90`을 입력하면 오른쪽 그림자가, `-30`을 입력하면 왼쪽으로 기울어진 그림자가 생성됩니다. 시각적인 변화가 즉시 나타납니다. + +## Step 6: Save the Document – Seeing the Result of **Add Shadow to Shape** + +그림자 설정을 마쳤으니 문서를 디스크에 저장합니다. 원본을 덮어쓸 수도 있고 새 파일을 만들 수도 있습니다; 예제에서는 새로운 출력 파일을 사용합니다. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Expected output:** `output.docx`를 열어보세요. 도형의 그림자가 더 부드럽고, 약간 오프셋되며, 반투명하고, 45° 각도로 기울어져 있을 것입니다. `input.docx`와 나란히 비교하면 차이가 확연히 보입니다. + +### Full Working Example (Copy‑Paste Ready) + +아래는 전체 프로그램을 하나의 블록에 넣은 예시입니다. 새 콘솔 프로젝트에 붙여넣고 `YOUR_DIRECTORY`를 실제 폴더 경로로 바꾼 뒤 실행하세요. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Common Questions & Edge Cases + +### What if the document has multiple shapes? + +다음과 같이 모든 도형을 순회할 수 있습니다: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Can I add a shadow to a shape that currently has none? + +물론 가능합니다. `ShadowFormat` 객체는 항상 존재하므로, 단순히 활성화하면 됩니다: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Does this work with pictures and SmartArt? + +네. `Shape`를 상속받는 모든 노드—그림, 차트, SmartArt 등—는 `ShadowFormat`을 제공하며 동일한 속성을 사용할 수 있습니다. + +### How do I control the shadow color? + +`Color` 속성을 사용하세요: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Compatibility concerns? + +Aspose.Words 23.12+는 .NET 6, .NET Core 3.1, .NET Framework 4.6.2 이상을 지원합니다. 여기서 보여준 API는 이러한 버전 모두에서 안정적입니다. + +## Conclusion + +우리는 Aspose.Words를 이용해 도형의 **그림자 이동** 방법을 다루었고, 그 과정에서 **도형에 그림자 추가**, **블러 변경**, **투명도 설정**, **그림자 회전**도 함께 배웠습니다. 완전하고 실행 가능한 예제를 통해 몇 초 만에 도형 그림자를 조정할 수 있어, Word를 직접 열지 않아도 문서를 깔끔하고 전문적으로 만들 수 있습니다. + +다음 단계는? **조건부 서식**과 결합해 보세요—예를 들어, 제목이나 특정 크기 이상의 차트에만 더 깊은 그림자를 적용한다든지. 혹은 도형 자체에 **그라디언트 채우기**를 적용해 눈에 띄는 디자인을 만들 수도 있습니다. + +문제가 발생하면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되시고, 그림자가 언제나 원하는 위치에 떨어지길 바랍니다! + +![그림자 이동 효과를 보여주는 다이어그램 – 그림자 이동 예시](https://example.com/images/shadow-demo.png "그림자 이동 예시") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/basic-conversions/_index.md b/words/polish/net/basic-conversions/_index.md index a8c4a7ea1a..1b15ebf476 100644 --- a/words/polish/net/basic-conversions/_index.md +++ b/words/polish/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Basic Conversions przeprowadzi Cię przez podstawowe konwersje dokumentów przy | [Zapisz PDF do formatu Word (Docx)](./pdf-to-docx/) | Dowiedz się, jak przekonwertować plik PDF na dokument Word (Docx) za pomocą Aspose.Words dla .NET w tym szczegółowym przewodniku krok po kroku. Idealne dla programistów. | | [Jak wyeksportować LaTeX z Worda – przewodnik krok po kroku](./how-to-export-latex-from-word-step-by-step-guide/) | Dowiedz się, jak wyeksportować dokument Word do formatu LaTeX przy użyciu Aspose.Words dla .NET. Szczegółowy przewodnik krok po kroku. | | [Zapisz Word jako PDF przy użyciu Aspose.Words – Kompletny przewodnik C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Dowiedz się, jak w prosty sposób zapisać dokument Word jako PDF przy użyciu Aspose.Words w C#. Szczegółowy przewodnik krok po kroku. | +| [Zapisz Word jako PDF przy użyciu Aspose.Words – Kompletny przewodnik](./save-word-as-pdf-with-aspose-words-complete-guide/) | Dowiedz się, jak w prosty sposób zapisać dokument Word jako PDF przy użyciu Aspose.Words. Szczegółowy przewodnik krok po kroku. | | [Zapisz DOCX jako PDF przy użyciu Aspose.Words – Kompletny przewodnik C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Dowiedz się, jak w prosty sposób zapisać dokument DOCX jako PDF przy użyciu Aspose.Words w C#. Szczegółowy przewodnik krok po kroku. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/polish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index ebcdc2b359..94da04159e 100644 --- a/words/polish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/polish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,22 @@ --- category: general -date: 2025-12-29 -description: Jak wyeksportować LaTeX z Worda przy użyciu Aspose.Words – dowiedz się, - jak konwertować Word na LaTeX, zapisywać docx jako txt oraz obsługiwać równania - w czystym tekście. +date: 2026-05-01 +description: Dowiedz się, jak wyeksportować LaTeX z pliku Word, przekonwertować Word + na txt oraz zachować tabele przy użyciu Aspose.Words w C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: pl -og_description: Jak wyeksportować LaTeX z Worda za pomocą Aspose.Words. Ten przewodnik - pokazuje, jak przekonwertować Word na LaTeX, zapisać plik docx jako txt i zachować - równania w nienaruszonym stanie. -og_title: Jak wyeksportować LaTeX z Worda – Szybki samouczek C# +og_description: Dowiedz się, jak wyeksportować LaTeX z programu Word, przekonwertować + Word na zwykły tekst i zachować niezmieniony układ tabeli dzięki Aspose.Words. +og_title: Jak wyeksportować LaTeX z Worda – Kompletny samouczek C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Jak wyeksportować LaTeX z Worda – Przewodnik krok po kroku url: /pl/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -29,178 +26,213 @@ url: /pl/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Jak wyeksportować LaTeX z Worda – Przewodnik krok po kroku +# Jak wyeksportować LaTeX z Word – Kompletny samouczek C# -Zastanawiałeś się kiedyś **jak wyeksportować LaTeX z Worda** bez utraty tych trudnych równań Office Math? Nie jesteś jedyny. Wielu programistów napotyka problem, gdy próbują *convert Word to LaTeX* dla prac akademickich, raportów naukowych lub zautomatyzowanych potoków publikacji. +Zastanawiałeś się kiedyś **jak wyeksportować LaTeX** z dokumentu Word bez utraty jakichkolwiek równań matematycznych? Nie jesteś sam. Wielu programistów musi przekształcić plik .docx zawierający Office Math w czysty LaTeX, a jednocześnie **convert Word to txt** dla dalszego przetwarzania. W tym przewodniku przeprowadzimy Cię przez praktyczne, gotowe do uruchomienia rozwiązanie, które **zachowuje tabele**, daje plik tekstowy i zachowuje znacznik LaTeX dokładnie tam, gdzie go potrzebujesz. -W tym samouczku przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład w C#, który pokazuje **jak wyeksportować LaTeX** przy użyciu Aspose.Words, wyjaśnia **jak zapisać pliki txt** z oznaczeniami LaTeX, a także omawia niuanse **convert word equations latex**, aby nic nie zostało utracone w tłumaczeniu. - -> **Pro tip:** To samo podejście działa dla dowolnego .docx — wystarczy skierować kod na inną ścieżkę pliku. - ---- +Omówimy wszystko, od wczytania pliku źródłowego po dostosowanie `TxtSaveOptions`, aby wynik był zarówno czytelny dla człowieka, jak i przyjazny dla maszyny. Po zakończeniu będziesz w stanie **save docx as txt**, **convert Word to plain text**, oraz wiedzieć **how to preserve tables** podczas eksportu. Bez zewnętrznych skryptów, bez ręcznego kopiowania—tylko czysty kod C#, który możesz wstawić do dowolnego projektu .NET. ## Czego będziesz potrzebować -Zanim zaczniemy, upewnij się, że masz następujące wymagania wstępne: - -| Wymaganie | Dlaczego jest ważne | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words obsługuje nowoczesne środowiska .NET. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | Biblioteka wykonuje ciężką pracę parsowania Worda i generowania LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Aby zobaczyć konwersję LaTeX w działaniu. | -| **Visual Studio 2022** (or any IDE you like) | Ułatwia debugowanie i uruchamianie przykładu. | - -Jeśli nie zainstalowałeś jeszcze pakietu NuGet, uruchom: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (najnowsza wersja, 2024.x lub nowsza). Pakiet NuGet to `Aspose.Words`. +- Środowisko programistyczne .NET (Visual Studio, VS Code, Rider — dowolne). +- Plik Word (`.docx`) zawierający równania Office Math oraz przynajmniej jedną tabelę (abyśmy mogli zobaczyć magię zachowywania tabel). -To wszystko — żadnych dodatkowych DLL, żadnego COM interop, tylko czysta biblioteka zarządzana. +To wszystko. Jeśli już je masz, czytaj dalej; w przeciwnym razie pobierz pakiet NuGet i przykładowy DOCX, zanim zanurkujemy głębiej. --- -## Jak wyeksportować LaTeX z Worda – Przegląd +## Jak wyeksportować LaTeX z dokumentu Word -Poniżej znajduje się ogólny obraz tego, co osiągniemy: +Poniżej znajduje się sedno samouczka — trzy zwięzłe kroki, które odpowiadają na pytanie **how to export latex** jednocześnie obsługując cele drugorzędne: **convert word to txt**, **convert word to plain text**, **save docx as txt** oraz **how to preserve tables**. -1. **Load** źródłowy dokument Word (`.docx`). -2. **Configure** `TxtSaveOptions`, aby wszystkie obiekty Office Math były emitowane jako kod LaTeX. -3. **Save** dokument jako plik tekstowy (`.txt`), który możesz bezpośrednio podać do dowolnego kompilatora LaTeX. +### Krok 1: Wczytaj plik DOCX -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") - ---- - -## Krok 1: Załaduj dokument Word - -Na początek — otwórz .docx, który chcesz przekonwertować. Klasa `Document` abstrahuje cały podkład XML, zapewniając przyjazny model obiektowy. +Najpierw musimy odczytać dokument Word do obiektu `Aspose.Words.Document`. Ten krok jest taki sam, niezależnie od tego, czy później **convert word to txt**, czy **save docx as txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Dlaczego to jest ważne:** -Wczesne załadowanie pliku pozwala nam przejrzeć jego zawartość (np. policzyć równania) zanim zdecydujemy, jak go zserializować. Jeśli plik jest uszkodzony, `Document` zgłosi czytelny wyjątek, chroniąc Cię przed tajemniczymi wynikami później. +> **Dlaczego to ważne:** Wczytanie pliku tworzy w‑pamięci reprezentację wszystkich elementów Word — akapity, tabele i obiekty Office Math. Bez tego obiektu nie możesz manipulować opcjami eksportu. ---- +### Krok 2: Skonfiguruj `TxtSaveOptions` dla LaTeX i układu tabel -## Krok 2: Skonfiguruj TxtSaveOptions do eksportu LaTeX +Klasa `TxtSaveOptions` pozwala dokładnie kontrolować, jak generowany jest plik tekstowy. Dwie właściwości są kluczowe w naszym scenariuszu: -Magia dzieje się w `TxtSaveOptions`. Ustawiając `OfficeMathExportMode` na `LaTeX`, każdy obiekt Office Math jest przekształcany w odpowiadającą mu reprezentację LaTeX. +| Property | Co robi | Dlaczego jest potrzebne | +|----------|---------|------------------------| +| `OfficeMathExportMode` | Określa, jak renderowany jest Office Math. Ustawienie na `LaTeX` konwertuje równania do składni LaTeX. | To jest sedno **how to export latex**. | +| `PreserveTableLayout` | Gdy `true`, Aspose dodaje białe znaki, aby tabele zachowały wygląd siatki. | To spełnia **how to preserve tables**, gdy **convert word to txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Dlaczego wybraliśmy te ustawienia:** +> **Wskazówka:** Jeśli potrzebujesz tylko surowego LaTeX bez formatowania tabel, ustaw `PreserveTableLayout` na `false`. Plik stanie się mniejszy, ale utracisz wizualny podgląd tabeli. -- `OfficeMathExportMode.LaTeX` jest jedynym trybem, który gwarantuje wierne tłumaczenie matematyczne. -- `PreserveTableLayout` utrzymuje wygląd tabel tak jak w Wordzie, co jest przydatne, gdy później wstawiasz wynik do środowiska LaTeX `tabular`. -- UTF‑8 zapewnia, że znaki takie jak „α”, „β” czy „∑” przetrwają w drodze tam i z powrotem. +### Krok 3: Zapisz dokument jako tekst zwykły -Jeśli kiedykolwiek potrzebujesz **convert word to latex** bez opakowania w plain‑text, możesz zamiast tego przełączyć na `SaveFormat.LaTeX` — szybka wskazówka dla zaawansowanych scenariuszy. +Teraz zapisujemy dokument do pliku `.txt` używając opcji, które właśnie zdefiniowaliśmy. Ten pojedynczy wiersz realizuje **convert word to plain text**, **save docx as txt**, oraz oczywiście **how to export latex** jednocześnie. ---- +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` -## Krok 3: Zapisz dokument jako plik tekstowy +Po zakończeniu wywołania otwórz `output.txt`. Zobaczysz: -Teraz zapisujemy tekst zawierający LaTeX na dysk. Powstały `.txt` można później przemianować na `.tex` lub bezpośrednio przekazać do kompilatora LaTeX. +- Fragmenty LaTeX, np. `\frac{a}{b}` dla każdego równania Office Math. +- Tabele renderowane przy użyciu znaków `|` i `-`, zachowujące wyrównanie kolumn. +- Zwykłe akapity jako tekst, gotowe do dalszego przetwarzania. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Pełny działający przykład + +Łącząc wszystko razem, oto samodzielny program, który możesz skompilować i uruchomić już dziś: -// Save using the configured options -doc.Save(outputPath, txtOptions); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Co zobaczysz w `output.txt`:** +**Oczekiwany wynik** (fragment): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Wszystkie pozostałe akapity pojawiają się jako zwykły tekst, podczas gdy każde równanie Office Math jest otoczone środowiskiem LaTeX `equation` (lub `inline`, jeśli było w linii w Wordzie). To doskonale spełnia wymaganie **convert word equations latex**. +Zauważ, jak tabela zachowuje swoją siatkę, a równanie pojawia się jako czysty LaTeX. To idealne rozwiązanie, gdy **convert word to txt** i nadal potrzebujesz wiernego odwzorowania zarówno struktury, jak i matematyki. --- -## Przypadki brzegowe i często zadawane pytania +## Wskazówki dotyczące konwertowania Word do TXT i zachowywania tabel -| Sytuacja | Co zrobić | -|-----------|------------| -| **No equations in the source** | Konwersja nadal działa; otrzymasz po prostu zwykły tekst. Nie zostanie dodany dodatkowy kod LaTeX. | -| **Very large documents (>100 MB)** | Rozważ strumieniowanie wyjścia przy użyciu `MemoryStream`, aby uniknąć dużego zużycia pamięci. | -| **Unsupported Math constructs** | Aspose.Words obsługuje 99 % Office Math. W rzadkich przypadkach może być konieczne ręczne post‑procesowanie LaTeX. | -| **Need a .tex file instead of .txt** | Zmień `outputPath`, aby kończył się na `.tex` i opcjonalnie ustaw `txtOptions.Encoding` na `Encoding.UTF8`. | -| **Running on Linux/macOS** | Ten sam kod działa — wystarczy zapewnić, że ścieżki plików używają ukośników `/` lub `Path.Combine`. | +Choć podejście trójkrokowe działa w większości przypadków, projekty w rzeczywistym świecie często rzucają wyzwania. Poniżej praktyczne sugestie, które uczynią Twój potok **convert word to plain text** odpornym. ---- +### Używaj spójnego kodowania -## Jak zapisać TXT z równaniami LaTeX – Szybkie podsumowanie +`TxtSaveOptions` domyślnie używa UTF‑8, co obsługuje większość znaków. Jeśli potrzebujesz innej strony kodowej (np. starsze systemy oczekujące Windows‑1252), ustaw właściwość `Encoding`: -1. **Load** the .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` in `TxtSaveOptions`. -3. **Save** the file (`doc.Save`) with those options. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -To cały przepływ pracy, aby **how to save txt** pliki zawierające równania sformatowane w LaTeX. +### Usuń nadmiarowe białe znaki ---- +Tabele z wieloma kolumnami mogą generować długie wiersze. Po zapisaniu możesz chcieć przetworzyć plik, aby zamienić wielokrotne spacje na pojedynczy tabulator: -## Bonus: Automatyzacja konwersji wielu plików +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -Jeśli masz folder pełen dokumentów Word, otocz powyższą logikę prostą pętlą: +### Obsługa zagnieżdżonych tabel -```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +Jeśli Twój DOCX zawiera tabele wewnątrz tabel, `PreserveTableLayout` nadal zachowa wizualną hierarchię, ale wcięcia mogą wyglądać dziwnie. Szybkim rozwiązaniem jest zamiana początkowych spacji na własny znacznik (np. `>>`), aby parsery dalszego przetwarzania mogły wykrywać poziomy zagnieżdżenia. -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Przetwarzanie wsadowe wielu plików + +Gdy potrzebujesz **convert word to txt** dla dziesiątek dokumentów, otocz logikę pętlą: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Teraz możesz **convert word to latex** masowo — idealne dla grup badawczych, które codziennie otrzymują dziesiątki rękopisów. +W ten sposób możesz **save docx as txt** masowo, bez ręcznej interwencji. --- -## Zakończenie +## Częste pułapki i jak ich unikać + +1. **Brak trybu eksportu LaTeX** – Jeśli zapomnisz ustawić `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, równania powrócą do zwykłego tekstu (np. „Equation 1”). Zawsze podwójnie sprawdzaj blok opcji. +2. **Układ tabeli zostaje utracony** – Domyślnie `PreserveTableLayout` jest ustawione na `false`. Jeśli wynik wygląda jak blok tekstu, prawdopodobnie nie włączyłeś flagi. +3. **Ścieżki plików z odstępami** – Użycie surowych łańcuchów (`@"C:\My Folder\input.docx"`) unika problemów z escapowaniem. W przeciwnym razie otrzymasz `FileNotFoundException`. +4. **Niezgodność wersji** – Starsze wersje Aspose.Words (< 21.9) nie obsługują `OfficeMathExportMode`. Zaktualizuj do najnowszego pakietu, aby **how to export latex** działało. +5. **Błędy kodowania dla znaków nie‑ASCII** – Jeśli widzisz symbole �, jawnie ustaw `options.Encoding` na UTF‑8 lub odpowiednią stronę kodową. + +## Rozszerzanie rozwiązania: od TXT do Markdown lub HTML + +Czasami potrzebujesz więcej niż zwykły tekst — może plik Markdown, który nadal zawiera bloki LaTeX. Ten sam `TxtSaveOptions` można zamienić na `HtmlSaveOptions` lub `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Ta mała zmiana pozwala na wyjście w stylu **convert word to txt**, zachowując jednocześnie składnię markdown, którą kochasz. + +--- + +## Podsumowanie + +Przeszliśmy przez kompletną, gotową do produkcji odpowiedź na **how to export latex** z dokumentu Word, jednocześnie pokazując, jak **convert word to txt**, **convert word to plain text**, **save docx as txt** oraz **how to preserve tables**. Najważniejsze wnioski to: -Omówiliśmy **how to export LaTeX from Word** krok po kroku, zademonstrowaliśmy **how to save txt** pliki zachowujące każde równanie Office Math oraz pokazaliśmy, jak **convert word equations latex** bez utraty dokładności. +- Wczytaj DOCX przy użyciu `Aspose.Words.Document`. +- Ustaw `TxtSaveOptions.OfficeMathExportMode = LaTeX` oraz `PreserveTableLayout = true`. +- Wywołaj `doc.Save(outputPath, options)`, aby uzyskać czysty plik tekstowy z bogatym LaTeX. -Dzięki kilku linijkom C# i potężnej bibliotece Aspose.Words możesz przekształcić dowolny .docx w tekst gotowy do LaTeX, gotowy do włączenia w prace naukowe, podręczniki lub zautomatyzowane potoki publikacji. +Wypróbuj to na własnych plikach, eksperymentuj z ustawieniami kodowania i śmiało przetwarzaj wsadowo całe foldery. Jeśli napotkasz przypadki brzegowe — zagnieżdżone tabele, egzotyczne znaki lub starsze wersje Aspose — odwołaj się do sekcji „Wskazówki” i „Częste pułapki” po szybkie rozwiązania. -**Kolejne kroki?** Spróbuj podać wygenerowany `.txt` (lub przemianować go na `.tex`) do `pdflatex` lub `xelatex`, aby uzyskać PDF, lub zbadaj opcję `SaveFormat.LaTeX` dla bezpośredniego pliku `.tex`. Jeśli potrzebujesz **save docx as txt** zachowując formatowanie, eksperymentuj z `PreserveTableLayout` i własnym obsługiwaniem podziałów linii. +Gotowy na kolejny krok? Spróbuj przekonwertować ten sam DOCX do Markdown lub podać wygenerowany `.txt` do generatora statycznych stron, który renderuje LaTeX w sieci. Możliwości są nieograniczone, a teraz masz solidną podstawę dla każdego przepływu pracy **convert word to txt**. -Masz pytania dotyczące przypadków brzegowych, licencjonowania lub optymalizacji wydajności? zostaw komentarz poniżej — miłego kodowania! +Szczęśliwego kodowania i niech Twój LaTeX zawsze kompiluje się za pierwszym razem! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/polish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/polish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..98a5bd8ac4 --- /dev/null +++ b/words/polish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Zapisz dokument Word jako PDF przy użyciu Aspose.Words w C#. Dowiedz + się, jak konwertować pliki docx na PDF, wykrywać brakujące czcionki i skutecznie + obsługiwać ostrzeżenia o podstawianiu czcionek. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: pl +og_description: Zapisz dokument Word jako PDF przy użyciu Aspose.Words. Ten krok po + kroku poradnik pokazuje, jak przekonwertować docx na PDF i wykryć brakujące czcionki. +og_title: Zapisz dokument Word jako PDF przy użyciu Aspose.Words – Kompletny przewodnik +tags: +- Aspose.Words +- C# +- PDF conversion +title: Zapisz dokument Word jako PDF przy użyciu Aspose.Words – Kompletny przewodnik +url: /pl/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zapisz Word jako PDF przy użyciu Aspose.Words – Kompletny przewodnik + +Czy kiedykolwiek musiałeś **zapisz Word jako PDF** „w locie” i zastanawiałeś się, czy nie zabraknie jakiejś czcionki? Nie jesteś sam — programiści ciągle zmagają się z problemami brakujących czcionek przy konwersji dokumentów. W tym przewodniku pokażemy praktyczne rozwiązanie, które nie tylko **konwertuje docx na pdf**, ale także **wykrywa brakujące czcionki** dzięki ostrzeżeniom o podstawianiu czcionek w Aspose.Words. + +Omówimy wszystko, od konfiguracji zbieracza ostrzeżeń po interpretację wyników, tak aby na końcu dokładnie wiedzieć, jak **zapisz Word jako PDF** bez niespodzianek. Bez zewnętrznych narzędzi, bez ukrytych ustawień — po prostu czysty kod C#, który możesz wkleić do dowolnego projektu .NET. + +## Co będzie potrzebne + +- **Aspose.Words for .NET** (najnowsza wersja, np. 24.10) – możesz pobrać go przez NuGet (`Install-Package Aspose.Words`). +- Środowisko programistyczne .NET (Visual Studio, Rider lub VS Code). +- Przykładowy plik DOCX, który może zawierać czcionki niezainstalowane na docelowej maszynie. +To wszystko. Jeśli masz te podstawy, możemy zaczynać. + +## Zapisz Word jako PDF – przegląd krok po kroku + +Poniżej pełny, gotowy do uruchomienia program. Skopiuj go do projektu aplikacji konsolowej i naciśnij **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Wskazówka:** Zamień `YOUR_DIRECTORY` na ścieżkę bezwzględną lub użyj `Path.Combine(Environment.CurrentDirectory, "input.docx")` dla względnej, bezpieczniejszej ścieżki. + +### Dlaczego używamy callbacku ostrzeżeń + +Aspose.Words cicho podmienia brakujące czcionki na domyślną (zwykle Arial). Bez callbacku nigdy nie dowiesz się, że podmiana nastąpiła, co może prowadzić do problemów z układem w wygenerowanym PDF. Podpinając `IWarningCallback`, otrzymujemy przejrzystą, programistyczną listę każdego zdarzenia brakującej czcionki — idealną do logowania lub powiadamiania użytkowników końcowych. + +### Wykrywanie brakujących czcionek – na co zwrócić uwagę + +Po uruchomieniu programu, każda brakująca czcionka wygeneruje w konsoli wiersz podobny do: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Jeśli lista jest pusta, gratulacje — **zapisz Word jako PDF** zakończył się sukcesem ze wszystkimi oryginalnymi czcionkami. + +## Konwertuj Docx na PDF – dostosowywanie wyniku + +Czasami potrzebna jest konkretna wersja PDF, jakość obrazów lub poziom zgodności. Aspose.Words pozwala dostosować obiekt `PdfSaveOptions` przed wywołaniem `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Dlaczego to ważne:** Jeśli generujesz PDF‑y do archiwów prawnych, ustawienie `PdfA1b` zapewnia, że plik spełnia rygorystyczne standardy. Ta sama konwersja nadal respektuje nasz callback ostrzeżeń, więc nadal **wykryjesz brakujące czcionki**. + +## Aspose Words Font Substitution – obsługa przypadków brzegowych + +### Scenariusz 1: Wiele brakujących czcionek + +Jeśli dokument źródłowy używa kilku własnych czcionek, zbieracz ostrzeżeń będzie zawierał po jeden wpis dla każdej czcionki. Możesz je zagregować: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenariusz 2: Podanie katalogu z czcionkami zapasowymi + +Aspose.Words może przeszukiwać dodatkowe foldery w poszukiwaniu czcionek. Ustaw właściwość `FontsFolder` w `FontSettings` przed załadowaniem dokumentu: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Teraz biblioteka najpierw sprawdzi Twój własny folder, zmniejszając ryzyko niechcianej podmiany. + +### Scenariusz 3: Ignorowanie podmian + +Jeśli wolisz, aby konwersja zakończyła się błędem, gdy brakuje czcionki (zamiast cichej podmiany), rzuć wyjątek wewnątrz callbacku: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Wymusza to rozwiązanie problemu brakującej czcionki przed kontynuacją — przydatne w pipeline’ach CI, gdzie ciche błędy są nieakceptowalne. + +## Pełny przykład od początku do końca + +Łącząc wszystko razem, oto zwarta wersja, która demonstruje **jak konwertować Word na PDF**, ustawia własne opcje PDF i loguje problemy z czcionkami: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Oczekiwany output w konsoli** (gdy brak czcionki Calibri): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Jeśli nie pojawią się ostrzeżenia, operacja **zapisz Word jako PDF** użyła dokładnie tych samych czcionek, co źródłowy DOCX. + +## Podsumowanie wizualne + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Tekst alternatywny obrazu:* **save word as pdf** workflow pokazujący ładowanie, zbieranie ostrzeżeń i wyjście PDF. + +## Często zadawane pytania + +| Pytanie | Odpowiedź | +|----------|-----------| +| **Czy potrzebna jest licencja na Aspose.Words?** | Bezpłatna licencja ewaluacyjna działa do testów, ale w produkcji wymagana jest płatna licencja, aby usunąć znak wodny ewaluacji. | +| **Czy to działa na .NET Core / .NET 6+?** | Oczywiście — Aspose.Words jest skierowany do .NET Standard 2.0, więc każdy nowoczesny runtime .NET jest kompatybilny. | +| **Czy mogę konwertować wiele plików DOCX w pętli?** | Tak, wystarczy utworzyć nowy `Document` dla każdego pliku i ewentualnie ponownie używać tego samego `WarningInfoCollector`, jeśli chcesz uzyskać zagregowane wyniki. | +| **Co się stanie, jeśli folder docelowy nie istnieje?** | `Document.Save` rzuci `DirectoryNotFoundException`. Utwórz folder wcześniej lub użyj `Directory.CreateDirectory`. | +| **Czy istnieje sposób, aby osadzić brakujące czcionki w PDF?** | Aspose.Words może automatycznie osadzać czcionki, jeśli są dostępne na maszynie; ustaw `PdfSaveOptions.EmbedFullFonts = true`. | + +## Zakończenie + +Masz teraz solidny, gotowy do produkcji wzorzec, aby **zapisz Word jako PDF** jednocześnie **wykrywając brakujące czcionki** i obsługując scenariusze **Aspose.Words font substitution**. Dzięki podpięciu callbacku ostrzeżeń, dostosowaniu folderów czcionek i opcjonalnemu dopasowaniu `PdfSaveOptions`, możesz niezawodnie **konwertować docx na pdf** i informować użytkowników o ewentualnych problemach z czcionkami, które mogą wpływać na dokładność układu. + +Gotowy na kolejny krok? Spróbuj generować PDF‑y z wielu dokumentów równolegle lub zbadaj dodawanie znaków wodnych i podpisów cyfrowych — oba są prostymi rozszerzeniami kodu, który właśnie opanowałeś. Szczęśliwego kodowania i niech Twoje PDF‑y zawsze wyglądają dokładnie tak, jak powinny! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-loadoptions/_index.md b/words/polish/net/programming-with-loadoptions/_index.md index 22e043c8eb..e2323e4d4a 100644 --- a/words/polish/net/programming-with-loadoptions/_index.md +++ b/words/polish/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ W tych samouczkach nauczysz się, jak używać LoadOptions do ładowania dokumen | [Jak odzyskać docx – ustaw tryb odzyskiwania i otwórz uszkodzone pliki Word](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Dowiedz się, jak odzyskać pliki docx, ustawić tryb odzyskiwania i otworzyć uszkodzone dokumenty Word przy użyciu Aspose.Words. | | [Jak używać LoadOptions w Aspose.Words – kompletny przewodnik](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Kompletny przewodnik po LoadOptions w Aspose.Words dla .NET, zawierający przykłady i wskazówki optymalnego ładowania dokumentów. | | [Odzyskaj uszkodzony dokument w C# – ustaw tryb odzyskiwania i wyświetl monit użytkownika](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Dowiedz się, jak w C# ustawić tryb odzyskiwania dokumentu i wyświetlić użytkownikowi komunikat, aby naprawić uszkodzony plik Word. | +| [Odzyskaj uszkodzony docx – Kompletny przewodnik ładowania uszkodzonych plików Word w C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Dowiedz się, jak w C# ładować uszkodzone pliki Word, odzyskiwać ich zawartość i obsługiwać błędy. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/polish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..de9d55829b --- /dev/null +++ b/words/polish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Szybko odzyskaj uszkodzone pliki docx za pomocą Aspose.Words. Dowiedz + się, jak ustawić tryb odzyskiwania, bezpiecznie wczytać docx i odczytać uszkodzone + pliki Word w kilku prostych krokach. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: pl +og_description: Odzyskaj uszkodzone pliki docx w C#. Ustaw tryb odzyskiwania, bezpiecznie + wczytaj docx i odczytaj uszkodzone pliki Word przy użyciu Aspose.Words. +og_title: Odzyskaj uszkodzony plik docx – szybki przewodnik C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Odzyskiwanie uszkodzonego pliku docx – Pełny przewodnik po ładowaniu uszkodzonych + plików Word w C# +url: /pl/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Odzyskaj uszkodzony docx – Szybki przewodnik C# + +Czy kiedykolwiek próbowałeś otworzyć plik Word, który po prostu nie chciał się załadować i zastanawiałeś się, czy zawartość została utracona na zawsze? W wielu rzeczywistych projektach będziesz **odzyskiwać uszkodzony docx** bez proszenia użytkownika o ponowne przesłanie załącznika. Dobrą wiadomością jest to, że Aspose.Words robi to łatwo: po prostu ustaw tryb odzyskiwania i pozwól bibliotece wykonać ciężką pracę. + +W tym samouczku przeprowadzimy Cię przez dokładne kroki **odzyskiwania uszkodzonych docx**, wyjaśnimy, dlaczego opcja `RecoveryMode.AutoRecover` jest najbezpieczniejszym wyborem, i pokażemy, jak **załadować docx** pliki, które mogą być częściowo uszkodzone. Po zakończeniu będziesz w stanie odczytać uszkodzony plik Word, wyodrębnić wszelki tekst, który przetrwał, oraz nawet zalogować oryginalny format do przyszłych audytów. Bez zewnętrznych narzędzi, tylko czysty kod C#. + +## Czego będziesz potrzebować + +- **Aspose.Words for .NET** (dowolna aktualna wersja; używane API działa z wersją 23.5 i nowszą). +- Środowisko programistyczne .NET (Visual Studio, VS Code lub Rider). +- Uszkodzony lub częściowo uszkodzony plik `.docx`, który chcesz uratować. + +Brak specjalnych uprawnień, brak interfejsu COM i nie ma potrzeby instalowania Microsoft Office na serwerze. Proste, prawda? + +## Krok 1: Ustaw tryb odzyskiwania na Auto‑Recover + +Gdy plik Word jest uszkodzony, domyślne zachowanie podczas ładowania rzuca wyjątek i przerywa operację. Konfigurując obiekt `LoadOptions`, informujesz Aspose.Words, aby **ustawił tryb odzyskiwania** na `AutoRecover`, który skanuje pakiet zip, pomija nieczytelne części i zwraca to, co uda się złożyć. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Dlaczego AutoRecover?** +> Próbuje odczytać jak najwięcej, jednocześnie utrzymując obiekt dokumentu w użyciu. Jeśli wybierzesz `RecoveryMode.NoRecovery`, ładowanie zakończy się niepowodzeniem przy pierwszej korupcji, co podważa sens scenariuszy **odzyskiwania uszkodzonych docx**. + +## Krok 2: Załaduj dokument z skonfigurowanymi opcjami + +Teraz, gdy tryb odzyskiwania jest ustawiony, możesz bezpiecznie spróbować otworzyć plik. Zastąp `"YOUR_DIRECTORY/input.docx"` rzeczywistą ścieżką do uszkodzonego pliku. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Jeśli plik jest jedynie częściowo uszkodzony, instancja `Document` nadal zostanie utworzona. Możesz później sprawdzić `document.IsStructureValid`, jeśli potrzebujesz dodatkowej walidacji. + +## Krok 3: Zweryfikuj wykryty format + +Aspose.Words automatycznie wykrywa oryginalny format (DOC, DOCX, ODT itp.). Wyświetlenie tej wartości pomaga potwierdzić, że biblioteka poprawnie rozpoznała plik, co jest szybkim sprawdzeniem po operacji **odzyskiwania uszkodzonych docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typowy wynik: + +``` +Loaded with Docx format. +``` + +Nawet jeśli niektóre części brakowały, wykrywanie formatu nadal się powodzi — kolejny sukces dla przepływów **odzyskiwania uszkodzonych docx**. + +## Krok 4: Wyodrębnij, co możesz + +Po załadowaniu dokumentu możesz traktować go jak każdy zdrowy plik Word. Poniżej znajduje się zwięzły przykład, który wyodrębnia zwykły tekst i wypisuje go w konsoli. To pokazuje, że możesz **odczytać uszkodzony plik Word** bez awarii. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Jeśli oryginalny plik zawierał tabele lub obrazy, które były uszkodzone, zostaną po prostu pominięte w wyjściu tekstowym. Reszta dokumentu pozostaje nienaruszona. + +## Krok 5: Zapisz czystą kopię (opcjonalnie) + +Często będziesz chciał przekazać użytkownikowi nową, czystą wersję pliku po odzyskaniu. Zapisanie w tym samym formacie zapewnia kompatybilność z dalszymi procesami. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Teraz masz **odzyskany uszkodzony docx** plik, który możesz bezpiecznie dołączyć do e‑maila lub przekazać innemu serwisowi. + +## Pełny działający przykład + +Łącząc wszystko razem, oto kompletny, gotowy do uruchomienia program. Wklej go do nowego projektu konsolowego, dostosuj ścieżki plików i naciśnij F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Oczekiwany wynik** (zakładając, że plik zawiera pojedynczy akapit „Hello world!” oraz pewien uszkodzony XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Zauważ, że program nigdy nie ulega awarii — mimo że źródłowy plik był częściowo uszkodzony. To istota **odzyskiwania uszkodzonych docx** przy użyciu Aspose.Words. + +## Częste pytania i przypadki brzegowe + +### Co jeśli plik jest całkowicie nieczytelny? + +Nawet `AutoRecover` ma swoje granice. Jeśli sam kontener zip jest uszkodzony ponad naprawę, Aspose.Words rzuci `CorruptedFileException`. W takim przypadku możesz potrzebować zewnętrznego narzędzia do naprawy zip przed ponowną próbą **odzyskiwania uszkodzonych docx**. + +### Czy mogę odzyskać inne formaty (np. `.doc`, `.odt`)? + +Zdecydowanie tak. Ten sam `LoadOptions` działa dla każdego formatu obsługiwanego przez Aspose.Words. Wystarczy zmienić rozszerzenie pliku, a biblioteka automatycznie wykryje oryginalny format. Oznacza to, że możesz również **odzyskać uszkodzone docx**‑podobne pliki, takie jak `.doc` czy `.rtf`, używając tego samego kodu. + +### Jak obsłużyć duże dokumenty bez ładowania wszystkiego do pamięci? + +Dla plików o rozmiarze gigabajtów możesz włączyć **opcje ładowania** takie jak `LoadOptions.LoadFormat` lub strumieniować dokument strona po stronie. Jednak algorytm odzyskiwania nadal musi odczytać cały pakiet, więc spodziewaj się większego zużycia pamięci przy bardzo dużych uszkodzonych plikach. + +### Czy istnieje sposób, aby dowiedzieć się, które części zostały utracone? + +Po załadowaniu możesz sprawdzić `document.GetChildNodes(NodeType.Any, true)` i porównać liczbę z oczekiwanym baseline. Brakujące tabele, obrazy lub nagłówki po prostu nie będą obecne w kolekcji węzłów. To pozwala zalogować dokładnie, co zostało **odzyskane w uszkodzonym docx** i poinformować użytkownika. + +## Porady profesjonalne dla niezawodnego odzyskiwania + +- **Sprawdź rozmiar pliku wejściowego** przed ładowaniem; plik o zerowym rozmiarze zawsze zakończy się niepowodzeniem. +- **Zaloguj wynik `RecoveryMode`** przechwytując `DocumentLoadingException` i zapisując komunikat wyjątku; często zawiera wskazówki, które części zostały pominięte. +- **Uruchom odzyskiwanie w tle** (na wątku) jeśli przetwarzasz przesyłane pliki w usłudze webowej — to utrzymuje responsywność żądania. +- **Połącz z sumą kontrolną** (np. MD5), aby wykryć, czy odzyskany plik różni się od oryginału; możesz wtedy zdecydować, czy zachować obie wersje. + +## Zakończenie + +Właśnie pokazaliśmy, jak **odzyskać uszkodzone docx** w C# poprzez **ustawienie trybu odzyskiwania** na `AutoRecover`, bezpieczne załadowanie dokumentu, wyodrębnienie przetrwanego tekstu oraz opcjonalne zapisanie czystej kopii. To podejście pozwala **załadować docx** pliki, które w przeciwnym razie wywołałyby wyjątki, i daje niezawodny sposób na **odczytanie uszkodzonego pliku Word** bez zewnętrznych narzędzi. + +Kolejne kroki? Spróbuj zamienić `RecoveryMode.AutoRecover` na `RecoveryMode.NoRecovery`, aby zobaczyć różnicę, lub poeksperymentuj z właściwościami `LoadOptions`, które kontrolują obsługę haseł i zamianę czcionek. Możesz także zintegrować procedurę odzyskiwania z API ASP.NET Core, które przyjmuje przesyłane pliki i zwraca naprawiony plik — idealne dla korporacyjnych pipeline'ów zarządzania dokumentami. + +Masz więcej pytań dotyczących odzyskiwania dokumentów Word, lub chcesz zobaczyć, jak **odzyskać uszkodzone docx** przy użyciu własnych callbacków? Dodaj komentarz poniżej i szczęśliwego kodowania! + +![Ilustracja odzyskanego dokumentu – odzyskaj uszkodzony docx](https://example.com/images/recover-corrupted-docx.png "odzyskaj uszkodzony docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-markdownsaveoptions/_index.md b/words/polish/net/programming-with-markdownsaveoptions/_index.md index e303dbabf2..7ee4c7e31b 100644 --- a/words/polish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/polish/net/programming-with-markdownsaveoptions/_index.md @@ -35,11 +35,15 @@ Kompletny przewodnik C# tworzenia dostępnych plików PDF i konwersji dokumentó ### [Zapisz docx jako markdown – Kompletny przewodnik C# z równaniami LaTeX](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) Kompletny przewodnik C# konwertujący pliki DOCX na Markdown z obsługą równań LaTeX przy użyciu Aspose.Words. +### [Zapisz docx jako markdown – Eksportuj równania Word do LaTeX przy użyciu Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) +Dowiedz się, jak wyeksportować równania matematyczne z dokumentu Word do formatu LaTeX podczas konwersji do Markdown przy użyciu Aspose.Words. + ### [Zapisz docx jako markdown – Pełny przewodnik C# z wyodrębnianiem obrazów](./save-docx-as-markdown-full-c-guide-with-image-extraction/) Kompletny przewodnik C# pokazujący, jak konwertować pliki DOCX do Markdown i wyodrębniać obrazy przy użyciu Aspose.Words. ### [Zapisz docx jako markdown – Pełny przewodnik C# z Aspose.Words](./save-docx-as-markdown-with-aspose-words-full-c-guide/) Kompletny przewodnik C# pokazujący, jak zapisać plik DOCX jako Markdown przy użyciu Aspose.Words. + ### [Konwertuj Word do Markdown w C# – Pełny przewodnik z wyodrębnianiem obrazów](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) Kompletny przewodnik C# konwertujący dokumenty Word do formatu Markdown z wyodrębnianiem obrazów. @@ -67,6 +71,9 @@ Dowiedz się, jak automatycznie zmieniać nazwy obrazów przy konwersji dokument ### [Zapisz obrazy Word – konwertuj Word do Markdown przy użyciu Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) Dowiedz się, jak wyodrębnić obrazy z dokumentu Word i zapisać je podczas konwersji do formatu Markdown przy użyciu Aspose.Words. +### [Prześlij obrazy do chmury podczas konwertowania Worda na Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) +Dowiedz się, jak automatycznie przesyłać obrazy do chmury podczas konwersji dokumentów Word do formatu Markdown przy użyciu Aspose.Words. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/polish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..e401fff7da --- /dev/null +++ b/words/polish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Zapisz docx jako markdown przy użyciu Aspose.Words – naucz się konwertować + Word na markdown, eksportować równania do LaTeX i ustawiać rozdzielczość obrazów + w markdown w jednym płynnym przepływie pracy. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: pl +og_description: Zapisz plik docx jako markdown przy użyciu Aspose.Words. Ten samouczek + pokazuje, jak przekonwertować Word na markdown, wyeksportować równania do LaTeX + i ustawić rozdzielczość obrazów w markdown. +og_title: zapisz docx jako markdown – Kompletny przewodnik eksportu matematyki Word + do LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Zapisz docx jako markdown – eksportuj równania Word do LaTeX przy użyciu Aspose.Words +url: /pl/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zapisz docx jako markdown – eksportuj równania Word do LaTeX przy użyciu Aspose.Words + +Czy kiedykolwiek potrzebowałeś **zapisz docx jako markdown**, ale utknąłeś, jak zachować równania Office Math w ostrej formie? Nie jesteś jedyny. Większość programistów napotyka problem, gdy domyślna konwersja zamienia równania w rozmyte obrazy, zmuszając do ręcznego przepisania ich w LaTeX. + +Dobre wiadomości: Aspose.Words może wykonać ciężką pracę za Ciebie. W tym samouczku **przekształcimy word na markdown**, poinstruujemy silnik, aby **eksportował równania do latex**, oraz **ustawimy rozdzielczość obrazów w markdown** dla reszty dokumentu. Po zakończeniu będziesz mieć jedno polecenie, które wygeneruje czysty plik `.md` z równaniami gotowymi do LaTeX i obrazami wysokiej rozdzielczości. + +## Czego się nauczysz + +- Jak załadować plik `.docx` zawierający obiekty Office Math. +- Które właściwości `MarkdownSaveOptions` kontrolują **eksportowanie równań do latex** oraz **ustawianie rozdzielczości obrazów w markdown**. +- Pełny, gotowy do uruchomienia fragment C#, który możesz wkleić do dowolnego projektu .NET. +- Wskazówki dotyczące rozwiązywania typowych problemów, takich jak brakujące czcionki czy nieobsługiwane funkcje równań. + +**Wymagania wstępne**: .NET 6+ (lub .NET Framework 4.6+), licencja na Aspose.Words for .NET oraz podstawowa znajomość C#. Jeśli potrafisz stworzyć aplikację konsolową, jesteś gotowy do działania. + +--- + +## Krok 1 – Zapisz docx jako markdown: Załaduj swój plik Word + +Pierwszą rzeczą, której potrzebujemy, jest obiekt `Document` wskazujący na źródłowy plik `.docx`. Pomyśl o tym jak o otwarciu książki przed rozpoczęciem kopiowania rozdziałów. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Dlaczego to ważne*: Jeśli dokument nie zawiera żadnych równań, krok **eksportowania równań do latex** nie wykona żadnej operacji, ale reszta konwersji nadal zostanie przeprowadzona. To sprawdzenie chroni Cię przed zastanawianiem się, dlaczego w wygenerowanym Markdown brakuje bloków LaTeX. + +--- + +## Krok 2 – Skonfiguruj eksport równań do LaTeX + +Aspose.Words pozwala zdecydować, jak mają być renderowane równania Office Math. Domyślnie zamienia je w obrazy PNG, co powoduje, że wiele samouczków kończy się ziarnistym plikiem markdown. Przełączenie `OfficeMathExportMode` na `LaTeX` zapewnia czyste równania gotowe do kopiowania i wklejania. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Dlaczego `OfficeMathExportMode.LaTeX`?* LaTeX jest lingua franca publikacji naukowych. Kiedy później renderujesz markdown przy użyciu generatora stron statycznych lub notatnika Jupyter, równania będą wyświetlane wyraźnie przy dowolnym poziomie powiększenia. + +--- + +## Krok 3 – Ustaw rozdzielczość obrazów w markdown (dla treści nie‑matematycznych) + +Mimo że koncentrujemy się na matematyce, większość dokumentów Word zawiera także obrazy, wykresy lub osadzone SVG. Właściwość `ImageResolution` kontroluje, jak Aspose.Words rasteryzuje te zasoby. Wartość **300 DPI** jest optymalna zarówno dla ekranu, jak i druku. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Wskazówka*: Jeśli Twój markdown będzie wyświetlany wyłącznie w sieci, możesz obniżyć tę wartość do 150 DPI, aby zmniejszyć rozmiar pliku. Natomiast dla PDF‑ów gotowych do druku, podnieś ją do 600 DPI. + +--- + +## Krok 4 – Uruchom konwersję – Konwertuj równania Word do LaTeX + +Gdy wszystko jest już skonfigurowane, właściwa konwersja odbywa się jedną linią. Aspose.Words wykonuje ciężką pracę w tle. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Oczekiwany wynik**: Otwórz wygenerowany plik `.md` i powinieneś zobaczyć coś podobnego do: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Zauważ bloki LaTeX (`$...$` i `$$...$$`) zastępujące poprzednie fragmenty PNG. Obraz na dole nadal jest PNG, renderowany w 300 DPI, tak jak prosiliśmy. + +--- + +## Krok 5 – Typowe przypadki brzegowe i jak je obsłużyć + +| Sytuacja | Co się dzieje | Jak naprawić | +|-----------|--------------|------------| +| **Brakujące czcionki** (np. Cambria Math nie zainstalowana) | Wynik LaTeX może zawierać nieznane symbole. | Zainstaluj brakującą czcionkę na serwerze lub osadź ją w dokumencie przed konwersją. | +| **Złożone równania** (macierz z niestandardowymi delimitatorami) | Aspose.Words może przejść do obrazu pomimo trybu `LaTeX`. | Uaktualnij do najnowszej wersji Aspose.Words; biblioteka stale poprawia obsługę równań. | +| **Duże dokumenty** ( > 50 MB ) | Nacisk na pamięć może spowodować `OutOfMemoryException`. | Użyj `LoadOptions` z `LoadFormat.Docx` i strumieniuj plik, lub podziel dokument na sekcje przed konwersją. | +| **Zbyt duży rozmiar obrazu** | Plik markdown staje się ogromny, spowalniając budowanie statycznych stron. | Obniż `ImageResolution` do 150 DPI dla scenariuszy tylko webowych (zobacz Krok 3). | + +--- + +## Krok 6 – Połącz wszystko razem: Pełny działający przykład + +Poniżej znajduje się *kompletny* program aplikacji konsolowej, który możesz skopiować i wkleić do `Program.cs`. Zawiera wszystkie elementy, o których rozmawialiśmy, oraz dodatkowe obsługi błędów. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Uruchom program (`dotnet run`), a otrzymasz plik markdown, który **zapisuje docx jako markdown** zachowując każde równanie w formacie LaTeX. Bez ręcznego kopiowania, bez brzydkich obrazów rastrowych dla równań. + +--- + +## Zakończenie + +Przeszliśmy cały proces **zapisywania docx jako markdown** przy użyciu Aspose.Words, od załadowania pliku Word po skonfigurowanie **eksportu równań do latex** oraz **ustawienia rozdzielczości obrazów w markdown**. Ostateczny fragment jest gotowy do produkcji i możesz go wkleić do dowolnego projektu .NET, który potrzebuje **konwertować word na markdown** w locie. + +Co dalej? Spróbuj wprowadzić wygenerowany plik `.md` do generatora stron statycznych, takiego jak Hugo lub Jekyll, i zobacz, jak Twoje równania renderują się pięknie. Jeśli potrzebujesz **konwertować równania Word do latex** w inne formaty (PDF, HTML), po prostu zamień `MarkdownSaveOptions` na `PdfSaveOptions` lub `HtmlSaveOptions` — ten sam znacznik `OfficeMathExportMode` działa we wszystkich przypadkach. + +Masz niestandardowy przepływ pracy, np. pobieranie plików Word z Azure Blob storage lub strumieniowanie ich z API? Ten sam wzorzec ma zastosowanie; po prostu zamień konstruktor `Document` oparty na systemie plików na wersję opartą na strumieniu. + +Śmiało eksperymentuj i daj nam znać w komentarzach, jak to podejście rozwiązało Twoje problemy z konwersją. Szczęśliwego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/polish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..a4b197a6d4 --- /dev/null +++ b/words/polish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-05-01 +description: Przesyłaj obrazy do chmury, konwertując dokument Word na markdown. Dowiedz + się, jak wyodrębnić obrazy z pliku docx i przechowywać je w Azure Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: pl +og_description: Prześlij obrazy do chmury podczas konwertowania dokumentu Word na + markdown. Ten przewodnik pokazuje, jak wyodrębnić obrazy z pliku docx i przechowywać + je w Azure Blob Storage. +og_title: Wysyłaj obrazy do chmury przy konwertowaniu Worda na Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Przesyłaj obrazy do chmury przy konwersji Worda na Markdown +url: /pl/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Przesyłanie obrazów do chmury podczas konwersji Worda na Markdown + +Kiedykolwiek potrzebowałeś **przesłać obrazy do chmury** podczas konwertowania pliku Word na markdown? Nie jesteś jedyny — programiści nieustannie żonglują konwersją dokumentów i zarządzaniem zasobami, a wykonanie obu rzeczy w jednym płynnym procesie może przypominać gonienie za ruchomym celem. + +Dobre wieści? Dzięki Aspose.Words możesz wyodrębnić każdy obraz, wykres lub diagram z pliku .docx, od razu przesłać go do Azure Blob Storage i pozwolić, aby wygenerowany markdown odwoływał się do tych adresów w chmurze zamiast do lokalnych plików. W tym samouczku przeprowadzimy Cię przez cały proces, od wczytania dokumentu źródłowego po uzyskanie czystego pliku markdown, który wskazuje na Twój zasobnik w Azure. + +Pod koniec tego przewodnika będziesz w stanie **konwertować docx na markdown**, **wyodrębniać obrazy z docx** i **przechowywać obrazy w Azure Blob** — wszystko przy użyciu kilku linijek C#. Bez zewnętrznych narzędzi, bez ręcznego kopiowania i wklejania oraz z pewnością bez zepsutych linków do obrazów. + +## Czego będziesz potrzebować + +- **.NET 6.0** lub nowszy (kod działa również na .NET Core i .NET Framework) +- **Aspose.Words for .NET** (pakiet NuGet `Aspose.Words`) +- Konto **Azure Storage** z kontenerem (np. `images`) i współdzielonym kluczem dostępu – będziesz potrzebował ciągu połączenia do przesyłania plików. +- Podstawowa znajomość C# i async/await (opcjonalna, ale przydatna). + +Jeśli masz już te elementy, świetnie — przejdźmy od razu do rozwiązania. Jeśli nie, sekcja „Wymagania wstępne” na końcu wskaże szybkie kroki konfiguracji. + +## Krok 1: Skonfiguruj pomocnika Azure Blob (Dlaczego to ważne) + +Zanim dotkniemy się dokumentu Word, potrzebujemy małego pomocnika, który potrafi przesłać tablicę bajtów do Azure Blob Storage i zwrócić publiczny URL. Ta abstrakcja utrzymuje logikę konwersji w czystości i ułatwia późniejszą wymianę dostawcy pamięci. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Dlaczego ten pomocnik?** + +1. **Separation of concerns** – kod konwersji markdown pozostaje skoncentrowany na obsłudze dokumentu, a nie na szczegółach HTTP. +2. **Reusability** – możesz wywołać `UploadAsync` z dowolnego miejsca w aplikacji (np. dla zdjęć przesyłanych przez użytkowników). +3. **Future‑proofing** – zamiana na Amazon S3 lub Google Cloud Storage wymaga jedynie nowej implementacji tego samego interfejsu. + +> **Pro tip:** Ustaw poziom dostępu kontenera na `Blob` (publiczny) tylko jeśli zgadzasz się, aby każdy mógł odczytać obrazy. W prywatnych scenariuszach generuj tokeny SAS dla każdego przesłania i wstawiaj zamiast nich te URL-e. + +## Krok 2: Zdefiniuj callback zapisywania zasobów (Rdzeń przesyłania podczas konwersji) + +Aspose.Words pozwala przechwycić każdy zasób (obraz, wykres itp.), który normalnie zostałby zapisany na dysku przy zapisywaniu dokumentu jako markdown. Dostarczając `ResourceSavingCallback`, możemy przesłać każdy zasób do Azure Blob i zamienić lokalną nazwę pliku na adres w chmurze. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Co się tutaj dzieje?** + +- **Extract** – Aspose.Words dostarcza nam strumień dla każdego obrazu. +- **Upload** – Przekazujemy ten strumień do `AzureBlobUploader`. +- **Replace** – Generator markdown otrzymuje publiczny URL i zapisuje go w składni obrazu markdown (`![](https://…)`). + +Ponieważ ustawiamy `args.AlreadyExists = true`, żadne pliki tymczasowe nie zaśmiecają systemu plików — czysta, bezstanowa operacja idealna dla funkcji serverless. + +## Krok 3: Skonfiguruj opcje zapisu Markdown (Połącz wszystko razem) + +Teraz wprowadzamy callback do `MarkdownSaveOptions` Aspose.Words. Kluczowe flagi to `ExportImagesAsBase64 = false` (aby uzyskać linki zewnętrzne) oraz `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Dlaczego wyłączamy Base64?** +Gdy `ExportImagesAsBase64` jest ustawione na true, Aspose osadza każdy obraz bezpośrednio w markdown jako data URI. To podważa cel **przesyłania obrazów do chmury**, ponieważ plik markdown rośnie w rozmiarze, a obrazy pozostają ukryte przed CDN. Wyłączając tę opcję, otrzymujemy czyste, zewnętrzne linki wskazujące na Azure Blob — dokładnie to, czego oczekuje nowoczesny generator statycznych stron. + +## Krok 4: Połącz wszystko — Minimalna aplikacja konsolowa + +Poniżej znajduje się kompletny, gotowy do uruchomienia program konsolowy. Zastąp symbole zastępcze rzeczywistym ciągiem połączenia Azure oraz nazwą kontenera. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu z `sample.docx`, który zawiera dwa obrazy, spowoduje wygenerowanie: + +- `output.md` zawierającego składnię obrazu markdown, np.: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-pdfsaveoptions/_index.md b/words/polish/net/programming-with-pdfsaveoptions/_index.md index 349c800a21..0dd882b84c 100644 --- a/words/polish/net/programming-with-pdfsaveoptions/_index.md +++ b/words/polish/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ Niezależnie od tego, czy chcesz przekonwertować dokumenty Word do PDF w celu d | [Renderuj efekty 3D DML 3DEffects w dokumencie PDF](./dml-3deffects-rendering/) | Dowiedz się, jak renderować niesamowite efekty 3D DML w dokumentach PDF za pomocą Aspose.Words dla .NET dzięki temu kompleksowemu przewodnikowi krok po kroku. | | [Interpolacja obrazów w dokumencie PDF](./interpolate-images/) | Dowiedz się, jak interpolować obrazy w dokumencie PDF za pomocą Aspose.Words dla .NET dzięki naszemu przewodnikowi krok po kroku. Łatwo popraw jakość obrazu w swoim pliku PDF. | | [Zapisz docx jako pdf przy użyciu Aspose.Words – Kompletny przewodnik C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Dowiedz się, jak w pełni konwertować pliki DOCX do PDF w C# przy użyciu Aspose.Words, krok po kroku. | +| [Zapisz dokument jako PDF przy użyciu Aspose.Words – Kompletny przewodnik C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Dowiedz się, jak w pełni konwertować dokumenty do PDF w C# przy użyciu Aspose.Words, krok po kroku. | | [Utwórz dostępny PDF z Word przy użyciu C# – Przewodnik krok po kroku](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Dowiedz się, jak wygenerować dostępny plik PDF z dokumentu Word w C#, stosując techniki dostępności krok po kroku. | | [Utwórz dostępny PDF w C# – Samouczek dostępności PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Dowiedz się, jak generować dostępne pliki PDF w C# przy użyciu Aspose.Words, spełniające standardy WCAG. | | [Utwórz dostępny PDF z Worda – Kompletny przewodnik](./create-accessible-pdf-from-word-complete-guide/) | Dowiedz się, jak tworzyć dostępne pliki PDF z dokumentów Word, spełniając standardy dostępności. | diff --git a/words/polish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/polish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..1c035da0bb --- /dev/null +++ b/words/polish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,255 @@ +--- +category: general +date: 2026-05-01 +description: Dowiedz się, jak zapisać dokument jako PDF przy użyciu Aspose.Words w + C#. Poradnik obejmuje również konwersję Worda do PDF, eksport matematyki w formacie + LaTeX oraz obsługę brakujących czcionek. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: pl +og_description: Zapisz dokument jako PDF bez wysiłku dzięki Aspose.Words. Ten przewodnik + pokazuje także, jak konwertować Word na PDF, eksportować LaTeX matematyczny oraz + radzić sobie z brakującymi czcionkami. +og_title: Zapisz dokument jako PDF przy użyciu Aspose.Words – Kompletny przewodnik + C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Zapisz dokument jako PDF przy użyciu Aspose.Words – Kompletny przewodnik C# +url: /pl/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zapisz dokument jako PDF przy użyciu Aspose.Words – Kompletny przewodnik C# + +Zastanawiałeś się kiedyś **jak zapisać dokument jako pdf** bezpośrednio z pliku Word, nie tracąc funkcji dostępności? Nie jesteś jedyny — programiści stale pytają o niezawodny sposób konwersji Word do PDF przy zachowaniu równań matematycznych i eleganckim obsługiwaniu brakujących czcionek. + +W tym samouczku przeprowadzimy krok po kroku rozwiązanie, które nie tylko **zapisuje dokument jako pdf**, ale także demonstruje **konwertować word do pdf**, **eksport matematyki do latex**, oraz **obsługę brakujących czcionek** przy użyciu najnowszego Aspose.Words dla .NET. Po zakończeniu będziesz mieć gotowy do uruchomienia program w C#, który generuje pliki zgodne z PDF/UA‑2, idealne do audytów dostępności. + +## Czego będziesz potrzebować + +- .NET 6 lub nowszy (kod działa również z .NET Core i .NET Framework) +- Aspose.Words dla .NET 25.10 lub nowszy – możesz pobrać darmową wersję próbną ze strony Aspose +- Skromny dokument Word (`input.docx`) zawierający przynajmniej jedną pływającą figurę i równanie matematyczne (aby zobaczyć działanie funkcji export‑math‑latex) +- Visual Studio 2022 (lub dowolne IDE) + +> **Wskazówka:** Jeśli pracujesz w pipeline CI/CD, dodaj pakiet NuGet Aspose.Words do pliku projektu: + +```xml + +``` + +## Krok 1: Załaduj dokument źródłowy z automatycznym odzyskiwaniem + +Podczas pracy z rzeczywistymi plikami Word możesz napotkać uszkodzone sekcje lub brakujące zasoby. Włączenie automatycznego odzyskiwania zapewnia, że proces ładowania nie zgłosi wyjątku. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Dlaczego to ważne:** +`RecoveryMode.AutoRecover` chroni Twój pipeline przed awarią przy niepoprawnym wejściu, co jest szczególnie przydatne, gdy **konwertujesz word do pdf** masowo. + +## Krok 2: Skonfiguruj opcje zapisu PDF dla pełnej dostępności + +PDF/UA‑2 to standard ISO dla dostępnych PDF‑ów. Konfigurując kilka flag, uzyskujemy plik, który czytniki ekranu mogą nawigować, a także zapewniamy, że równania matematyczne są eksportowane jako ukryty LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – zapewnia, że wynikowy PDF zachowuje oryginalny układ, pozostając jednocześnie semantycznie poprawny. +- **OfficeMathExportMode.LaTeX** – spełnia wymóg **export math latex**, umożliwiając narzędziom downstream wyodrębnianie równań w razie potrzeby. + +## Krok 3: Przechwyć ostrzeżenia (np. brakujące czcionki) + +Brakujące czcionki to częsta bolączka przy konwersji dokumentów. Aspose.Words może zgłaszać te problemy za pomocą `WarningCallback`. Zbierzemy je, abyś mógł je później zalogować lub podjąć odpowiednie działania. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Dlaczego to ważne:** +Jeśli źródło używa czcionki, która nie jest zainstalowana na serwerze, PDF przełączy się na domyślną czcionkę, co może zepsuć układ. Dzięki **handle missing fonts** możemy ostrzec użytkownika lub osadzić zamiennik. + +## Krok 4: Zapisz dokument jako dostępny PDF + +Teraz moment prawdy — faktyczne wykonanie konwersji. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Jeśli wszystko pójdzie gładko, otrzymasz plik PDF/UA‑2 zawierający ukryty LaTeX dla każdego równania oraz odpowiednie tagowanie pływających figur. + +## Krok 5: Przejrzyj przechwycone ostrzeżenia (opcjonalnie, ale zalecane) + +Po operacji zapisu możesz przeiterować zebrane ostrzeżenia i je zalogować. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typowy wynik może wyglądać tak: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Wczesne zobaczenie tych komunikatów pomaga **handle missing fonts** zanim wpłyną na końcowych użytkowników. + +## Pełny działający przykład + +Łącząc wszystko razem, oto kompletny, gotowy do uruchomienia program. Zamień ścieżki zastępcze na własne. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` jest zgodny z PDF/UA‑2. +- Wszystkie pływające figury są oznaczone jako inline figures. +- Każdy obiekt Office Math pojawia się jako ukryty LaTeX (widoczny po zbadaniu struktury PDF). +- Wszelkie problemy związane z czcionkami są wypisywane w konsoli, dając Ci możliwość **handle missing fonts** przed udostępnieniem pliku. + +![Diagram przedstawiający przepływ od Word → Aspose.Words → Dostępny PDF (zapisz dokument jako pdf)](conversion-diagram.png "Diagram przepływu zapisywania dokumentu jako pdf") + +*Tekst alternatywny obrazu:* **Diagram pokazujący, jak zapisać dokument jako pdf przy użyciu Aspose.Words** + +## Częste pytania i przypadki brzegowe + +### Co jeśli używam starszej wersji Aspose.Words? + +Flaga `OfficeMathExportMode.LaTeX` została wprowadzona w wersji 25.10. W starszych wydaniach nadal możesz **convert word to pdf**, ale matematyka będzie rasteryzowana zamiast eksportowana jako LaTeX. Zaktualizuj, aby uzyskać najlepszą dostępność. + +### Czy mogę osadzić własne czcionki, aby uniknąć domyślnego zastąpienia? + +Tak. Ustaw `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` przed wywołaniem `Save`. To również pomaga **handle missing fonts**, wymuszając, aby PDF zawierał wymagane glify. + +### Jak zweryfikować zgodność z PDF/UA‑2? + +Otwórz plik w Adobe Acrobat Pro → “Print Production” → “Preflight”. Wybierz profil “PDF/A‑2b” lub “PDF/UA‑2”; Acrobat zgłosi wszelkie naruszenia. + +### Co z plikami Word chronionymi hasłem? + +Załaduj dokument przy użyciu `LoadOptions`, które zawiera `Password`. Przykład: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Reszta pipeline pozostaje niezmieniona. + +## Zakończenie + +Omówiliśmy wszystko, co potrzebne, aby **save document as pdf** przy użyciu Aspose.Words w C#. Samouczek również pokazał, jak **convert word to pdf**, **export math latex**, oraz **handle missing fonts** — wszystko przy tworzeniu dostępnego pliku PDF/UA‑2. + +Wypróbuj kod, eksperymentuj z różnymi `PdfSaveOptions` (np. kompresja obrazów, PDF/A‑2b) i zintegrować go z usługą przetwarzania dokumentów. Jeśli potrzebujesz iść dalej, rozważ eksplorację biblioteki PDF‑specyficznej Aspose do post‑przetwarzania lub podpisów cyfrowych. + +Masz więcej scenariuszy, które chciałbyś rozwiązać? Śmiało zostaw komentarz lub sprawdź nasze inne przewodniki o **PDF manipulation**, **image extraction** i **batch conversion**. Szczęśliwego kodowania! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-shapes/_index.md b/words/polish/net/programming-with-shapes/_index.md index fef35a59b3..af406e3eca 100644 --- a/words/polish/net/programming-with-shapes/_index.md +++ b/words/polish/net/programming-with-shapes/_index.md @@ -36,8 +36,8 @@ Korzystając z Aspose.Words dla .NET i postępując zgodnie z tymi samouczkami, | [Aktualizuj rysunek Smart Art](./update-smart-art-drawing/) | Dowiedz się, jak aktualizować rysunki Smart Art w dokumentach Word za pomocą Aspose.Words dla .NET dzięki temu przewodnikowi krok po kroku. Upewnij się, że Twoje wizualizacje są zawsze dokładne. | | [Utwórz prostokątny kształt w Wordzie za pomocą Aspose.Words – przewodnik krok po kroku](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Dowiedz się, jak utworzyć prostokątny kształt w dokumencie Word przy użyciu Aspose.Words, korzystając z naszego szczegółowego przewodnika krok po kroku. | | [Utwórz pusty dokument Word z cieniowanym prostokątnym kształtem – przewodnik krok po kroku](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Dowiedz się, jak utworzyć pusty dokument Word z cieniowanym prostokątnym kształtem przy użyciu Aspose.Words dla .NET, krok po kroku. | - | [Utwórz prostokątny kształt w Wordzie przy użyciu C# – przewodnik krok po kroku](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Dowiedz się, jak w C# utworzyć prostokątny kształt w dokumencie Word, korzystając z Aspose.Words dla .NET – kompletny przewodnik krok po kroku. | +| [Jak przenieść cień w Aspose.Words – kompletny przewodnik C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Dowiedz się, jak przenieść cień kształtu w dokumencie Word przy użyciu Aspose.Words dla .NET i C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/polish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..271b447de8 --- /dev/null +++ b/words/polish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Jak przesunąć cień na kształcie w Aspose.Words przy użyciu C#. Dowiedz + się, jak dodać cień do kształtu, zmienić rozmycie, ustawić przezroczystość i obrócić + cień w kilka minut. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: pl +og_description: Jak przenieść cień na kształt w Aspose.Words przy użyciu C#. Ten samouczek + pokazuje, jak dodać cień do kształtu, zmienić rozmycie, ustawić przezroczystość + i obrócić cień. +og_title: Jak przesunąć cień w Aspose.Words – Kompletny przewodnik C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Jak przesunąć cień w Aspose.Words – Kompletny przewodnik C# +url: /pl/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak przesunąć cień w Aspose.Words – Kompletny przewodnik C# + +Zastanawiałeś się kiedyś, **jak przesunąć cień** na kształcie w dokumencie Word bez ręcznego otwierania Worda? W codziennej pracy często musiałem programowo modyfikować cień kształtu — czy to dla dopracowanego raportu, czy dynamicznego szablonu. Dobra wiadomość? Dzięki Aspose.Words możesz to zrobić w kilku linijkach kodu, a przy okazji nauczysz się **dodawać cień do kształtu**, **zmieniać rozmycie**, **ustawiać przezroczystość** i **obracać cień** w jednym przebiegu. + +W tym tutorialu przejdziemy przez realistyczny scenariusz: wczytanie istniejącego pliku DOCX, który już zawiera kształt, dostosowanie pozycji, miękkości, nieprzezroczystości i kierunku cienia, a na koniec zapisanie wyniku. Po zakończeniu będziesz mieć gotowy fragment kodu, który możesz wkleić do dowolnego projektu .NET, oraz zrozumiesz, dlaczego każda właściwość ma znaczenie. + +## Wymagania wstępne – Co potrzebujesz przed rozpoczęciem + +- **Aspose.Words for .NET** (wersja 23.12 lub nowsza). Pobierz go z NuGet za pomocą `Install-Package Aspose.Words`. +- Środowisko programistyczne .NET 6+ (Visual Studio, VS Code, Rider — cokolwiek wolisz). +- Plik Word wejściowy (`input.docx`), który już zawiera przynajmniej jeden kształt (prostokąt, koło lub obrazek będą wystarczające). +- Podstawowa znajomość składni C# — nic skomplikowanego. + +Jeśli czegoś brakuje, zatrzymaj się na chwilę i zainstaluj bibliotekę; dalsza część przewodnika zakłada, że pakiet jest już dodany do projektu. + +## Krok 1: Wczytaj dokument i pobierz docelowy kształt – **Jak przesunąć cień** zaczyna się tutaj + +Pierwsze, co robimy, to wczytujemy dokument źródłowy i znajdujemy kształt, który chcemy zmodyfikować. Aspose.Words traktuje każdy obiekt (akapity, tabele, kształty) jako węzeł w drzewie, więc możemy go od razu zapytać. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Dlaczego to ważne:** Wczytanie dokumentu raz i ponowne użycie tej samej instancji `Document` jest wydajne. Wywołanie `GetChild` jest bezpieczne, ponieważ zwraca `null`, gdy indeks jest poza zakresem, co pozwala elegancko obsłużyć brakujące kształty. + +## Krok 2: Dostosuj promień rozmycia – Mistrzowskie **Jak zmienić rozmycie** + +Miękki cień wygląda profesjonalnie, natomiast twarda krawędź może sprawiać wrażenie taniości. Właściwość `BlurRadius` kontroluje miękkość w punktach (1 pt ≈ 1/72 cala). Podnieśmy ją do 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro tip:** Domyślne rozmycie wynosi 0,5 pt. Wszystko powyżej 5 pt jest zazwyczaj zauważalne, ale uważaj, by nie przesadzić — zbyt duże rozmycie może sprawić, że kształt będzie wyglądał, jakby odrywał się od strony. + +## Krok 3: Ustaw przezroczystość – Odpowiedź na **Jak ustawić przezroczystość** + +Przezroczystość określa, jak bardzo cień jest prześwitujący. Wartość `0` oznacza całkowitą nieprzezroczystość; `1` — całkowitą niewidzialność. Dla subtelnego efektu użyjemy `0.3` (30 % przezroczystości). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Dlaczego może cię to interesować:** Jeśli kształt jest ciemny, w pełni nieprzezroczysty cień może przytłoczyć leżący pod nim tekst. Regulacja przezroczystości utrzymuje czytelność dokumentu, jednocześnie dodając głębię. + +## Krok 4: Przesuń cień – Sedno **Jak przesunąć cień** + +Właściwość `Distance` określa, jak daleko cień jest odsunięty od kształtu, mierzona w punktach. Większa odległość powoduje, że cień jest dalej, tworząc bardziej dramatyczny efekt. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Co zrobić, gdy potrzebny jest minimalny offset?** Ustawienie `Distance` na `0` spowoduje, że cień znajdzie się bezpośrednio pod kształtem, co może być przydatne przy efektach wytłoczenia. + +## Krok 5: Obróć źródło światła – Rozwiązanie **Jak obrócić cień** + +Cienie nie zawsze padają prosto w dół; podążają za kątem źródła światła. Właściwość `Angle` (w stopniach) obraca cień wokół kształtu. Przechylmy go o 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Szybki eksperyment:** Spróbuj `90` dla cienia po prawej stronie lub `-30` dla cienia po lewej. Zmiana jest natychmiastowa. + +## Krok 6: Zapisz dokument – Zobacz wynik **Dodaj cień do kształtu** + +Teraz, gdy dostosowaliśmy cień, zapisujemy dokument na dysku. Możesz nadpisać oryginał lub utworzyć nowy plik; w przykładzie używamy nowego pliku wyjściowego. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Oczekiwany rezultat:** Otwórz `output.docx`. Cień kształtu będzie miększy, lekko odsunięty, półprzezroczysty i obrócony o 45°. Porównując go obok `input.docx`, różnica będzie wyraźna. + +### Pełny działający przykład (gotowy do kopiowania) + +Poniżej znajduje się cały program w jednym bloku. Wklej go do nowego projektu konsolowego, zamień `YOUR_DIRECTORY` na rzeczywistą ścieżkę folderu i uruchom. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Często zadawane pytania i przypadki brzegowe + +### Co zrobić, gdy dokument zawiera wiele kształtów? + +Możesz przeiterować wszystkie kształty: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Czy mogę dodać cień do kształtu, który go nie ma? + +Oczywiście. Obiekt `ShadowFormat` zawsze istnieje; wystarczy go włączyć: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Czy to działa z obrazkami i SmartArt? + +Tak. Każdy węzeł dziedziczący po `Shape` — w tym obrazy, wykresy i SmartArt — udostępnia `ShadowFormat`. Te same właściwości mają zastosowanie. + +### Jak kontrolować kolor cienia? + +Użyj właściwości `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Obawy dotyczące kompatybilności? + +Aspose.Words 23.12+ obsługuje .NET 6, .NET Core 3.1 oraz .NET Framework 4.6.2+. Pokazane API jest stabilne we wszystkich tych wersjach. + +## Podsumowanie + +Właśnie omówiliśmy **jak przesunąć cień** na kształcie przy użyciu Aspose.Words, a przy okazji zaprezentowaliśmy **dodawanie cienia do kształtu**, **zmianę rozmycia**, **ustawianie przezroczystości** oraz **obracanie cienia**. Kompletny, gotowy do uruchomienia przykład pozwala w kilka sekund dostosować cień dowolnego kształtu, nadając dokumentom wykończenie i profesjonalny wygląd, bez konieczności otwierania Worda. + +Gotowy na kolejny krok? Spróbuj połączyć te modyfikacje cienia z **formatowaniem warunkowym** — na przykład zastosować głębszy cień tylko do nagłówków lub wykresów przekraczających określony rozmiar. Albo zbadaj **gradientowe wypełnienia** samego kształtu, aby stworzyć naprawdę przyciągający wzrok projekt. + +Jeśli napotkasz problemy, zostaw komentarz poniżej. Szczęśliwego kodowania i niech Twoje cienie zawsze padają dokładnie tam, gdzie chcesz! + +![Diagram pokazujący efekt przesunięcia cienia na kształcie – przykład jak przesunąć cień](https://example.com/images/shadow-demo.png "przykład jak przesunąć cień") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/basic-conversions/_index.md b/words/portuguese/net/basic-conversions/_index.md index c473dfde66..70b6b52a87 100644 --- a/words/portuguese/net/basic-conversions/_index.md +++ b/words/portuguese/net/basic-conversions/_index.md @@ -33,6 +33,7 @@ Conversões Básicas orienta você nas conversões básicas de documentos usando | [Como Exportar LaTeX do Word – Guia Passo a Passo](./how-to-export-latex-from-word-step-by-step-guide/) | Aprenda a exportar conteúdo LaTeX de documentos Word usando Aspose.Words para .NET. Guia passo a passo com exemplos de código. | | [Converter Word para PDF em C# usando Aspose.Words – Guia](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aprenda a converter documentos Word para PDF em C# usando Aspose.Words com este guia passo a passo. | | [Salvar Word como PDF com Aspose.Words – Guia Completo C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aprenda a salvar documentos Word como PDF usando Aspose.Words em C#. Guia completo passo a passo. | +| [Salvar Word como PDF com Aspose.Words – Guia Completo](./save-word-as-pdf-with-aspose-words-complete-guide/) | Aprenda a salvar documentos Word como PDF usando Aspose.Words. Guia completo passo a passo. | | [Salvar Docx como PDF com Aspose.Words – Guia Completo C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Aprenda a salvar documentos Docx como PDF usando Aspose.Words em C#. Guia completo passo a passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/portuguese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 731f8fd977..e5a77db863 100644 --- a/words/portuguese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/portuguese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,22 @@ --- category: general -date: 2025-12-29 -description: Como exportar LaTeX do Word usando Aspose.Words – aprenda a converter - Word para LaTeX, salvar docx como txt e lidar com equações em texto simples. +date: 2026-05-01 +description: Aprenda como exportar LaTeX de um arquivo Word, converter Word para txt + e preservar tabelas usando Aspose.Words em C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: pt -og_description: Como exportar LaTeX do Word com Aspose.Words. Este guia mostra como - converter Word para LaTeX, salvar docx como txt e manter as equações intactas. -og_title: Como Exportar LaTeX do Word – Tutorial Rápido de C# +og_description: Descubra como exportar LaTeX do Word, converter Word para texto simples + e manter o layout da tabela intacto com Aspose.Words. +og_title: Como Exportar LaTeX do Word – Tutorial Completo de C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Como Exportar LaTeX do Word – Guia Passo a Passo url: /pt/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,162 +26,215 @@ url: /pt/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Como Exportar LaTeX do Word – Guia Passo a Passo +# Como Exportar LaTeX do Word – Tutorial Completo em C# -Já se perguntou **como exportar LaTeX do Word** sem perder aquelas complicadas equações do Office Math? Você não está sozinho. Muitos desenvolvedores se deparam com um obstáculo ao tentar *converter Word para LaTeX* para artigos acadêmicos, relatórios científicos ou pipelines de publicação automatizados. +Já se perguntou **como exportar LaTeX** de um documento Word sem perder nenhuma das equações matemáticas? Você não está sozinho. Muitos desenvolvedores precisam transformar um .docx que contém Office Math em LaTeX limpo enquanto também **convert word to txt** para processamento posterior. Neste guia, vamos percorrer uma solução prática, pronta‑para‑executar que **preserva tabelas**, fornece um arquivo de texto simples e mantém a marcação LaTeX exatamente onde você precisa. -Neste tutorial, percorreremos um exemplo completo e pronto‑para‑executar em C# que mostra **como exportar LaTeX** usando Aspose.Words, explica **como salvar arquivos txt** com marcação LaTeX e ainda aborda as nuances de **convert word equations latex** para que nada se perca na tradução. - -> **Dica profissional:** A mesma abordagem funciona para qualquer .docx que você tenha — basta apontar o código para um caminho de arquivo diferente. - ---- +Vamos cobrir tudo, desde o carregamento do arquivo fonte até o ajuste de `TxtSaveOptions` para que a saída seja tanto legível por humanos quanto amigável para máquinas. Ao final, você será capaz de **save docx as txt**, **convert Word to plain text**, e saber **how to preserve tables** durante a exportação. Sem scripts externos, sem copiar‑colar manual — apenas código puro em C# que você pode inserir em qualquer projeto .NET. ## O que você precisará -Antes de mergulharmos, certifique‑se de que você tem os seguintes pré‑requisitos: - -| Pré‑requisito | Por que isso importa | -|--------------|----------------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words tem como alvo runtimes .NET modernos. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | A biblioteca realiza o trabalho pesado de analisar Word e gerar LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Para ver a conversão para LaTeX em ação. | -| **Visual Studio 2022** (or any IDE you like) | Facilita a depuração e a execução do exemplo. | - -Se ainda não instalou o pacote NuGet, execute: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (última versão, 2024.x ou mais recente). O pacote NuGet é `Aspose.Words`. +- Um ambiente de desenvolvimento .NET (Visual Studio, VS Code, Rider — qualquer um serve). +- Um arquivo Word (`.docx`) que contém equações Office Math e pelo menos uma tabela (para que possamos ver a magia da preservação de tabelas). -É isso — sem DLLs extras, sem interop COM, apenas uma biblioteca gerenciada limpa. +É isso. Se você já tem tudo isso, continue lendo; caso contrário, obtenha o pacote NuGet e um DOCX de exemplo antes de mergulharmos mais fundo. -## Como Exportar LaTeX do Word – Visão Geral - -A seguir está a visão geral do que vamos alcançar: +--- -1. **Carregar** o documento Word de origem (`.docx`). -2. **Configure** `TxtSaveOptions` para que quaisquer objetos Office Math sejam emitidos como código LaTeX. -3. **Salvar** o documento como um arquivo de texto simples (`.txt`) que você pode alimentar diretamente em qualquer compilador LaTeX. +## Como Exportar LaTeX de um Documento Word -![Exemplo de como exportar LaTeX do Word](image.png "Como exportar LaTeX do Word") +A seguir está o cerne do tutorial — três passos concisos que respondem à pergunta **how to export latex** enquanto também tratam dos objetivos secundários de **convert word to txt**, **convert word to plain text**, **save docx as txt**, e **how to preserve tables**. -## Etapa 1: Carregar o Documento Word +### Etapa 1: Carregar o Arquivo DOCX -Primeiro de tudo — abra o .docx que você deseja converter. A classe `Document` abstrai todo o XML subjacente, fornecendo um modelo de objetos amigável. +Primeiro, precisamos ler o documento Word em um objeto `Aspose.Words.Document`. Esta etapa é a mesma, independentemente de você depois **convert word to txt** ou **save docx as txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Por que isso importa:** -Carregar o arquivo antecipadamente nos permite inspecionar seu conteúdo (por exemplo, contar equações) antes de decidirmos como serializá‑lo. Se o arquivo estiver corrompido, `Document` lançará uma exceção clara, poupando‑o de uma saída misteriosa mais tarde. +> **Por que isso importa:** Carregar o arquivo cria uma representação em memória de todos os elementos do Word — parágrafos, tabelas e objetos Office Math. Sem esse objeto, você não pode manipular as opções de exportação. + +### Etapa 2: Configurar `TxtSaveOptions` para LaTeX e Layout de Tabela -## Etapa 2: Configurar TxtSaveOptions para Exportação LaTeX +A classe `TxtSaveOptions` permite controlar exatamente como o arquivo de texto simples é gerado. Duas propriedades são essenciais para o nosso cenário: -A mágica acontece em `TxtSaveOptions`. Ao definir `OfficeMathExportMode` como `LaTeX`, cada objeto Office Math é transformado em sua representação LaTeX correspondente. +| Propriedade | O que faz | Por que você precisa | +|-------------|-----------|----------------------| +| `OfficeMathExportMode` | Determina como o Office Math é renderizado. Definir como `LaTeX` converte equações para a sintaxe LaTeX. | Este é o núcleo de **how to export latex**. | +| `PreserveTableLayout` | Quando `true`, o Aspose adiciona espaços em branco para que as tabelas mantenham uma aparência de grade. | Isso satisfaz **how to preserve tables** enquanto você **convert word to txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Por que escolhemos estas configurações:** +> **Dica:** Se você precisar apenas do LaTeX bruto sem formatação de tabela, defina `PreserveTableLayout` como `false`. O arquivo fica menor, mas você perde a indicação visual da tabela. + +### Etapa 3: Salvar o Documento como Texto Simples + +Agora escrevemos o documento em um arquivo `.txt` usando as opções que acabamos de definir. Esta única linha realiza **convert word to plain text**, **save docx as txt**, e, claro, **how to export latex** de uma só vez. -- `OfficeMathExportMode.LaTeX` é o único modo que garante uma tradução matemática fiel. -- `PreserveTableLayout` mantém as tabelas com a mesma aparência do Word, o que é útil quando você incorpora a saída em um ambiente LaTeX `tabular`. -- UTF‑8 garante que caracteres como “α”, “β” ou “∑” sobrevivam ao ciclo completo. +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` -Se você precisar **convert word to latex** sem o contêiner de texto simples, pode mudar para `SaveFormat.LaTeX` — apenas uma dica rápida para cenários avanç. +Depois que a chamada terminar, abra `output.txt`. Você verá: -## Etapa 3: Salvar o Documento como Arquivo de Texto +- Trechos LaTeX como `\frac{a}{b}` para cada equação Office Math. +- Tabelas renderizadas com os caracteres `|` e `-`, preservando o alinhamento das colunas. +- Parágrafos normais como texto simples, prontos para qualquer analisador posterior. -Agora escrevemos o texto rico em LaTeX no disco. O `.txt` resultante pode ser renomeado para `.tex` posteriormente, ou encaminhado diretamente para um compilador LaTeX. +### Exemplo Completo em Funcionamento -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +Juntando tudo, aqui está um programa autônomo que você pode compilar e executar hoje: -// Save using the configured options -doc.Save(outputPath, txtOptions); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**O que você verá em `output.txt`:** +**Saída esperada** (trecho): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Todos os demais parágrafos aparecem como texto simples, enquanto qualquer equação Office Math é envolvida em um ambiente LaTeX `equation` (ou `inline` se estava inline no Word). Isso satisfaz perfeitamente o requisito **convert word equations latex**. +Observe como a tabela mantém sua grade e a equação aparece como LaTeX limpo. Esse é o ponto ideal quando você **convert word to txt** e ainda precisa de uma representação fiel tanto da estrutura quanto da matemática. + +--- -## Casos de Borda & Perguntas Frequentes +## Dicas para Converter Word para TXT e Preservar Tabelas -| Situação | O que fazer | -|-----------|------------| -| **No equations in the source** | A conversão ainda funciona; você receberá apenas texto simples. Nenhum código LaTeX extra é adicionado. | -| **Very large documents (>100 MB)** | Considere transmitir a saída usando `MemoryStream` para evitar alto consumo de memória. | -| **Unsupported Math constructs** | Aspose.Words cobre 99 % do Office Math. Para o raro caso de borda, pode ser necessário pós‑processar o LaTeX manualmente. | -| **Need a .tex file instead of .txt** | Altere `outputPath` para terminar com `.tex` e, opcionalmente, defina `txtOptions.Encoding` como `Encoding.UTF8`. | -| **Running on Linux/macOS** | O mesmo código funciona — apenas garanta que os caminhos de arquivo usem barras normais ou `Path.Combine`. | +Embora a abordagem de três passos funcione na maioria dos casos, projetos do mundo real costumam apresentar desafios. Abaixo estão sugestões práticas que tornam seu pipeline de **convert word to plain text** robusto. -## Como Salvar TXT com Equações LaTeX – Resumo Rápido +### Use uma Codificação Consistente -1. **Carregar** o .docx (`Document`). -2. **Definir** `OfficeMathExportMode = LaTeX` em `TxtSaveOptions`. -3. **Salvar** o arquivo (`doc.Save`) com essas opções. +`TxtSaveOptions` tem UTF‑8 como padrão, o que lida com a maioria dos caracteres. Se você precisar de uma página de código diferente (por exemplo, sistemas legados que esperam Windows‑1252), defina a propriedade `Encoding`: -Esse é todo o fluxo de trabalho para **how to save txt** arquivos que contêm equações formatadas em LaTeX. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -## Bônus: Automatizando a Conversão para Vários Arquivos +### Remover Espaços em Branco Excessivos -Se você tem uma pasta cheia de documentos Word, envolva a lógica acima em um loop simples: +Tabelas com muitas colunas podem gerar linhas longas. Após salvar, você pode querer pós‑processar o arquivo para colapsar múltiplos espaços em um único tab: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Lidar com Tabelas Aninhadas + +Se seu DOCX contém tabelas dentro de tabelas, `PreserveTableLayout` ainda manterá a hierarquia visual, mas a indentação pode parecer estranha. Uma solução rápida é substituir os espaços iniciais por um marcador personalizado (por exemplo, `>>`) para que analisadores posteriores possam detectar os níveis de aninhamento. + +### Processamento em Lote de Múltiplos Arquivos + +Quando você precisar **convert word to txt** para dezenas de documentos, envolva a lógica em um loop: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Agora você pode **convert word to latex** em massa — perfeito para grupos de pesquisa que recebem dezenas de manuscritos diariamente. +Dessa forma, você pode **save docx as txt** em massa sem intervenção manual. + +--- + +## Armadilhas Comuns e Como Evitá‑las + +1. **Modo de Exportação LaTeX Ausente** – Se você esquecer de definir `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, as equações voltarão ao texto simples (por exemplo, “Equation 1”). Sempre verifique novamente o bloco de opções. +2. **Layout da Tabela se Perde** – Definir `PreserveTableLayout` como `false` é o padrão. Se sua saída parecer um bloco de texto, provavelmente você não ativou a flag. +3. **Caminhos de Arquivo com Espaços** – Usar strings brutas (`@"C:\My Folder\input.docx"`) evita problemas de escape. Caso contrário, você receberá uma `FileNotFoundException`. +4. **Incompatibilidade de Versão** – Versões mais antigas do Aspose.Words (< 21.9) não suportam `OfficeMathExportMode`. Atualize para o pacote mais recente para garantir que **how to export latex** funcione. +5. **Erros de Codificação para Caracteres Não‑ASCII** – Se você vir símbolos �, defina explicitamente `options.Encoding` para UTF‑8 ou a página de código apropriada. + +--- + +## Expandindo a Solução: De TXT para Markdown ou HTML + +Às vezes você precisa de mais que texto simples — talvez um arquivo Markdown que ainda contenha blocos LaTeX. O mesmo `TxtSaveOptions` pode ser substituído por `HtmlSaveOptions` ou `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Essa pequena mudança permite que você obtenha uma saída no estilo **convert word to txt** enquanto mantém a sintaxe markdown que você adora. + +--- ## Conclusão -Cobremos **how to export LaTeX from Word** passo a passo, demonstramos **how to save txt** arquivos que preservam cada equação Office Math, e ainda mostramos como **convert word equations latex** sem perder fidelidade. +Percorremos uma resposta completa e pronta para produção de **how to export latex** a partir de um documento Word, ao mesmo tempo mostrando como **convert word to txt**, **convert word to plain text**, **save docx as txt**, e **how to preserve tables**. Os principais pontos são: + +- Carregar o DOCX com `Aspose.Words.Document`. +- Definir `TxtSaveOptions.OfficeMathExportMode = LaTeX` e `PreserveTableLayout = true`. +- Chamar `doc.Save(outputPath, options)` para obter um arquivo de texto simples rico em LaTeX limpo. -Com apenas algumas linhas de C# e a poderosa biblioteca Aspose.Words, você pode transformar qualquer .docx em texto pronto para LaTeX, pronto para inclusão em artigos científicos, livros didáticos ou pipelines de publicação automatizados. +Experimente em seus próprios arquivos, experimente ajustes de codificação e sinta-se à vontade para processar pastas inteiras em lote. Se você encontrar casos extremos — tabelas aninhadas, caracteres exóticos ou versões antigas do Aspose — consulte as seções “Dicas” e “Armadilhas” para soluções rápidas. -**Próximos passos?** Experimente alimentar o `.txt` gerado (ou renomeá‑lo para `.tex`) ao `pdflatex` ou `xelatex` para produzir um PDF, ou explore a opção `SaveFormat.LaTeX` para um arquivo `.tex` direto. Se precisar **save docx as txt** enquanto preserva a formatação, experimente `PreserveTableLayout` e manipulação personalizada de quebras de linha. +Pronto para o próximo passo? Tente converter o mesmo DOCX para Markdown, ou alimente o `.txt` gerado em um gerador de site estático que renderiza LaTeX na web. As possibilidades são infinitas, e agora você tem uma base sólida para qualquer fluxo de trabalho **convert word to txt**. -Tem perguntas sobre casos de borda, licenciamento ou ajustes de desempenho? Deixe um comentário abaixo — feliz codificação! +Feliz codificação, e que seu LaTeX sempre compile na primeira tentativa! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/portuguese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/portuguese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..e397610be8 --- /dev/null +++ b/words/portuguese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-01 +description: Salve Word como PDF usando Aspose.Words em C#. Aprenda a converter docx + para PDF, detectar fontes ausentes e lidar eficientemente com avisos de substituição + de fontes. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: pt +og_description: Salvar Word como PDF usando Aspose.Words. Este tutorial passo a passo + mostra como converter docx para PDF e detectar fontes ausentes. +og_title: Salvar Word como PDF com Aspose.Words – Guia Completo +tags: +- Aspose.Words +- C# +- PDF conversion +title: Salvar Word como PDF com Aspose.Words – Guia Completo +url: /pt/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salvar Word como PDF com Aspose.Words – Guia Completo + +Já precisou **salvar Word como PDF** rapidamente e se perguntou se perderia alguma fonte no caminho? Você não está sozinho—desenvolvedores constantemente lidam com dores de cabeça de fontes ausentes ao converter documentos. Neste guia, vamos percorrer uma solução prática que não só **converte docx para pdf** mas também **detecta fontes ausentes** usando os avisos de substituição de fontes do Aspose.Words. + +Cobriremos tudo, desde a configuração do coletor de avisos até a interpretação da saída, de modo que ao final você saberá exatamente como **salvar Word como PDF** sem surpresas. Sem ferramentas externas, sem configurações obscuras—apenas código C# limpo que você pode inserir em qualquer projeto .NET. + +## O que você precisará + +- **Aspose.Words for .NET** (versão mais recente, por exemplo, 24.10) – você pode obtê-lo via NuGet (`Install-Package Aspose.Words`). +- Um ambiente de desenvolvimento .NET (Visual Studio, Rider ou VS Code funciona bem). +- Um arquivo DOCX de exemplo que pode conter fontes não instaladas na máquina de destino. + +É isso. Se você tem esses requisitos básicos, estamos prontos para mergulhar. + +## Salvar Word como PDF – Visão geral passo a passo + +Abaixo está o programa completo e executável. Sinta-se à vontade para copiar‑colar em um projeto de aplicativo console e pressionar **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Dica profissional:** Substitua `YOUR_DIRECTORY` por um caminho absoluto ou use `Path.Combine(Environment.CurrentDirectory, "input.docx")` para uma abordagem relativa e mais segura. + +### Por que usamos um callback de aviso + +Aspose.Words substitui silenciosamente fontes ausentes por uma fonte padrão (geralmente Arial). Sem um callback, você nunca saberia que a substituição ocorreu, o que pode causar falhas de layout no PDF resultante. Ao conectar `IWarningCallback`, obtemos uma lista clara e programática de cada evento de fonte ausente—perfeita para registro ou notificação dos usuários finais. + +### Detectar fontes ausentes – O que observar + +Ao executar o programa, qualquer fonte ausente produzirá uma linha no console semelhante a: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Se a lista estiver vazia, parabéns—**salvar word como pdf** foi bem-sucedido com todas as fontes originais intactas. + +## Converter Docx para PDF – Personalizando a saída + +Às vezes você precisa de uma versão específica de PDF, qualidade de imagem ou nível de conformidade. Aspose.Words permite ajustar o objeto `PdfSaveOptions` antes de chamar `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Por que isso importa:** Se você está gerando PDFs para arquivos legais, definir `PdfA1b` garante que o arquivo atenda a padrões rigorosos. A mesma conversão ainda respeita nosso callback de aviso, então você ainda **detectará fontes ausentes**. + +## Substituição de Fonte do Aspose Words – Lidando com casos extremos + +### Cenário 1: Várias fontes ausentes + +Se seu documento de origem usa várias fontes personalizadas, o coletor de avisos conterá uma entrada por fonte. Você pode agregá-las: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Cenário 2: Fornecendo um diretório de fontes de fallback + +Aspose.Words pode pesquisar pastas adicionais por fontes. Defina a propriedade `FontsFolder` em `FontSettings` antes de carregar o documento: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Agora a biblioteca tentará sua pasta personalizada primeiro, reduzindo a chance de substituição indesejada. + +### Cenário 3: Ignorando substituições + +Se você prefere que a conversão falhe quando uma fonte está ausente (em vez de substituir silenciosamente), lance uma exceção dentro do callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Isso obriga você a resolver a fonte ausente antes de prosseguir—útil em pipelines de CI onde falhas silenciosas são inaceitáveis. + +## Exemplo completo de ponta a ponta + +Juntando tudo, aqui está uma versão compacta que demonstra **como converter Word para PDF**, define opções de PDF personalizadas e registra quaisquer problemas de fonte: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Saída esperada no console** (se Calibri estiver ausente): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Se não aparecerem avisos, sua operação de **salvar word como pdf** usou exatamente as mesmas fontes do DOCX de origem. + +## Resumo visual + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Texto alternativo da imagem:* **salvar word como pdf** fluxo mostrando carregamento, coleta de avisos e saída PDF. + +## Perguntas frequentes + +| Pergunta | Resposta | +|----------|--------| +| **Preciso de uma licença para Aspose.Words?** | Uma licença de avaliação gratuita funciona para testes, mas o uso em produção requer uma licença paga para remover a marca d'água de avaliação. | +| **Isso funciona em .NET Core / .NET 6+?** | Absolutamente—Aspose.Words tem como alvo .NET Standard 2.0, então qualquer runtime .NET recente é compatível. | +| **Posso converter vários arquivos DOCX em um loop?** | Sim, basta instanciar um novo `Document` para cada arquivo e reutilizar o mesmo `WarningInfoCollector` se quiser resultados agregados. | +| **E se a pasta de saída não existir?** | `Document.Save` lançará `DirectoryNotFoundException`. Crie a pasta primeiro ou use `Directory.CreateDirectory`. | +| **Existe uma forma de incorporar as fontes ausentes no PDF?** | Aspose.Words pode incorporar fontes automaticamente se elas estiverem disponíveis na máquina; defina `PdfSaveOptions.EmbedFullFonts = true`. | + +## Conclusão + +Agora você tem um padrão sólido e pronto para produção para **salvar Word como PDF** enquanto **detecta fontes ausentes** e lida com cenários de **substituição de fonte do Aspose.Words**. Ao anexar um callback de aviso, personalizar pastas de fontes e, opcionalmente, ajustar `PdfSaveOptions`, você pode converter **docx para pdf** de forma confiável e manter seus usuários informados sobre quaisquer problemas de fonte que possam afetar a fidelidade do layout. + +Pronto para o próximo passo? Tente gerar PDFs a partir de vários documentos em paralelo, ou explore a adição de marcas d'água e assinaturas digitais—ambas são extensões simples do código que você acabou de dominar. Feliz codificação, e que seus PDFs sempre tenham exatamente a aparência pretendida! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-loadoptions/_index.md b/words/portuguese/net/programming-with-loadoptions/_index.md index 4cf4ddce0c..2783eb0715 100644 --- a/words/portuguese/net/programming-with-loadoptions/_index.md +++ b/words/portuguese/net/programming-with-loadoptions/_index.md @@ -37,10 +37,10 @@ Nestes tutoriais, você aprenderá a usar LoadOptions para carregar documentos d | [Aspose Load Options – Carregar DOCX com Configurações de Fonte Personalizadas](./aspose-load-options-load-docx-with-custom-font-settings/) | Aprenda a carregar documentos DOCX usando LoadOptions com fontes personalizadas no Aspose.Words para .NET. Guia passo a passo incluído. | | [Recuperar Arquivo Word Danificado – Guia Completo para Abrir DOCX Corrompido e Obter Contagem de Páginas](./recover-damaged-word-file-complete-guide-to-open-corrupted-d/) | Aprenda a reparar arquivos Word danificados, abrir DOCX corrompidos e obter a contagem de páginas usando Aspose.Words para .NET. | | [Como recuperar docx – Guia C# para arquivos Word corrompidos](./how-to-recover-docx-c-guide-for-corrupted-word-files/) | Aprenda a recuperar arquivos DOCX corrompidos usando C# com Aspose.Words para .NET. Guia passo a passo para restaurar documentos. | - | [Recuperar documento Word com Aspose.Words em C#](./recover-word-document-with-aspose-words-in-c/) | Aprenda a recuperar documentos Word usando Aspose.Words em C# com este guia passo a passo. | | [Como usar LoadOptions no Aspose.Words – Guia completo](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Aprenda passo a passo como utilizar LoadOptions no Aspose.Words para .NET, configurando opções avançadas de carregamento de documentos. | | [Recuperar documento corrompido em C# – Definir modo de recuperação e solicitar ao usuário](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Aprenda a recuperar documentos corrompidos em C# definindo o modo de recuperação e exibindo prompts ao usuário com Aspose.Words. | +| [Recuperar docx corrompido – Guia completo para carregar arquivos Word danificados em C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Aprenda a carregar e reparar arquivos DOCX corrompidos usando C# com Aspose.Words, passo a passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/portuguese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..af3ceab4c0 --- /dev/null +++ b/words/portuguese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Recupere arquivos docx corrompidos rapidamente usando Aspose.Words. Aprenda + como definir o modo de recuperação, carregar docx com segurança e ler arquivos Word + danificados em apenas alguns passos. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: pt +og_description: Recupere arquivos docx corrompidos em C#. Defina o modo de recuperação, + carregue o docx com segurança e leia arquivos Word danificados com Aspose.Words. +og_title: Recupere docx corrompido – Guia rápido de C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Recuperar docx corrompido – Guia completo para carregar arquivos Word danificados + em C# +url: /pt/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Recuperar docx corrompido – Guia rápido em C# + +Já tentou abrir um arquivo Word que simplesmente não carregava e se perguntou se o conteúdo estava perdido para sempre? Em muitos projetos do mundo real, você **recuperará docx corrompidos** sem pedir ao usuário que reenvie o anexo. A boa notícia é que o Aspose.Words torna isso muito fácil: basta definir o modo de recuperação e deixar a biblioteca fazer o trabalho pesado. + +Neste tutorial, percorreremos os passos exatos para **recuperar docx corrompidos**, explicar por que a opção `RecoveryMode.AutoRecover` é a escolha mais segura e mostrar como **carregar docx** que podem estar parcialmente danificados. Ao final, você será capaz de ler um arquivo Word danificado, extrair o texto que sobreviveu e até registrar o formato original para auditorias futuras. Sem ferramentas externas, apenas código C# limpo. + +## O que você precisará + +- **Aspose.Words for .NET** (qualquer versão recente; a API que usamos funciona com 23.5 e superior). +- Um ambiente de desenvolvimento .NET (Visual Studio, VS Code ou Rider). +- O `.docx` corrompido ou parcialmente danificado que você deseja recuperar. + +Sem permissões especiais, sem interop COM e sem necessidade de instalar o Microsoft Office no servidor. Simples, não? + +## Etapa 1: Definir o modo de recuperação para Auto‑Recover + +Quando um arquivo Word está quebrado, o comportamento padrão de carregamento lança uma exceção e aborta. Ao configurar um objeto `LoadOptions`, você indica ao Aspose.Words para **definir o modo de recuperação** como `AutoRecover`, que analisa o pacote zip, ignora as partes ilegíveis e devolve o que conseguir reconstruir. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Por que AutoRecover?** +> Ele tenta ler o máximo possível mantendo o objeto do documento utilizável. Se você escolher `RecoveryMode.NoRecovery`, o carregamento falhará na primeira corrupção, o que anula o objetivo de cenários de **recuperar docx corrompidos**. + +## Etapa 2: Carregar o documento com as opções configuradas + +Agora que o modo de recuperação está definido, você pode tentar abrir o arquivo com segurança. Substitua `"YOUR_DIRECTORY/input.docx"` pelo caminho real do seu arquivo danificado. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Se o arquivo estiver apenas parcialmente corrompido, a instância `Document` ainda será criada. Você pode verificar `document.IsStructureValid` posteriormente se precisar de validação extra. + +## Etapa 3: Verificar o formato detectado + +O Aspose.Words detecta automaticamente o formato original (DOC, DOCX, ODT, etc.). Exibir esse valor ajuda a confirmar que a biblioteca reconheceu o arquivo corretamente, o que é uma verificação rápida de sanidade após uma operação de **recuperar docx corrompidos**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Saída típica: + +``` +Loaded with Docx format. +``` + +Mesmo que algumas partes estejam ausentes, a detecção de formato ainda tem sucesso — mais uma vantagem para fluxos de trabalho de **recuperar docx corrompidos**. + +## Etapa 4: Extrair o que for possível + +Depois que o documento é carregado, você pode tratá-lo como qualquer arquivo Word saudável. Abaixo está um exemplo compacto que extrai texto simples e o escreve no console. Isso demonstra que você pode **ler conteúdo de arquivo Word danificado** sem travamentos. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Se o arquivo original continha tabelas ou imagens que estavam corrompidas, elas simplesmente serão omitidas na saída de texto. O restante do documento permanece intacto. + +## Etapa 5: Salvar uma cópia limpa (Opcional) + +Frequentemente você desejará fornecer ao usuário uma nova versão limpa do arquivo após a recuperação. Salvar no mesmo formato garante compatibilidade com quaisquer processos subsequentes. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Agora você tem um arquivo **docx danificado recuperado** que pode anexar com segurança a um e‑mail ou passar para outro serviço. + +## Exemplo completo em funcionamento + +Juntando tudo, aqui está o programa completo, pronto para ser executado. Cole-o em um novo projeto de console, ajuste os caminhos dos arquivos e pressione F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Saída esperada** (supondo que o arquivo contenha um único parágrafo “Hello world!” e algum XML corrompido): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Observe como o programa nunca trava — mesmo que o arquivo de origem estivesse parcialmente quebrado. Essa é a essência de **recuperar docx corrompidos** usando o Aspose.Words. + +## Perguntas comuns e casos extremos + +### E se o arquivo for completamente ilegível? + +Mesmo o `AutoRecover` tem limites. Se o contêiner zip estiver corrompido além do reparo, o Aspose.Words lançará uma `CorruptedFileException`. Nesse caso, pode ser necessário usar uma ferramenta de reparo de zip de terceiros antes de tentar **recuperar docx corrompidos** novamente. + +### Posso recuperar outros formatos (por exemplo, `.doc`, `.odt`)? + +Com certeza. O mesmo `LoadOptions` funciona para qualquer formato que o Aspose.Words suporte. Basta mudar a extensão do arquivo e a biblioteca detectará o formato original automaticamente. Isso significa que você também pode **recuperar arquivos semelhantes a docx danificados**, como `.doc` ou `.rtf`, com o mesmo código. + +### Como lidar com documentos grandes sem carregar tudo na memória? + +Para arquivos de tamanho gigabyte, você pode habilitar **opções de carregamento** como `LoadOptions.LoadFormat` ou transmitir o documento página a página. Contudo, o algoritmo de recuperação ainda precisa ler todo o pacote, portanto espere um uso maior de memória para arquivos corrompidos muito grandes. + +### Existe uma maneira de saber quais partes foram perdidas? + +Após o carregamento, você pode inspecionar `document.GetChildNodes(NodeType.Any, true)` e comparar a contagem com uma linha de base esperada. Tabelas, imagens ou cabeçalhos ausentes simplesmente não aparecerão na coleção de nós. Isso permite registrar exatamente o que foi **recuperado de docx danificado** e informar o usuário. + +## Dicas profissionais para recuperação confiável + +- **Valide o tamanho do arquivo de entrada** antes de carregar; um arquivo de zero bytes sempre falhará. +- **Registre o resultado do `RecoveryMode`** capturando `DocumentLoadingException` e armazenando a mensagem da exceção; ela costuma conter pistas sobre quais partes foram ignoradas. +- **Execute a recuperação em uma thread em segundo plano** se você estiver processando uploads em um serviço web — isso mantém a requisição responsiva. +- **Combine com uma soma de verificação** (por exemplo, MD5) para detectar se o arquivo recuperado difere do original; assim você pode decidir se mantém ambas as versões. + +## Conclusão + +Acabamos de mostrar como **recuperar docx corrompidos** em C# definindo o **modo de recuperação** para `AutoRecover`, carregando o documento com segurança, extraindo o texto que sobrevive e, opcionalmente, salvando uma cópia limpa. Essa abordagem permite que você **carregue docx** que de outra forma lançariam exceções, e oferece uma maneira confiável de **ler conteúdo de arquivo Word danificado** sem ferramentas externas. + +Próximos passos? Experimente trocar `RecoveryMode.AutoRecover` por `RecoveryMode.NoRecovery` para ver a diferença, ou experimente as propriedades do `LoadOptions` que controlam o tratamento de senhas e substituição de fontes. Você também pode integrar a rotina de recuperação em uma API ASP.NET Core que aceita uploads e devolve um arquivo reparado — perfeito para pipelines corporativos de gerenciamento de documentos. + +Tem mais perguntas sobre recuperação de documentos Word, ou quer ver como **recuperar docx danificados** com callbacks personalizados? Deixe um comentário abaixo e feliz codificação! + +![Ilustração de um documento recuperado – recuperar docx corrompido](https://example.com/images/recover-corrupted-docx.png "recuperar docx corrompido") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-markdownsaveoptions/_index.md b/words/portuguese/net/programming-with-markdownsaveoptions/_index.md index 0d50695fe3..85508dfd17 100644 --- a/words/portuguese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/portuguese/net/programming-with-markdownsaveoptions/_index.md @@ -75,6 +75,9 @@ Aprenda a extrair e salvar imagens de documentos Word ao convertê-los para Mark ### [Converter Word para Markdown em C# – Guia completo com extração de imagens](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) Aprenda a converter documentos Word para Markdown em C#, extraindo imagens e preservando a formatação usando Aspose.Words. +### [Salvar docx como markdown – Exportar matemática do Word para LaTeX com Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) +Aprenda a exportar equações matemáticas de documentos Word para LaTeX ao salvar como Markdown usando Aspose.Words. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/portuguese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..68ff423240 --- /dev/null +++ b/words/portuguese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: salve docx como markdown usando Aspose.Words – aprenda a converter Word + para markdown, exportar equações para LaTeX e definir a resolução de imagens em + markdown em um fluxo de trabalho contínuo. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: pt +og_description: salvar docx como markdown com Aspose.Words. Este tutorial mostra como + converter Word para markdown, exportar equações para LaTeX e definir a resolução + de imagens em markdown. +og_title: salvar docx como markdown – Guia completo para exportar equações do Word + como LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: salvar docx como markdown – Exportar matemática do Word para LaTeX com Aspose.Words +url: /pt/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# salvar docx como markdown – Exportar Word Math para LaTeX com Aspose.Words + +Já precisou **salvar docx como markdown** mas ficou travado em como manter as equações do Office Math nítidas? Você não está sozinho. A maioria dos desenvolvedores bate na parede quando a conversão padrão transforma as equações em imagens borradas, forçando uma reescrita manual em LaTeX. + +Boa notícia: o Aspose.Words pode fazer o trabalho pesado por você. Neste tutorial vamos **converter word para markdown**, instruir o motor a **exportar equações para latex** e ainda **definir a resolução de imagens markdown** para o restante do documento. Ao final, você terá um único comando que gera um arquivo `.md` limpo com matemática pronta para LaTeX e imagens em alta resolução. + +## O que você vai aprender + +- Como carregar um `.docx` que contém objetos Office Math. +- Quais propriedades de `MarkdownSaveOptions` controlam **exportar equações para latex** e **definir a resolução de imagens markdown**. +- Um trecho completo e executável em C# que você pode colar em qualquer projeto .NET. +- Dicas para solucionar armadilhas comuns, como fontes ausentes ou recursos de equação não suportados. + +**Pré‑requisitos**: .NET 6+ (ou .NET Framework 4.6+), uma licença para Aspose.Words for .NET e familiaridade básica com C#. Se você está confortável criando um aplicativo de console, está pronto para começar. + +--- + +## Etapa 1 – Salvar docx como markdown: carregue seu arquivo Word + +A primeira coisa que precisamos é de um objeto `Document` que aponte para o `.docx` de origem. Pense nisso como abrir o livro antes de começar a copiar capítulos. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Por que isso importa*: Se o documento não contiver nenhuma matemática, a etapa **exportar equações para latex** será um no‑op, mas o restante da conversão ainda será executado. A verificação evita que você se pergunte por que seu Markdown de saída está sem blocos LaTeX. + +--- + +## Etapa 2 – Configurar Exportação de Equações para LaTeX + +O Aspose.Words permite decidir como o Office Math será renderizado. Por padrão ele os converte em imagens PNG, o que explica por que muitos tutoriais acabam com um arquivo markdown granulado. Alterar `OfficeMathExportMode` para `LaTeX` fornece equações limpas, prontas para copiar e colar. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Por que `OfficeMathExportMode.LaTeX`?* LaTeX é a lingua franca da publicação científica. Quando você renderizar o markdown com um gerador de site estático ou um notebook Jupyter, as equações aparecerão nítidas em qualquer nível de zoom. + +--- + +## Etapa 3 – Definir Resolução de Imagens Markdown (para Conteúdo Não‑Matemático) + +Mesmo focando na matemática, a maioria dos documentos Word também contém fotos, gráficos ou SVGs incorporados. A propriedade `ImageResolution` controla como o Aspose.Words rasteriza esses recursos. Um valor de **300 DPI** é um ponto ideal para tela e impressão. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Dica de especialista*: Se seu markdown será exibido apenas na web, você pode reduzir para 150 DPI para diminuir o tamanho do arquivo. Por outro lado, para PDFs prontos para impressão, aumente para 600 DPI. + +--- + +## Etapa 4 – Executar a Conversão – Converter Word Math para LaTeX + +Com tudo configurado, a conversão real é uma única linha. O Aspose.Words faz o trabalho pesado nos bastidores. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Saída esperada**: Abra o arquivo `.md` gerado e você deverá ver algo como: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Observe os blocos LaTeX (`$...$` e `$$...$$`) substituindo os trechos PNG anteriores. A imagem ao final ainda é um PNG, renderizada em 300 DPI como solicitamos. + +--- + +## Etapa 5 – Casos de Borda Comuns & Como Lidar com Eles + +| Situação | O que acontece | Como corrigir | +|-----------|----------------|---------------| +| **Fontes ausentes** (ex.: Cambria Math não instalada) | A saída LaTeX pode conter símbolos desconhecidos. | Instale a fonte faltante no servidor ou incorpore-a no documento antes da conversão. | +| **Equações complexas** (matriz com delimitadores personalizados) | O Aspose.Words pode recair para uma imagem apesar do modo `LaTeX`. | Atualize para a versão mais recente do Aspose.Words; a biblioteca melhora continuamente a cobertura de equações. | +| **Documentos grandes** ( > 50 MB ) | Pressão de memória pode causar `OutOfMemoryException`. | Use `LoadOptions` com `LoadFormat.Docx` e faça streaming do arquivo, ou divida o documento em seções antes da conversão. | +| **Tamanho de imagem muito grande** | O arquivo markdown fica enorme, retardando builds de sites estáticos. | Reduza `ImageResolution` para 150 DPI em cenários somente web (veja a Etapa 3). | + +--- + +## Etapa 6 – Junte Tudo: Exemplo Completo Funcional + +Abaixo está o programa *completo* de console que você pode copiar‑colar em `Program.cs`. Ele inclui todas as partes discutidas, mais um pouco de tratamento de erros. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Execute o programa (`dotnet run`) e você obterá um arquivo markdown que **salva docx como markdown** preservando cada equação como LaTeX. Sem cópia manual, sem imagens rasterizadas feias para matemática. + +--- + +## Conclusão + +Percorremos todo o processo de **salvar docx como markdown** com Aspose.Words, desde o carregamento do arquivo Word até a configuração de **exportar equações para latex** e **definir a resolução de imagens markdown**. O trecho final está pronto para produção e pode ser inserido em qualquer projeto .NET que precise **converter word para markdown** em tempo real. + +Qual o próximo passo? Experimente alimentar o `.md` gerado em um gerador de site estático como Hugo ou Jekyll e veja suas equações renderizarem lindamente. Se precisar **converter word math latex** para outros formatos (PDF, HTML), basta trocar `MarkdownSaveOptions` por `PdfSaveOptions` ou `HtmlSaveOptions`—o mesmo sinalizador `OfficeMathExportMode` funciona em todos eles. + +Tem alguma variação no seu fluxo, como buscar arquivos Word do Azure Blob Storage ou transmiti‑los de uma API? O mesmo padrão se aplica; basta substituir o construtor `Document` baseado em sistema de arquivos por um baseado em stream. + +Sinta‑se à vontade para experimentar e nos conte nos comentários como essa abordagem resolveu seus problemas de conversão. Feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-pdfsaveoptions/_index.md b/words/portuguese/net/programming-with-pdfsaveoptions/_index.md index f8fba90ef0..a5ee15258b 100644 --- a/words/portuguese/net/programming-with-pdfsaveoptions/_index.md +++ b/words/portuguese/net/programming-with-pdfsaveoptions/_index.md @@ -49,8 +49,8 @@ Quer você queira converter documentos do Word em PDF para distribuição online | [Criar PDF acessível a partir do Word com C# – Guia passo a passo](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Aprenda a gerar PDFs acessíveis a partir de documentos Word usando C# e Aspose.Words, seguindo este guia passo a passo. | | [Criar PDF acessível em C# – Tutorial de acessibilidade de PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Aprenda a criar PDFs acessíveis em C# usando Aspose.Words, garantindo conformidade com padrões de acessibilidade. | | [Criar PDF acessível a partir do Word – Guia completo](./create-accessible-pdf-from-word-complete-guide/) | Aprenda a criar PDFs acessíveis a partir de documentos Word, garantindo conformidade com padrões de acessibilidade, usando Aspose.Words para .NET. | - | [Criar PDF acessível – Guia passo a passo para conformidade PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Aprenda a criar PDFs acessíveis compatíveis com PDF/UA usando Aspose.Words para .NET com este guia passo a passo. | +| [Salvar documento como PDF com Aspose.Words – Guia completo em C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Aprenda passo a passo como converter documentos Word em PDF usando Aspose.Words em C# com exemplos completos. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/portuguese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..4beca99660 --- /dev/null +++ b/words/portuguese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: Aprenda como salvar documento como PDF usando Aspose.Words em C#. O tutorial + também aborda converter Word para PDF, exportar LaTeX de matemática e lidar com + fontes ausentes. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: pt +og_description: Salve o documento como PDF sem esforço com Aspose.Words. Este guia + também mostra como converter Word para PDF, exportar LaTeX de matemática e lidar + com fontes ausentes. +og_title: Salvar documento como PDF com Aspose.Words – Guia completo em C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Salvar documento como PDF com Aspose.Words – Guia completo em C# +url: /pt/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salvar Documento como PDF com Aspose.Words – Guia Completo em C# + +Já se perguntou **como salvar documento como pdf** diretamente de um arquivo Word sem perder recursos de acessibilidade? Você não está sozinho—os desenvolvedores perguntam constantemente por uma maneira confiável de converter Word para PDF preservando equações matemáticas e lidando com fontes ausentes de forma elegante. + +Neste tutorial vamos percorrer uma solução passo a passo que não só **save document as pdf** mas também demonstra **convert word to pdf**, **export math latex**, e **handle missing fonts** usando a versão mais recente do Aspose.Words para .NET. Ao final, você terá um programa C# pronto‑para‑executar que produz arquivos compatíveis com PDF/UA‑2, perfeitos para auditorias de acessibilidade. + +## O que você precisará + +- .NET 6 ou posterior (o código funciona também com .NET Core e .NET Framework) +- Aspose.Words for .NET 25.10 ou mais recente – você pode obter uma avaliação gratuita no site da Aspose +- Um documento Word modesto (`input.docx`) que contenha ao menos uma forma flutuante e uma equação matemática (para ver o recurso export‑math‑latex em ação) +- Visual Studio 2022 (ou qualquer IDE de sua preferência) + +> **Dica profissional:** Se você estiver em um pipeline CI/CD, adicione o pacote NuGet Aspose.Words ao seu arquivo de projeto: + +```xml + +``` + +## Etapa 1: Carregar o Documento Fonte com Recuperação Automática + +Ao lidar com arquivos Word do mundo real, você pode encontrar seções corrompidas ou recursos ausentes. Habilitar a recuperação automática garante que o processo de carregamento nunca lance uma exceção. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Por que isso importa:** +`RecoveryMode.AutoRecover` protege seu pipeline de travar com entrada malformada, o que é especialmente útil quando você **convert word to pdf** em massa. + +## Etapa 2: Configurar Opções de Salvamento PDF para Acessibilidade Completa + +PDF/UA‑2 é o padrão ISO para PDFs acessíveis. Ao configurar alguns sinalizadores, obtemos um arquivo que leitores de tela podem navegar, e também garantimos que as equações matemáticas sejam exportadas como LaTeX oculto. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Pontos principais:** + +- **ExportFloatingShapesAsInlineTag** – garante que o PDF resultante respeite o layout original mantendo a correção semântica. +- **OfficeMathExportMode.LaTeX** – satisfaz o requisito **export math latex**, permitindo que ferramentas subsequentes extraiam as equações, se necessário. + +## Etapa 3: Capturar Avisos (por exemplo, Fontes Ausentes) + +Fontes ausentes são um incômodo comum ao converter documentos. Aspose.Words pode relatar esses problemas via um `WarningCallback`. Nós os coletaremos para que você possa registrá‑los ou agir sobre eles mais tarde. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Por que isso importa:** +Se a fonte da origem não estiver instalada no servidor, o PDF usará uma fonte padrão, potencialmente quebrando o layout. Ao **handle missing fonts** podemos alertar o usuário ou incorporar um substituto. + +## Etapa 4: Salvar o Documento como PDF Acessível + +Agora chega o momento da verdade—realizar efetivamente a conversão. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Se tudo correr bem, você terá um arquivo PDF/UA‑2 que contém LaTeX oculto para cada equação e marcação adequada para formas flutuantes. + +## Etapa 5: Revisar Avisos Capturados (Opcional, mas Recomendado) + +Após a operação de salvamento, você pode iterar sobre os avisos coletados e registrá‑los. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +A saída típica pode ser assim: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Ver essas mensagens cedo ajuda você a **handle missing fonts** antes que afetem os usuários finais. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está o programa completo, pronto‑para‑executar. Substitua os caminhos de placeholder pelos seus próprios. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Resultado esperado:** +- `output.pdf` está em conformidade com PDF/UA‑2. +- Todas as formas flutuantes são marcadas como figuras inline. +- Todo objeto Office Math aparece como LaTeX oculto (visível ao inspecionar a estrutura do PDF). +- Qualquer problema relacionado a fontes é impresso no console, dando a você a chance de **handle missing fonts** antes de distribuir o arquivo. + +![Diagrama mostrando o fluxo de Word → Aspose.Words → PDF Acessível (save document as pdf)](conversion-diagram.png "Diagrama de fluxo para salvar documento como pdf") + +*Texto alternativo da imagem:* **Diagrama de como salvar documento como pdf usando Aspose.Words** + +## Perguntas Frequentes e Casos Limítrofes + +### E se eu estiver usando uma versão mais antiga do Aspose.Words? + +O sinalizador `OfficeMathExportMode.LaTeX` foi introduzido na 25.10. Para versões mais antigas você ainda pode **convert word to pdf**, mas a matemática será rasterizada em vez de exportada como LaTeX. Atualize para melhor acessibilidade. + +### Posso incorporar fontes personalizadas para evitar fallback? + +Sim. Defina `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` antes de chamar `Save`. Isso também ajuda a **handle missing fonts** ao forçar o PDF a conter os glifos necessários. + +### Como verifico a conformidade PDF/UA‑2? + +Abra o arquivo no Adobe Acrobat Pro → “Print Production” → “Preflight”. Escolha o perfil “PDF/A‑2b” ou “PDF/UA‑2”; o Acrobat relatará quaisquer violações. + +### E quanto a arquivos Word protegidos por senha? + +Carregue o documento com um `LoadOptions` que inclua `Password`. Exemplo: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +O resto do pipeline permanece inalterado. + +## Conclusão + +Cobremos tudo o que você precisa para **save document as pdf** usando Aspose.Words em C#. O tutorial também demonstrou como **convert word to pdf**, **export math latex**, e **handle missing fonts**—tudo enquanto produz um arquivo PDF/UA‑2 acessível. + +Teste o código, experimente diferentes `PdfSaveOptions` (por exemplo, compressão de imagens, PDF/A‑2b), e integre‑o ao seu serviço de processamento de documentos. Se precisar ir além, considere explorar a biblioteca específica de PDF da Aspose para pós‑processamento ou assinaturas digitais. + +Tem mais cenários que gostaria de enfrentar? Sinta‑se à vontade para deixar um comentário ou conferir nossos outros guias sobre **PDF manipulation**, **image extraction**, e **batch conversion**. Feliz codificação! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-shapes/_index.md b/words/portuguese/net/programming-with-shapes/_index.md index 65b773c1b5..c40f3040d4 100644 --- a/words/portuguese/net/programming-with-shapes/_index.md +++ b/words/portuguese/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Usando o Aspose.Words para .NET e seguindo estes tutoriais, você dominará a ma | [Criar forma retangular no Word usando C# – Guia passo a passo](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Aprenda a criar uma forma retangular em documentos do Word usando C# com este guia passo a passo. | | [Tutorial de Sombra de Forma do Aspose.Words – Adicionar Sombra a Forma do Word em C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Aprenda a adicionar sombra a formas em documentos do Word usando o Aspose.Words para .NET com este tutorial passo a passo. | | [Criar documento Word em branco com forma de retângulo sombreada – Guia passo a passo](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Aprenda a criar um documento Word em branco com uma forma de retângulo sombreada usando o Aspose.Words para .NET. | +| [Como mover sombra no Aspose.Words – Guia completo em C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Aprenda a mover sombras em formas do Word usando Aspose.Words com C# neste guia passo a passo. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/portuguese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..9ac7fb3f15 --- /dev/null +++ b/words/portuguese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Como mover a sombra em uma forma no Aspose.Words usando C#. Aprenda a + adicionar sombra à forma, alterar o desfoque, definir a transparência e girar a + sombra em minutos. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: pt +og_description: Como mover a sombra em uma forma no Aspose.Words usando C#. Este tutorial + mostra como adicionar sombra à forma, alterar o desfoque, definir a transparência + e girar a sombra. +og_title: Como mover sombra no Aspose.Words – Guia completo em C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Como mover a sombra no Aspose.Words – Guia completo em C# +url: /pt/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como Mover Sombra no Aspose.Words – Guia Completo em C# + +Já se perguntou **como mover a sombra** de uma forma dentro de um documento Word sem abrir o Word manualmente? No meu dia a dia, frequentemente precisei ajustar a sombra de uma forma programaticamente — seja para um relatório refinado ou um modelo dinâmico. A boa notícia? Com Aspose.Words você pode fazer isso em poucas linhas, e ainda aprenderá **adicionar sombra à forma**, **como mudar o desfoque**, **como definir transparência** e **como girar a sombra** tudo de uma vez. + +Neste tutorial vamos percorrer um cenário real: carregar um DOCX existente que já contém uma forma, ajustar a posição, suavidade, opacidade e direção da sombra e, por fim, salvar o resultado. Ao final, você terá um trecho reutilizável que pode ser inserido em qualquer projeto .NET, e entenderá por que cada propriedade é importante. + +## Pré‑requisitos – O Que Você Precisa Antes de Começar + +- **Aspose.Words for .NET** (versão 23.12 ou posterior). Você pode obtê‑lo via NuGet com `Install-Package Aspose.Words`. +- Um ambiente de desenvolvimento .NET 6+ (Visual Studio, VS Code, Rider — o que preferir). +- Um arquivo Word de entrada (`input.docx`) que já contenha ao menos uma forma (um retângulo, círculo ou imagem serve). +- Familiaridade básica com a sintaxe C# — nada avançado. + +Se estiver faltando algum desses itens, faça uma pausa e instale a biblioteca; o restante do guia assume que o pacote já está referenciado. + +## Etapa 1: Carregar o Documento e Capturar a Forma‑Alvo – **Como Mover Sombra** Começa Aqui + +A primeira coisa que fazemos é carregar o documento fonte e localizar a forma que queremos modificar. Aspose.Words trata cada objeto (parágrafos, tabelas, formas) como um nó em uma árvore, permitindo consultá‑lo diretamente. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Por que isso importa:** Carregar o documento uma única vez e reutilizar a mesma instância `Document` é eficiente. A chamada `GetChild` é segura porque retorna `null` se o índice estiver fora do intervalo, permitindo lidar com formas ausentes de forma elegante. + +## Etapa 2: Ajustar o Raio de Desfoque – Domine **Como Mudar Desfoque** + +Uma sombra suave parece profissional, enquanto uma borda dura pode parecer barata. A propriedade `BlurRadius` controla a suavidade em pontos (1 pt ≈ 1/72 polegada). Vamos aumentá‑la para 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Dica de especialista:** O desfoque padrão é 0,5 pt. Qualquer valor acima de 5 pt costuma ser perceptível, mas cuidado para não exagerar — pode fazer a forma parecer desconectada da página. + +## Etapa 3: Definir Transparência – A Resposta para **Como Definir Transparência** + +Transparência determina o quão translúcida a sombra será. Valor `0` significa totalmente opaco; `1` significa completamente invisível. Para um efeito sutil usaremos `0.3` (30 % transparente). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Por que isso pode ser importante:** Se a forma for escura, uma sombra totalmente opaca pode ofuscar o texto subjacente. Ajustar a transparência mantém o documento legível e ainda confere profundidade. + +## Etapa 4: Mover a Sombra – O Núcleo de **Como Mover Sombra** + +A propriedade `Distance` define a distância da sombra em relação à forma, medida em pontos. Uma distância maior desloca a sombra mais longe, criando um efeito mais dramático. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **E se precisar de um deslocamento mínimo?** Definir `Distance` como `0` fará a sombra ficar diretamente atrás da forma, útil para efeitos de relevo. + +## Etapa 5: Rotacionar a Fonte de Luz – Resolvendo **Como Girar Sombra** + +Sombras não são apenas para baixo; elas seguem o ângulo da fonte de luz. A propriedade `Angle` (em graus) gira a sombra ao redor da forma. Vamos inclinar 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Experimento rápido:** Tente `90` para uma sombra à direita ou `-30` para uma sombra inclinada à esquerda. A mudança visual é imediata. + +## Etapa 6: Salvar o Documento – Visualizando o Resultado de **Adicionar Sombra à Forma** + +Agora que ajustamos a sombra, vamos gravar o documento de volta ao disco. Você pode sobrescrever o original ou criar um novo arquivo; o exemplo usa um arquivo de saída novo. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Saída esperada:** Abra `output.docx`. A sombra da forma aparecerá mais suave, ligeiramente deslocada, semitransparente e inclinada em 45°. Se comparar lado a lado com `input.docx`, a diferença será notória. + +### Exemplo Completo (Pronto para Copiar‑Colar) + +Abaixo está o programa inteiro em um único bloco. Cole em um novo projeto de console, substitua `YOUR_DIRECTORY` por um caminho de pasta real e execute. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Perguntas Frequentes & Casos de Borda + +### E se o documento tiver várias formas? + +Você pode percorrer todas as formas: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Posso adicionar sombra a uma forma que ainda não tem sombra? + +Com certeza. O objeto `ShadowFormat` está sempre presente; basta habilitá‑lo: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Isso funciona com imagens e SmartArt? + +Sim. Qualquer nó que derive de `Shape` — incluindo imagens, gráficos e SmartArt — expõe `ShadowFormat`. As mesmas propriedades se aplicam. + +### Como controlo a cor da sombra? + +Use a propriedade `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Preocupações de compatibilidade? + +Aspose.Words 23.12+ suporta .NET 6, .NET Core 3.1 e .NET Framework 4.6.2+. A API mostrada é estável nessas versões. + +## Conclusão + +Acabamos de cobrir **como mover sombra** em uma forma usando Aspose.Words e, ao longo do caminho, demonstramos **adicionar sombra à forma**, **como mudar desfoque**, **como definir transparência** e **como girar sombra**. O exemplo completo e executável permite ajustar a sombra de qualquer forma em segundos, conferindo aos seus documentos um aspecto polido e profissional sem jamais abrir o Word. + +Pronto para o próximo passo? Experimente combinar esses ajustes de sombra com **formatação condicional** — por exemplo, aplicar uma sombra mais profunda apenas a títulos ou a gráficos que excedam certo tamanho. Ou explore **preenchimentos gradientes** para a própria forma e crie um design realmente chamativo. + +Se encontrar algum obstáculo, deixe um comentário abaixo. Boa codificação, e que suas sombras caiam exatamente onde você deseja! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/basic-conversions/_index.md b/words/russian/net/basic-conversions/_index.md index c6ad4f2e14..d97cee444e 100644 --- a/words/russian/net/basic-conversions/_index.md +++ b/words/russian/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ Basic Conversions проведет вас через базовые преобр | [Конвертировать Word в PDF в C# с Aspose.Words – Руководство](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Узнайте, как конвертировать Word в PDF в C# с помощью Aspose.Words. Пошаговое руководство для разработчиков. | | [Сохранить Word как PDF с Aspose.Words – Полное руководство C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Узнайте, как сохранить документ Word в PDF с помощью Aspose.Words в C#. Подробное руководство с примерами кода. | | [Сохранить DOCX как PDF с Aspose.Words – Полное руководство C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Узнайте, как сохранить документ DOCX в PDF с помощью Aspose.Words в C#. Подробное руководство с примерами кода. | +| [Сохранить Word как PDF с Aspose.Words – Полное руководство](./save-word-as-pdf-with-aspose-words-complete-guide/) | Узнайте, как сохранить документ Word в PDF с помощью Aspose.Words. Подробное руководство с примерами кода. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/russian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 62686bf256..3d7c675fcc 100644 --- a/words/russian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/russian/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,27 +1,24 @@ --- category: general -date: 2025-12-29 -description: Как экспортировать LaTeX из Word с помощью Aspose.Words – узнайте, как - конвертировать Word в LaTeX, сохранить docx как txt и работать с уравнениями в простом - тексте. +date: 2026-05-01 +description: Узнайте, как экспортировать LaTeX из файла Word, преобразовать Word в + txt и сохранить таблицы с помощью Aspose.Words в C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: ru -og_description: Как экспортировать LaTeX из Word с помощью Aspose.Words. Это руководство - покажет, как преобразовать Word в LaTeX, сохранить docx как txt и сохранить формулы - без изменений. -og_title: Как экспортировать LaTeX из Word – быстрый урок по C# +og_description: Узнайте, как экспортировать LaTeX из Word, преобразовать Word в обычный + текст и сохранить макет таблицы неизменным с помощью Aspose.Words. +og_title: Как экспортировать LaTeX из Word – Полный учебник по C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: Как экспортировать LaTeX из Word – пошаговое руководство +title: Как экспортировать LaTeX из Word – пошаговое руководство url: /ru/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -29,178 +26,215 @@ url: /ru/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Как экспортировать LaTeX из Word – Пошаговое руководство +# Как экспортировать LaTeX из Word – Полный C# учебник -Задумывались ли вы когда‑нибудь **как экспортировать LaTeX из Word** без потери сложных уравнений Office Math? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда пытаются *convert Word to LaTeX* для академических статей, научных отчётов или автоматизированных конвейеров публикаций. +Когда‑нибудь задавались вопросом **how to export LaTeX** из документа Word без потери математических формул? Вы не одиноки. Многие разработчики нуждаются в преобразовании .docx, содержащего Office Math, в чистый LaTeX, одновременно **convert Word to txt** для последующей обработки. В этом руководстве мы пошагово разберём практичное, готовое к запуску решение, которое **preserves tables**, выдаёт обычный текстовый файл и сохраняет разметку LaTeX именно там, где она нужна. -В этом руководстве мы пройдем полный, готовый к запуску пример на C#, который демонстрирует **how to export LaTeX** с использованием Aspose.Words, объясняет **how to save txt** файлы с разметкой LaTeX и даже рассматривает нюансы **convert word equations latex**, чтобы ничего не терялось при конвертации. +Мы охватим всё: от загрузки исходного файла до настройки `TxtSaveOptions`, чтобы результат был одновременно удобочитаемым для человека и пригодным для машин. К концу вы сможете **save docx as txt**, **convert Word to plain text**, а также знать **how to preserve tables** при экспорте. Никаких внешних скриптов, никаких ручных копирований — только чистый C# код, который можно вставить в любой .NET проект. -> **Pro tip:** Этот же подход работает с любым .docx — просто укажите коду другой путь к файлу. +## Что понадобится + +- **Aspose.Words for .NET** (последняя версия, 2024.x или новее). Пакет NuGet — `Aspose.Words`. +- Среда разработки .NET (Visual Studio, VS Code, Rider — любая подойдет). +- Файл Word (`.docx`), содержащий уравнения Office Math и хотя бы одну таблицу (чтобы увидеть магию сохранения таблиц). + +Это всё. Если у вас уже есть эти вещи, продолжайте чтение; иначе скачайте пакет NuGet и образец DOCX перед тем, как углубиться дальше. --- -## Что понадобится +## Как экспортировать LaTeX из документа Word -Прежде чем погрузиться, убедитесь, что у вас есть следующие предварительные требования: +Ниже — сердце руководства — три лаконичных шага, отвечающих на вопрос **how to export latex**, а также решающих второстепенные задачи **convert word to txt**, **convert word to plain text**, **save docx as txt** и **how to preserve tables**. -| Требование | Почему это важно | -|------------|------------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words ориентирован на современные среды .NET. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | Библиотека выполняет основную работу по разбору Word и генерации LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Чтобы увидеть процесс конвертации LaTeX в действии. | -| **Visual Studio 2022** (or any IDE you like) | Обеспечивает простую отладку и запуск примера. | +### Шаг 1: Загрузите файл DOCX -Если вы ещё не установили пакет NuGet, выполните: +Сначала нужно прочитать документ Word в объект `Aspose.Words.Document`. Этот шаг одинаков независимо от того, будете ли вы позже **convert word to txt** или **save docx as txt**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -Вот и всё — никаких дополнительных DLL, без COM‑interop, только чистая управляемая библиотека. +> **Почему это важно:** Загрузка файла создаёт в памяти представление всех элементов Word — абзацев, таблиц и объектов Office Math. Без этого объекта вы не сможете управлять параметрами экспорта. ---- +### Шаг 2: Настройте `TxtSaveOptions` для LaTeX и макета таблиц -## Как экспортировать LaTeX из Word – Обзор +Класс `TxtSaveOptions` позволяет точно контролировать, как генерируется текстовый файл. Для нашего сценария ключевыми являются два свойства: -Ниже представлена общая картина того, что мы собираемся выполнить: +| Свойство | Что делает | Зачем нужно | +|----------|------------|--------------| +| `OfficeMathExportMode` | Определяет, как будет отображаться Office Math. Установка в `LaTeX` преобразует уравнения в синтаксис LaTeX. | Это ядро **how to export latex**. | +| `PreserveTableLayout` | При `true` Aspose добавляет пробелы, чтобы таблицы сохраняли вид сетки. | Это удовлетворяет **how to preserve tables**, пока вы **convert word to txt**. | -1. **Load** исходный документ Word (`.docx`). -2. **Configure** `TxtSaveOptions`, чтобы любые объекты Office Math выводились как код LaTeX. -3. **Save** документ как обычный текстовый файл (`.txt`), который можно напрямую передать в любой компилятор LaTeX. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Как экспортировать LaTeX из Word пример](image.png "Как экспортировать LaTeX из Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Совет:** Если вам нужен только «сырой» LaTeX без форматирования таблиц, установите `PreserveTableLayout` в `false`. Файл станет меньше, но вы потеряете визуальный индикатор таблицы. -## Шаг 1: Загрузка документа Word +### Шаг 3: Сохраните документ как обычный текст -Сначала откройте .docx, который хотите конвертировать. Класс `Document` скрывает всю внутреннюю XML‑структуру, предоставляя удобную объектную модель. +Теперь запишем документ в файл `.txt`, используя только что определённые параметры. Эта единственная строка одновременно реализует **convert word to plain text**, **save docx as txt** и, конечно же, **how to export latex**. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Почему это важно:** -Загрузка файла заранее позволяет нам проверить его содержимое (например, подсчитать уравнения) перед тем, как решить, как его сериализовать. Если файл повреждён, `Document` выбросит понятное исключение, спасая вас от загадочного вывода позже. +После завершения вызова откройте `output.txt`. Вы увидите: ---- +- Фрагменты LaTeX вроде `\frac{a}{b}` для каждой формулы Office Math. +- Таблицы, отрисованные символами `|` и `-`, сохраняющие выравнивание столбцов. +- Обычные абзацы как простой текст, готовый к любой последующей обработке. -## Шаг 2: Настройка TxtSaveOptions для экспорта LaTeX +### Полный рабочий пример -Волшебство происходит в `TxtSaveOptions`. Установив `OfficeMathExportMode` в `LaTeX`, каждый объект Office Math преобразуется в соответствующее представление LaTeX. +Объединив всё вместе, получаем самостоятельную программу, которую можно собрать и запустить уже сегодня: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Почему мы выбираем эти настройки:** +**Ожидаемый вывод** (фрагмент): -- `OfficeMathExport.LaTeX` — единственный режим, гарантирующий точный математический перевод. -- `PreserveTableLayout` сохраняет внешний вид таблиц, как в Word, что удобно при дальнейшем встраивании вывода в LaTeX‑окружение `tabular`. -- UTF‑8 обеспечивает сохранность символов вроде “α”, “β” или “∑” при обратном преобразовании. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Если вам когда‑нибудь понадобится **convert word to latex** без оболочки plain‑text, вы можете переключиться на `SaveFormat.LaTeX` — небольшая подсказка для продвинутых сценариев. +Обратите внимание, как таблица сохраняет свою сетку, а уравнение выглядит как чистый LaTeX. Это идеальный компромисс, когда вы **convert word to txt** и одновременно нуждаетесь в точном представлении структуры и математики. --- -## Шаг 3: Сохранение документа в текстовый файл +## Советы по конвертации Word в TXT и сохранению таблиц -Теперь мы записываем текст с LaTeX‑разметкой на диск. Полученный `.txt` позже можно переименовать в `.tex` или передать напрямую в компилятор LaTeX. +Хотя трёхшаговый подход работает в большинстве случаев, реальные проекты часто бросают вызовы. Ниже — практические рекомендации, делающие ваш конвейер **convert word to plain text** более надёжным. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Используйте единый кодировочный набор -// Save using the configured options -doc.Save(outputPath, txtOptions); +По умолчанию `TxtSaveOptions` использует UTF‑8, который покрывает большинство символов. Если нужна другая кодовая страница (например, старые системы, ожидающие Windows‑1252), задайте свойство `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Что вы увидите в `output.txt`:** +### Удаляйте лишние пробелы -``` -\begin{equation} -E = mc^{2} -\end{equation} +Таблицы с множеством столбцов могут генерировать длинные строки. После сохранения вы можете пост‑обработать файл, заменив несколько пробелов одним табом: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Все остальные абзацы выводятся как обычный текст, а любое уравнение Office Math оборачивается в LaTeX‑окружение `equation` (или `inline`, если оно было встроенным в Word). Это полностью удовлетворяет требование **convert word equations latex**. +### Обрабатывайте вложенные таблицы ---- +Если ваш DOCX содержит таблицы внутри таблиц, `PreserveTableLayout` всё равно сохранит визуальную иерархию, но отступы могут выглядеть странно. Быстрое решение — заменить ведущие пробелы на пользовательский маркер (например, `>>`), чтобы downstream‑парсеры могли определить уровень вложенности. -## Пограничные случаи и часто задаваемые вопросы +### Пакетная обработка нескольких файлов -| Ситуация | Что делать | -|----------|------------| -| **Нет уравнений в исходном файле** | Конвертация всё равно работает; вы получите просто обычный текст. Дополнительный код LaTeX не добавляется. | -| **Очень большие документы (>100 МБ)** | Рассмотрите возможность потоковой записи вывода с использованием `MemoryStream`, чтобы избежать высокого потребления памяти. | -| **Неподдерживаемые математические конструкции** | Aspose.Words покрывает 99 % Office Math. Для редких исключений может потребоваться ручная пост‑обработка LaTeX. | -| **Нужен файл .tex вместо .txt** | Измените `outputPath`, чтобы он заканчивался на `.tex`, и при необходимости задайте `txtOptions.Encoding` как `Encoding.UTF8`. | -| **Запуск на Linux/macOS** | Тот же код работает — просто убедитесь, что пути к файлам используют прямые слэши или `Path.Combine`. | +Когда нужно **convert word to txt** для десятков документов, оберните логику в цикл: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +Так вы сможете **save docx as txt** массово без ручного вмешательства. -## Как сохранить TXT с уравнениями LaTeX – Краткое резюме +--- -1. **Load** .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` в `TxtSaveOptions`. -3. **Save** файл (`doc.Save`) с этими параметрами. +## Распространённые подводные камни и как их избежать -Это весь рабочий процесс для **how to save txt** файлов, содержащих уравнения в формате LaTeX. +1. **Отсутствует режим экспорта LaTeX** — Если забыть установить `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, уравнения превратятся в обычный текст (например, “Equation 1”). Всегда проверяйте блок параметров. +2. **Потеря макета таблицы** — По умолчанию `PreserveTableLayout` = `false`. Если ваш вывод выглядит как сплошной текст, скорее всего флаг не был включён. +3. **Пути к файлам с пробелами** — Использование строк‑литералов (`@"C:\My Folder\input.docx"`) избавляет от проблем с экранированием. Иначе получите `FileNotFoundException`. +4. **Несоответствие версии** — Старые версии Aspose.Words (< 21.9) не поддерживают `OfficeMathExportMode`. Обновитесь до последнего пакета, чтобы **how to export latex** работал. +5. **Ошибки кодировки для не‑ASCII символов** — Если видите символы �, явно задайте `options.Encoding` в UTF‑8 или нужную кодовую страницу. --- -## Бонус: Автоматизация конвертации нескольких файлов +## Расширение решения: от TXT к Markdown или HTML -Если у вас есть папка, полная Word‑документов, оберните вышеописанную логику в простой цикл: +Иногда требуется не просто текст — например, файл Markdown, содержащий блоки LaTeX. Тот же `TxtSaveOptions` можно заменить на `HtmlSaveOptions` или `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Теперь вы можете **convert word to latex** пакетно — идеально для исследовательских групп, получающих десятки рукописей ежедневно. +Эта небольшая замена позволяет вам **convert word to txt**‑подобный вывод, сохраняя при этом синтаксис markdown, который вы любите. --- ## Заключение -Мы рассмотрели **how to export LaTeX from Word** пошагово, продемонстрировали **how to save txt** файлы, сохраняющие каждое уравнение Office Math, и даже показали, как **convert word equations latex** без потери точности. +Мы прошли полный, готовый к продакшну ответ на вопрос **how to export latex** из документа Word, одновременно показав, как **convert word to txt**, **convert word to plain text**, **save docx as txt** и **how to preserve tables**. Ключевые выводы: + +- Загрузите DOCX через `Aspose.Words.Document`. +- Установите `TxtSaveOptions.OfficeMathExportMode = LaTeX` и `PreserveTableLayout = true`. +- Вызовите `doc.Save(outputPath, options)`, получив чистый LaTeX‑насыщенный текстовый файл. -Всего лишь несколькими строками C# и мощной библиотекой Aspose.Words вы можете превратить любой .docx в готовый к LaTeX текст, пригодный для включения в научные статьи, учебники или автоматизированные конвейеры публикаций. +Попробуйте на своих файлах, поиграйте с настройками кодировки и смело обрабатывайте целые папки пакетно. Если столкнётесь с особенностями — вложенными таблицами, экзотическими символами или старой версией Aspose — обратитесь к разделам «Советы» и «Подводные камни» для быстрых решений. -**Next steps?** Попробуйте передать сгенерированный `.txt` (или переименовать его в `.tex`) в `pdflatex` или `xelatex` для получения PDF, либо изучите опцию `SaveFormat.LaTeX` для прямого создания файла `.tex`. Если вам нужно **save docx as txt** с сохранением форматирования, поэкспериментируйте с `PreserveTableLayout` и пользовательской обработкой разрывов строк. +Готовы к следующему шагу? Попробуйте конвертировать тот же DOCX в Markdown или передать сгенерированный `.txt` в статический генератор сайтов, который рендерит LaTeX в браузере. Возможностей бесконечно много, а теперь у вас есть надёжная база для любого **convert word to txt** рабочего процесса. -Есть вопросы о пограничных случаях, лицензировании или настройках производительности? Оставьте комментарий ниже — happy coding! +Счастливого кодинга, и пусть ваш LaTeX всегда компилируется с первой попытки! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/russian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/russian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..445174719e --- /dev/null +++ b/words/russian/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Сохраните документ Word в PDF с помощью Aspose.Words на C#. Узнайте, + как конвертировать docx в PDF, обнаруживать отсутствующие шрифты и эффективно обрабатывать + предупреждения о замене шрифтов. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: ru +og_description: Сохраните Word в PDF с помощью Aspose.Words. Этот пошаговый учебник + показывает, как преобразовать docx в pdf и обнаружить отсутствующие шрифты. +og_title: Сохранить Word в PDF с помощью Aspose.Words – Полное руководство +tags: +- Aspose.Words +- C# +- PDF conversion +title: Сохранение Word в PDF с помощью Aspose.Words – Полное руководство +url: /ru/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Сохранить Word как PDF с Aspose.Words – Полное руководство + +Когда‑то вам нужно **сохранить Word как PDF** «на лету», и вы задавались вопросом, не пропустит‑ли система какой‑то шрифт? Вы не одиноки — разработчики постоянно сталкиваются с проблемой отсутствующих шрифтов при конвертации документов. В этом руководстве мы пройдём пошаговое решение, которое не только **конвертирует docx в pdf**, но и **обнаруживает недостающие шрифты** с помощью предупреждений о замене шрифтов в Aspose.Words. + +Мы рассмотрим всё: от настройки сборщика предупреждений до интерпретации вывода, так что к концу вы точно будете знать, как **сохранить Word как PDF** без сюрпризов. Никаких внешних инструментов, никаких скрытых настроек — только чистый C#‑код, который можно вставить в любой .NET‑проект. + +## Что понадобится + +- **Aspose.Words for .NET** (последняя версия, например, 24.10) — её можно получить через NuGet (`Install-Package Aspose.Words`). +- Среда разработки .NET (Visual Studio, Rider или VS Code подойдут). +- Пример файла DOCX, который может содержать шрифты, не установленные на целевой машине. +Это всё. Если у вас есть эти базовые вещи, можно начинать. + +## Сохранить Word как PDF — Обзор шагов + +Ниже представлен полностью готовый к запуску пример программы. Скопируйте‑вставьте его в проект консольного приложения и нажмите **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Совет:** замените `YOUR_DIRECTORY` на абсолютный путь или используйте `Path.Combine(Environment.CurrentDirectory, "input.docx")` для относительного, более безопасного подхода. + +### Почему мы используем обратный вызов предупреждений + +Aspose.Words тихо заменяет недостающие шрифты запасным (обычно Arial). Без обратного вызова вы никогда не узнаете, что замена произошла, что может привести к искажениям макета в полученном PDF. Подключив `IWarningCallback`, мы получаем чёткий программный список каждого события отсутствующего шрифта — идеально для логирования или уведомления конечных пользователей. + +### Обнаружение недостающих шрифтов — Что искать + +При запуске программы любой недостающий шрифт выведет в консоль строку, похожую на: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Если список пуст, поздравляем — **сохранить Word как PDF** удалось со всеми оригинальными шрифтами. + +## Конвертировать Docx в PDF — Настройка вывода + +Иногда требуется определённая версия PDF, качество изображений или уровень соответствия стандартам. Aspose.Words позволяет настроить объект `PdfSaveOptions` перед вызовом `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Почему это важно:** если вы генерируете PDF для юридических архивов, установка `PdfA1b` гарантирует, что файл соответствует строгим требованиям. Та же конверсия сохраняет наш обратный вызов предупреждений, так что вы всё равно **обнаружите недостающие шрифты**. + +## Замена шрифтов в Aspose Words — Обработка особых случаев + +### Сценарий 1: Несколько недостающих шрифтов + +Если исходный документ использует несколько пользовательских шрифтов, сборщик предупреждений будет содержать одну запись на каждый шрифт. Их можно агрегировать: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Сценарий 2: Указание каталога запасных шрифтов + +Aspose.Words может искать шрифты в дополнительных папках. Установите свойство `FontsFolder` у `FontSettings` перед загрузкой документа: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Теперь библиотека сначала проверит вашу пользовательскую папку, уменьшая вероятность нежелательной замены. + +### Сценарий 3: Игнорирование замен + +Если вы хотите, чтобы конвертация завершалась ошибкой при отсутствии шрифта (а не заменяла его тихо), выбросьте исключение внутри обратного вызова: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Это заставит вас решить проблему с шрифтом до продолжения — полезно в CI‑конвейерах, где тихие сбои недопустимы. + +## Полный пример от начала до конца + +Объединив всё, получаем компактную версию, демонстрирующую **как конвертировать Word в PDF**, задающую пользовательские параметры PDF и регистрирующую любые проблемы со шрифтами: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Ожидаемый вывод в консоли** (если шрифт Calibri отсутствует): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Если предупреждений нет, ваша операция **сохранить Word как PDF** использовала точно такие же шрифты, как в исходном DOCX. + +## Визуальное резюме + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Текст альтернативы изображения:* **save word as pdf** workflow, показывающий загрузку, сбор предупреждений и вывод PDF. + +## Часто задаваемые вопросы + +| Вопрос | Ответ | +|----------|--------| +| **Нужна ли лицензия для Aspose.Words?** | Бесплатная оценочная лицензия подходит для тестирования, но для продакшн‑использования требуется платная лицензия, чтобы убрать водяной знак оценки. | +| **Работает ли это на .NET Core / .NET 6+?** | Да — Aspose.Words нацелен на .NET Standard 2.0, поэтому совместим с любой современной версией .NET. | +| **Можно ли конвертировать несколько DOCX файлов в цикле?** | Да, просто создавайте новый `Document` для каждого файла и при желании переиспользуйте тот же `WarningInfoCollector` для агрегированных результатов. | +| **Что делать, если папка назначения не существует?** | `Document.Save` бросит `DirectoryNotFoundException`. Создайте папку заранее или используйте `Directory.CreateDirectory`. | +| **Можно ли встроить недостающие шрифты в PDF?** | Aspose.Words может автоматически встраивать шрифты, если они доступны на машине; установите `PdfSaveOptions.EmbedFullFonts = true`. | + +## Заключение + +Теперь у вас есть надёжный, готовый к продакшн шаблон для **сохранения Word как PDF** с **обнаружением недостающих шрифтов** и обработкой сценариев **замены шрифтов Aspose.Words**. Подключив обратный вызов предупреждений, настроив каталоги шрифтов и при необходимости изменив `PdfSaveOptions`, вы сможете надёжно **конвертировать docx в pdf** и информировать пользователей о любых проблемах, которые могут повлиять на точность макета. + +Готовы к следующему шагу? Попробуйте генерировать PDF из нескольких документов параллельно или изучите добавление водяных знаков и цифровых подписей — оба направления легко реализуются на основе кода, который вы только что освоили. Приятного кодинга, и пусть ваши PDF всегда выглядят точно так, как задумано! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-loadoptions/_index.md b/words/russian/net/programming-with-loadoptions/_index.md index 566b36ed54..c7ecf0ac7f 100644 --- a/words/russian/net/programming-with-loadoptions/_index.md +++ b/words/russian/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ | [Как восстановить DOCX – установить режим восстановления и открыть повреждённые файлы Word](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Узнайте, как включить режим восстановления и открыть повреждённые файлы DOCX с помощью Aspose.Words для .NET. | | [Как использовать LoadOptions в Aspose.Words – Полное руководство](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Полное руководство по использованию LoadOptions в Aspose.Words для .NET с примерами кода. | | [Восстановление повреждённого документа в C# – установить режим восстановления и запросить пользователя](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Узнайте, как восстановить повреждённый документ в C#, установить режим восстановления и запросить действие у пользователя. | +| [Восстановление повреждённого docx – Полное руководство по загрузке повреждённых файлов Word в C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Узнайте, как восстановить повреждённые файлы DOCX в C# с помощью Aspose.Words, следуя полному руководству. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/russian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..a9f928c5b2 --- /dev/null +++ b/words/russian/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Быстро восстанавливайте повреждённые файлы docx с помощью Aspose.Words. + Узнайте, как включить режим восстановления, безопасно загрузить docx и прочитать + повреждённые файлы Word всего за несколько шагов. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: ru +og_description: Восстановление повреждённых файлов docx в C#. Установите режим восстановления, + безопасно загрузите docx и читайте повреждённые файлы Word с помощью Aspose.Words. +og_title: Восстановление повреждённого docx – Краткое руководство по C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Восстановление повреждённого docx – Полное руководство по загрузке повреждённых + файлов Word в C# +url: /ru/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Восстановление повреждённого docx – Быстрое руководство на C# + +Когда‑то пытались открыть файл Word, который просто не загружался, и задавались вопросом, навсегда ли потеряно содержимое? Во многих реальных проектах вам **нужно восстановить повреждённый docx** без просьбы к пользователю отправить вложение заново. Хорошая новость: Aspose.Words делает это элементарно — достаточно задать режим восстановления и позволить библиотеке выполнить всю тяжёлую работу. + +В этом руководстве мы пройдём по точным шагам **восстановления повреждённого docx**, объясним, почему вариант `RecoveryMode.AutoRecover` является самым безопасным, и покажем, **как загружать docx** файлы, которые могут быть частично повреждены. К концу вы сможете прочитать повреждённый Word‑файл, извлечь любой оставшийся текст и даже записать исходный формат для будущих аудитов. Никаких внешних инструментов, только чистый C#‑код. + +## Что понадобится + +- **Aspose.Words for .NET** (любая современная версия; используемый API работает с 23.5 и новее). +- Среда разработки .NET (Visual Studio, VS Code или Rider). +- Повреждённый или частично испорченный `.docx`, который нужно спасти. + +Никаких специальных прав, COM‑interop и установки Microsoft Office на сервере. Просто, правда? + +## Шаг 1: Установить режим восстановления в Auto‑Recover + +Когда Word‑файл сломан, стандартное поведение загрузки бросает исключение и прерывает процесс. Настраивая объект `LoadOptions`, вы говорите Aspose.Words **установить режим восстановления** в `AutoRecover`, который сканирует zip‑пакет, пропускает нечитаемые части и возвращает всё, что удалось собрать. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Почему AutoRecover?** +> Он пытается прочитать как можно больше, сохраняя объект документа пригодным к использованию. Если выбрать `RecoveryMode.NoRecovery`, загрузка завершится ошибкой при первой же коррумпированной части, что сводит на нет цель **восстановления повреждённого docx**. + +## Шаг 2: Загрузить документ с настроенными параметрами + +Теперь, когда режим восстановления установлен, можно безопасно попытаться открыть файл. Замените `"YOUR_DIRECTORY/input.docx"` реальным путём к вашему повреждённому файлу. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Если файл лишь частично повреждён, экземпляр `Document` всё равно будет создан. При необходимости вы можете позже проверить `document.IsStructureValid` для дополнительной валидации. + +## Шаг 3: Проверить определённый формат + +Aspose.Words автоматически определяет исходный формат (DOC, DOCX, ODT и т.д.). Вывод этого значения помогает убедиться, что библиотека правильно распознала файл — быстрый sanity‑check после операции **восстановления повреждённого docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Типичный вывод: + +``` +Loaded with Docx format. +``` + +Даже если некоторые части отсутствовали, определение формата всё равно успешно — ещё один плюс для процессов **восстановления повреждённого docx**. + +## Шаг 4: Извлечь всё, что возможно + +После загрузки документ можно использовать как любой здоровый Word‑файл. Ниже компактный пример, который извлекает простой текст и выводит его в консоль. Это демонстрирует, как **читать повреждённый word‑файл** без сбоев. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Если в оригинальном файле были таблицы или изображения, которые оказались повреждёнными, они просто не попадут в текстовый вывод. Остальная часть документа останется нетронутой. + +## Шаг 5: Сохранить чистую копию (по желанию) + +Часто после восстановления нужно предоставить пользователю новую, чистую версию файла. Сохранение в том же формате гарантирует совместимость с любыми downstream‑процессами. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Теперь у вас есть **восстановленный повреждённый docx**, который можно безопасно прикрепить к письму или передать другому сервису. + +## Полный рабочий пример + +Собрав всё вместе, получаем полностью готовую к запуску программу. Вставьте её в новый консольный проект, поправьте пути к файлам и нажмите F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Ожидаемый вывод** (при условии, что файл содержит один абзац «Hello world!» и некоторый повреждённый XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Обратите внимание, что программа никогда не падает — несмотря на частичную порчу исходного файла. Это и есть суть **восстановления повреждённого docx** с помощью Aspose.Words. + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если файл полностью нечитаем? + +Даже `AutoRecover` имеет ограничения. Если zip‑контейнер повреждён настолько, что его невозможно восстановить, Aspose.Words бросит `CorruptedFileException`. В таком случае может потребоваться сторонний инструмент для восстановления zip‑архива перед повторной попыткой **восстановления повреждённого docx**. + +### Можно ли восстанавливать другие форматы (например, `.doc`, `.odt`)? + +Конечно. Тот же `LoadOptions` работает для любого формата, поддерживаемого Aspose.Words. Достаточно изменить расширение файла, и библиотека автоматически определит исходный формат. Это значит, что вы также можете **восстанавливать повреждённые docx‑подобные** файлы, такие как `.doc` или `.rtf`, тем же кодом. + +### Как обрабатывать большие документы, не загружая всё в память? + +Для файлов гигабайтного размера можно включать дополнительные **load options**, такие как `LoadOptions.LoadFormat`, или потоково обрабатывать документ постранично. Тем не менее алгоритм восстановления всё равно читает весь пакет, поэтому ожидайте повышенное потребление памяти для очень больших повреждённых файлов. + +### Есть ли способ узнать, какие части были утеряны? + +После загрузки можно исследовать `document.GetChildNodes(NodeType.Any, true)` и сравнить количество узлов с ожидаемым базовым уровнем. Отсутствующие таблицы, изображения или колонтитулы просто не появятся в коллекции узлов. Это позволяет точно залогировать, что было **восстановлено из повреждённого docx**, и сообщить пользователю. + +## Профессиональные советы для надёжного восстановления + +- **Проверьте размер входного файла** перед загрузкой; файл нулевого размера всегда завершится ошибкой. +- **Записывайте результат `RecoveryMode`**, отлавливая `DocumentLoadingException` и сохраняя сообщение исключения; оно часто содержит подсказки о пропущенных частях. +- **Запускайте восстановление в фоновом потоке**, если обрабатываете загрузки в веб‑службе — это сохраняет отзывчивость запросов. +- **Сочетайте с контрольной суммой** (например, MD5), чтобы определить, отличается ли восстановленный файл от оригинала; затем решайте, хранить обе версии или только одну. + +## Заключение + +Мы показали, как **восстановить повреждённый docx** в C# путем **установки режима восстановления** в `AutoRecover`, безопасной загрузки документа, извлечения любого оставшегося текста и, при желании, сохранения чистой копии. Такой подход позволяет **загружать docx** файлы, которые иначе бросали бы исключения, и даёт надёжный способ **читать повреждённый word‑файл** без внешних утилит. + +Что дальше? Попробуйте заменить `RecoveryMode.AutoRecover` на `RecoveryMode.NoRecovery`, чтобы увидеть разницу, или поэкспериментируйте с свойствами `LoadOptions`, управляющими обработкой паролей и подстановкой шрифтов. Вы также можете интегрировать процедуру восстановления в ASP.NET Core API, принимающий загрузки и возвращающий отремонтированный файл — идеальное решение для корпоративных конвейеров управления документами. + +Есть дополнительные вопросы по восстановлению Word‑документов или хотите увидеть, как **восстанавливать повреждённый docx** с пользовательскими колбэками? Оставляйте комментарий ниже, и happy coding! + +![Иллюстрация восстановленного документа – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-markdownsaveoptions/_index.md b/words/russian/net/programming-with-markdownsaveoptions/_index.md index 09cee05007..b849033af2 100644 --- a/words/russian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/russian/net/programming-with-markdownsaveoptions/_index.md @@ -36,11 +36,13 @@ | [Конвертировать Word в Markdown – Встраивание изображений в формате Base64](./convert-word-to-markdown-embed-images-as-base64/) | Конвертируйте документы Word в Markdown, встраивая изображения в виде Base64, используя Aspose.Words для .NET. | | [Как сохранить Markdown из Word – Полное руководство C#](./how-to-save-markdown-from-word-complete-c-gu/) | Полное руководство по сохранению документов Word в формате Markdown с использованием C# и Aspose.Words. | | [Как сохранить Markdown из Word – Полное руководство](./how-to-save-markdown-from-word-complete-guide/) | Полное руководство по сохранению документов Word в формате Markdown с использованием Aspose.Words для .NET. | -| [Как экспортировать LaTeX: конвертировать DOCX в Markdown и TXT](./how-to-export-latex-convert-docx-to-markdown-txt/) | Экспортируйте LaTeX, преобразуя DOCX в форматы Markdown и TXT с помощью Aspose.Words для .NET. | +| [Как экспортировать LaTeX из Word: конвертировать DOCX в Markdown и TXT](./how-to-export-latex-convert-docx-to-markdown-txt/) | Экспортируйте LaTeX, преобразуя DOCX в форматы Markdown и TXT с помощью Aspose.Words для .NET. | | [Как переименовать изображения при конвертации DOCX в Markdown](./how-to-rename-images-when-converting-docx-to-markdown/) | Узнайте, как автоматически переименовывать изображения при конвертации DOCX в Markdown с помощью Aspose.Words для .NET. | | [Сохранить docx как markdown с Aspose.Words – Полное руководство C#](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Полное руководство по сохранению DOCX в Markdown с использованием Aspose.Words и C#. | | [Сохранить изображения Word – Конвертировать Word в Markdown с Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) | Сохраните изображения из документов Word и конвертируйте их в Markdown с помощью Aspose.Words для .NET. | | [Конвертировать Word в Markdown на C# – Полное руководство с извлечением изображений](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) | Подробное руководство по конвертации документов Word в Markdown с извлечением изображений на C# с использованием Aspose.Words. | +| [Сохранить docx как markdown – экспортировать математические формулы Word в LaTeX с Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Экспортируйте формулы Word в LaTeX при сохранении DOCX в Markdown с помощью Aspose.Words. | +| [Загрузка изображений в облако при конвертации Word в Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) | Конвертируйте документы Word в Markdown, автоматически загружая изображения в облако с помощью Aspose.Words для .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/russian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..e56f0e8fc5 --- /dev/null +++ b/words/russian/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-01 +description: Сохраните DOCX в формате Markdown с помощью Aspose.Words — узнайте, как + конвертировать Word в Markdown, экспортировать уравнения в LaTeX и установить разрешение + изображений в Markdown в одном плавном рабочем процессе. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: ru +og_description: Сохранить DOCX как Markdown с помощью Aspose.Words. Этот учебник показывает, + как преобразовать Word в Markdown, экспортировать уравнения в LaTeX и установить + разрешение изображений в Markdown. +og_title: Сохранить docx как markdown – Полное руководство по экспорту формул Word + в LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Сохранить docx как markdown – экспортировать формулы Word в LaTeX с помощью + Aspose.Words +url: /ru/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# сохранить docx как markdown – Экспортировать формулы Word в LaTeX с помощью Aspose.Words + +Когда‑то вам нужно было **сохранить docx как markdown**, но возникли трудности с тем, как сохранить формулы Office Math чёткими? Вы не одиноки. Большинство разработчиков сталкиваются с тем, что стандартное преобразование превращает формулы в размытые изображения, заставляя вручную переписывать их в LaTeX. + +Хорошие новости: Aspose.Words может выполнить всю тяжёлую работу за вас. В этом руководстве мы **конвертируем word в markdown**, укажем движку **экспортировать формулы в latex**, а также **установим разрешение изображений в markdown** для остального документа. В конце у вас будет одна команда, которая выдаст чистый файл `.md` с готовой к LaTeX математикой и изображениями высокого разрешения. + +## Что вы узнаете + +- Как загрузить `.docx`, содержащий объекты Office Math. +- Какие свойства `MarkdownSaveOptions` управляют **экспортом формул в latex** и **установкой разрешения изображений в markdown**. +- Полный, готовый к запуску фрагмент C#, который можно вставить в любой .NET‑проект. +- Советы по устранению распространённых проблем, таких как отсутствие шрифтов или неподдерживаемые возможности формул. + +**Prerequisites**: .NET 6+ (или .NET Framework 4.6+), лицензия Aspose.Words for .NET и базовое знакомство с C#. Если вы умеете создавать консольное приложение, вы готовы к работе. + +--- + +## Шаг 1 – Сохранить docx как markdown: загрузить ваш Word‑файл + +Первое, что нам нужно, — объект `Document`, указывающий на исходный `.docx`. Представьте, что вы открываете книгу перед тем, как начать копировать главы. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Почему это важно*: Если в документе нет формул, шаг **экспортировать формулы в latex** будет бездействующим, но остальная часть конвертации всё равно выполнится. Эта проверка избавит вас от вопросов, почему в полученном Markdown отсутствуют блоки LaTeX. + +--- + +## Шаг 2 – Настроить экспорт формул в LaTeX + +Aspose.Words позволяет задать способ рендеринга Office Math. По умолчанию они превращаются в PNG‑изображения, из‑за чего многие руководства заканчиваются «зернистым» markdown‑файлом. Переключение `OfficeMathExportMode` на `LaTeX` даёт чистые формулы, готовые к копированию. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Почему `OfficeMathExportMode.LaTeX`?* LaTeX — lingua franca научных публикаций. Когда вы позже отобразите markdown с помощью генератора статических сайтов или Jupyter‑ноутбука, формулы будут выглядеть чётко при любом масштабе. + +--- + +## Шаг 3 – Установить разрешение изображений в markdown (для контента без формул) + +Хотя мы сосредоточены на формулах, большинство Word‑документов также содержат картинки, диаграммы или встроенные SVG. Свойство `ImageResolution` управляет тем, как Aspose.Words растеризует эти ресурсы. Значение **300 DPI** — хороший компромисс для экрана и печати. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: Если ваш markdown будет отображаться только в вебе, можно снизить значение до 150 DPI, чтобы уменьшить размер файлов. И наоборот, для PDF‑файлов, готовых к печати, поднимите до 600 DPI. + +--- + +## Шаг 4 – Выполнить конвертацию – Конвертировать Word Math в LaTeX + +После настройки всё готово, и сама конвертация занимает одну строку. Aspose.Words делает всю тяжёлую работу «за кулисами». + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Ожидаемый результат**: Откройте сгенерированный файл `.md`, и вы увидите примерно следующее: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Обратите внимание на блоки LaTeX (`$...$` и `$$...$$`), заменяющие прежние PNG‑фрагменты. Изображение внизу остаётся PNG, отрендеренным с 300 DPI, как мы и задали. + +--- + +## Шаг 5 – Распространённые граничные случаи и их решение + +| Ситуация | Что происходит | Как исправить | +|-----------|----------------|----------------| +| **Отсутствующие шрифты** (например, Cambria Math не установлен) | Вывод LaTeX может содержать неизвестные символы. | Установите недостающий шрифт на сервере или внедрите его в документ перед конвертацией. | +| **Сложные уравнения** (матрица с пользовательскими разделителями) | Aspose.Words может переключиться на изображение, несмотря на режим `LaTeX`. | Обновите до последней версии Aspose.Words; библиотека постоянно улучшает поддержку уравнений. | +| **Большие документы** ( > 50 МБ ) | Нагрузка на память может вызвать `OutOfMemoryException`. | Используйте `LoadOptions` с `LoadFormat.Docx` и потоковую передачу файла, либо разбейте документ на секции перед конвертацией. | +| **Слишком большой размер изображения** | Файл Markdown становится огромным, замедляя сборку статического сайта. | Уменьшите `ImageResolution` до 150 DPI для сценариев только веб (см. Шаг 3). | + +--- + +## Шаг 6 – Соберите всё вместе: полностью рабочий пример + +Ниже представлен *полный* консольный пример, который можно скопировать в `Program.cs`. Он включает все обсуждённые детали и небольшую обработку ошибок. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Запустите программу (`dotnet run`), и вы получите markdown‑файл, который **сохраняет docx как markdown**, при этом каждая формула сохраняется в виде LaTeX. Никакого ручного копирования, никаких некрасивых растровых изображений для формул. + +--- + +## Заключение + +Мы прошли весь процесс **сохранения docx как markdown** с помощью Aspose.Words, от загрузки Word‑файла до настройки **экспорта формул в latex** и **установки разрешения изображений в markdown**. Финальный фрагмент готов к продакшену, и его можно внедрить в любой .NET‑проект, которому требуется **конвертировать word в markdown** «на лету». + +Что дальше? Попробуйте передать полученный `.md` в генератор статических сайтов, такой как Hugo или Jekyll, и наблюдайте, как ваши формулы красиво рендерятся. Если нужно **конвертировать word math latex** в другие форматы (PDF, HTML), просто замените `MarkdownSaveOptions` на `PdfSaveOptions` или `HtmlSaveOptions` — тот же флаг `OfficeMathExportMode` работает и там. + +Есть особый сценарий, например загрузка Word‑файлов из Azure Blob Storage или потоковая передача их из API? Тот же шаблон применим; просто замените конструктор `Document`, работающий с файловой системой, на вариант, принимающий поток. + +Экспериментируйте, делитесь результатами в комментариях — расскажите, как этот подход избавил вас от проблем с конвертацией. Приятного кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/russian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..3e86ce4661 --- /dev/null +++ b/words/russian/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-05-01 +description: Загружайте изображения в облако при конвертации документа Word в markdown. + Узнайте, как извлекать изображения из docx и сохранять их в Azure Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: ru +og_description: Загружайте изображения в облако при конвертации документа Word в markdown. + Это руководство показывает, как извлечь изображения из docx и сохранить их в Azure + Blob Storage. +og_title: Загружать изображения в облако при конвертации Word в Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Загрузка изображений в облако при конвертации Word в Markdown +url: /ru/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Загрузка изображений в облако при конвертации Word в Markdown + +Когда‑нибудь нужно было **загрузить изображения в облако** при преобразовании файла Word в markdown? Вы не одиноки — разработчики постоянно балансируют между конвертацией документов и управлением ресурсами, а объединить оба процесса в едином плавном потоке бывает как попытка поймать движущийся объект. + +Хорошие новости? С помощью Aspose.Words можно извлечь каждую картинку, диаграмму или схему из .docx, сразу отправить её в Azure Blob Storage и позволить сгенерированному markdown ссылаться на эти облачные URL вместо локальных файлов. В этом руководстве мы пройдём весь процесс от загрузки исходного документа до получения чистого markdown‑файла, указывающего на ваш Azure‑бакет. + +К концу этого руководства вы сможете **конвертировать docx в markdown**, **извлекать изображения из docx** и **сохранять изображения в Azure Blob** — всё это несколькими строками C#. Никаких внешних инструментов, ручного копирования‑вставки и, конечно, никаких битых ссылок на изображения. + +## Что понадобится + +- **.NET 6.0** или новее (код работает и на .NET Core, и на .NET Framework) +- **Aspose.Words for .NET** (NuGet‑пакет `Aspose.Words`) +- Учётная запись **Azure Storage** с контейнером (например, `images`) и общим ключом доступа — понадобится строка подключения для загрузки файлов. +- Базовое понимание C# и async/await (необязательно, но полезно). + +Если всё уже готово — отлично, сразу переходим к решению. Если нет, раздел «Prerequisites» в конце подскажет быстрые шаги по настройке. + +## Шаг 1: Создание помощника Azure Blob (Зачем это нужно) + +Прежде чем трогать документ Word, нам нужен небольшой помощник, умеющий отправлять массив байтов в Azure Blob Storage и возвращать публичный URL. Такая абстракция сохраняет чистоту логики конвертации и упрощает замену провайдера хранилища в будущем. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Зачем нужен этот помощник?** +1. **Разделение ответственности** — код конвертации markdown остаётся сосредоточенным на работе с документом, а не на деталях HTTP. +2. **Повторное использование** — `UploadAsync` можно вызвать из любой части приложения (например, для пользовательских загрузок). +3. **Подготовка к будущему** — переход на Amazon S3 или Google Cloud Storage потребует лишь новой реализации того же интерфейса. + +> **Pro tip:** Установите уровень доступа контейнера в `Blob` (публичный) только если вас устраивает, что любой может просматривать изображения. Для приватных сценариев генерируйте SAS‑токены для каждой загрузки и используйте их URL. + +## Шаг 2: Определение обратного вызова сохранения ресурса (Суть загрузки‑во‑время‑конвертации) + +Aspose.Words позволяет перехватывать каждый ресурс (изображение, диаграмму и т.д.), который обычно записывался бы на диск при сохранении документа в markdown. Предоставив `ResourceSavingCallback`, мы можем загрузить каждый ресурс в Azure Blob и заменить локальное имя файла облачным URL. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Что происходит?** + +- **Extract** — Aspose.Words предоставляет поток для каждой картинки. +- **Upload** — Мы передаём этот поток в `AzureBlobUploader`. +- **Replace** — Писатель markdown получает публичный URL и вставляет его в синтаксис изображения markdown (`![](https://…)`). + +Поскольку мы устанавливаем `args.AlreadyExists = true`, временные файлы не захламляют файловую систему — чистая, безсостояния операция, идеальная для серверлесс‑функций. + +## Шаг 3: Настройка параметров сохранения Markdown (Связываем всё вместе) + +Теперь внедряем обратный вызов в `MarkdownSaveOptions` Aspose.Words. Важные флаги: `ExportImagesAsBase64 = false` (чтобы получать внешние ссылки) и `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Почему отключаем Base64?** +Когда `ExportImagesAsBase64` включён, Aspose встраивает каждую картинку прямо в markdown как data URI. Это противоречит цели **upload images to cloud**, потому что файл markdown разрастается, а изображения скрыты от CDN. Отключив эту опцию, мы получаем чистые внешние ссылки, указывающие на Azure Blob — именно то, что ожидает современный генератор статических сайтов. + +## Шаг 4: Собираем всё вместе — минимальное консольное приложение + +Ниже полностью готовая к запуску консольная программа. Замените заполнители на вашу реальную строку подключения Azure и имя контейнера. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Ожидаемый вывод + +Запуск программы с `sample.docx`, содержащим две картинки, даст: + +- `output.md` с синтаксисом изображений markdown, например: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-pdfsaveoptions/_index.md b/words/russian/net/programming-with-pdfsaveoptions/_index.md index e8a00d3d0b..de09d26360 100644 --- a/words/russian/net/programming-with-pdfsaveoptions/_index.md +++ b/words/russian/net/programming-with-pdfsaveoptions/_index.md @@ -46,12 +46,12 @@ | [Визуализация 3D DML 3DEffects в PDF-документе](./dml-3deffects-rendering/) | Узнайте, как визуализировать потрясающие 3D-эффекты DML в документах PDF с помощью Aspose.Words для .NET с этим подробным пошаговым руководством. | | [Интерполяция изображений в PDF-документе](./interpolate-images/) | Узнайте, как интерполировать изображения в PDF-документе с помощью Aspose.Words для .NET с нашим пошаговым руководством. Улучшите качество изображений в PDF-файле легко. | | [Сохранить DOCX в PDF с Aspose.Words – Полное руководство на C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Полное руководство на C# по сохранению DOCX в PDF с помощью Aspose.Words. | +| [Сохранить документ как PDF с Aspose.Words – Полное руководство на C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Полное руководство на C# по сохранению документа в PDF с помощью Aspose.Words. | | [Создать доступный PDF из Word с помощью C# – пошаговое руководство](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Узнайте, как создать доступный PDF из документа Word с помощью C# и Aspose.Words, следуя подробному пошаговому руководству. | | [Обновить последнее напечатанное свойство в документе PDF](./update-last-printed-property/) | Узнайте, как обновить последнее напечатанное свойство в документе PDF с помощью Aspose.Words для .NET с нашим пошаговым руководством. | | [Визуализация 3D DML 3DEffects в PDF-документе](./dml-3deffects-rendering/) | Узнайте, как визуализировать потрясающие 3D-эффекты DML в документах PDF с помощью Aspose.Words для .NET с этим подробным пошаговым руководством. | | [Интерполяция изображений в PDF-документе](./interpolate-images/) | Узнайте, как интерполировать изображения в PDF-документе с помощью Aspose.Words для .NET с нашим пошаговым руководством. Улучшите качество изображений в PDF-файле легко. | | [Создание доступного PDF в C# – Руководство по доступности PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Узнайте, как создавать PDF с поддержкой доступности, используя Aspose.Words для .NET и C#. | - | [Интерполяция изображений в PDF-документе](./interpolate-images/) | Узнайте, как интерполировать изображения в PDF-документе с помощью Aspose.Words для .NET с помощью нашего пошагового руководства. Улучшите качество изображений в PDF-файле легко. | | [Создание доступного PDF из Word – Полное руководство](./create-accessible-pdf-from-word-complete-guide/) | Узнайте, как создать доступный PDF из документа Word, соблюдая стандарты доступности, с помощью Aspose.Words для .NET. | | [Визуализация 3D DML 3DEffects в PDF-документе](./dml-3deffects-rendering/) | Узнайте, как визуализировать потрясающие 3D-эффекты DML в документах PDF с помощью Aspose.Words для .NET с помощью этого подробного пошагового руководства. | diff --git a/words/russian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/russian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..68ba5a1072 --- /dev/null +++ b/words/russian/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,257 @@ +--- +category: general +date: 2026-05-01 +description: Узнайте, как сохранять документ в формате PDF с помощью Aspose.Words + в C#. В руководстве также рассматривается преобразование Word в PDF, экспорт математических + формул в LaTeX и обработка отсутствующих шрифтов. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: ru +og_description: Сохраняйте документ в PDF без усилий с Aspose.Words. Это руководство + также показывает, как конвертировать Word в PDF, экспортировать математические формулы + в LaTeX и работать с отсутствующими шрифтами. +og_title: Сохранить документ в PDF с помощью Aspose.Words – Полное руководство по + C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Сохранение документа в PDF с помощью Aspose.Words – Полное руководство по C# +url: /ru/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Сохранить документ как PDF с помощью Aspose.Words – Полное руководство на C# + +Когда‑то задумывались **как сохранить документ как pdf** напрямую из файла Word, не теряя возможностей доступности? Вы не одиноки — разработчики постоянно ищут надёжный способ конвертировать Word в PDF, сохраняя математические уравнения и корректно обрабатывая отсутствующие шрифты. + +В этом руководстве мы пошагово пройдём решение, которое не только **сохраняет документ как pdf**, но и демонстрирует **конвертировать word в pdf**, **экспортировать math latex** и **обрабатывать отсутствующие шрифты** с использованием последней версии Aspose.Words для .NET. К концу вы получите готовую к запуску программу на C#, которая создаёт файлы, соответствующие PDF/UA‑2, идеально подходящие для аудитов доступности. + +## Что понадобится + +- .NET 6 или новее (код работает также с .NET Core и .NET Framework) +- Aspose.Words для .NET 25.10 или новее — получите бесплатную пробную версию на сайте Aspose +- Небольшой документ Word (`input.docx`), содержащий хотя бы одну плавающую форму и математическое уравнение (чтобы увидеть работу функции **export‑math‑latex**) +- Visual Studio 2022 (или любая другая IDE) + +> **Совет:** Если вы работаете в CI/CD‑конвейере, добавьте пакет Aspose.Words NuGet в файл проекта: + +```xml + +``` + +Теперь перейдём к коду. + +## Шаг 1: Загрузка исходного документа с автоматическим восстановлением + +При работе с реальными файлами Word вы можете столкнуться с повреждёнными разделами или отсутствующими ресурсами. Включение автоматического восстановления гарантирует, что процесс загрузки никогда не бросит исключение. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Почему это важно:** +`RecoveryMode.AutoRecover` защищает ваш конвейер от падения при некорректных входных данных, что особенно удобно, когда вы **конвертируете word в pdf** массово. + +## Шаг 2: Настройка параметров сохранения PDF для полной доступности + +PDF/UA‑2 — это ISO‑стандарт для доступных PDF‑файлов. Настроив несколько флагов, мы получаем документ, который могут навигировать скрин‑ридеры, и при этом гарантируем экспорт уравнений как скрытого LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Ключевые моменты:** + +- **ExportFloatingShapesAsInlineTag** — обеспечивает сохранение оригинального макета PDF при сохранении семантической корректности. +- **OfficeMathExportMode.LaTeX** — удовлетворяет требование **export math latex**, позволяя downstream‑инструментам извлекать уравнения при необходимости. + +## Шаг 3: Захват предупреждений (например, отсутствующие шрифты) + +Отсутствующие шрифты часто становятся проблемой при конвертации документов. Aspose.Words может сообщать об этих проблемах через `WarningCallback`. Мы соберём их, чтобы вы могли позже записать в лог или обработать. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Зачем это нужно:** +Если исходный документ использует шрифт, который не установлен на сервере, PDF переключится на шрифт по умолчанию, что может нарушить макет. **Обрабатывая отсутствующие шрифты**, мы можем предупредить пользователя или встроить замену. + +## Шаг 4: Сохранение документа как доступный PDF + +Настал момент истины — непосредственно выполнение конвертации. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Если всё прошло гладко, вы получите файл PDF/UA‑2, содержащий скрытый LaTeX для каждого уравнения и корректную разметку плавающих форм. + +## Шаг 5: Просмотр захваченных предупреждений (по желанию, но рекомендуется) + +После операции сохранения вы можете пройтись по собранным предупреждениям и вывести их в лог. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Типичный вывод может выглядеть так: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Получение этих сообщений заранее помогает **обрабатывать отсутствующие шрифты**, прежде чем они повлияют на конечных пользователей. + +## Полный рабочий пример + +Объединив всё вместе, получаем полностью готовую к запуску программу. Замените шаблонные пути на свои. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Ожидаемый результат:** +- `output.pdf` соответствует PDF/UA‑2. +- Все плавающие формы размечены как встроенные изображения. +- Каждый объект Office Math экспортируется как скрытый LaTeX (видимый при инспекции структуры PDF). +- Любые проблемы со шрифтами выводятся в консоль, давая возможность **обрабатывать отсутствующие шрифты** до публикации файла. + +![Диаграмма, показывающая поток от Word → Aspose.Words → Доступный PDF (сохранить документ как pdf)](conversion-diagram.png "Схема потока для сохранения документа как pdf") + +*Текст alt изображения:* **Диаграмма того, как сохранить документ как pdf с помощью Aspose.Words** + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если я использую более старую версию Aspose.Words? + +Флаг `OfficeMathExportMode.LaTeX` появился в версии 25.10. В более ранних релизах вы всё ещё можете **конвертировать word в pdf**, но математика будет растрирована вместо экспорта в LaTeX. Обновитесь для лучшей доступности. + +### Можно ли встроить пользовательские шрифты, чтобы избежать отката? + +Да. Установите `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` перед вызовом `Save`. Это также помогает **обрабатывать отсутствующие шрифты**, принудительно встраивая необходимые глифы в PDF. + +### Как проверить соответствие PDF/UA‑2? + +Откройте файл в Adobe Acrobat Pro → «Print Production» → «Preflight». Выберите профиль «PDF/A‑2b» или «PDF/UA‑2»; Acrobat покажет любые нарушения. + +### Что делать с защищёнными паролем файлами Word? + +Загружайте документ с `LoadOptions`, включающим `Password`. Пример: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Остальная часть конвейера остаётся без изменений. + +## Заключение + +Мы рассмотрели всё, что нужно для **сохранения документа как pdf** с помощью Aspose.Words на C#. Руководство также показало, как **конвертировать word в pdf**, **экспортировать math latex** и **обрабатывать отсутствующие шрифты** — всё это при создании доступного PDF/UA‑2. + +Запустите код, поэкспериментируйте с различными `PdfSaveOptions` (например, сжатие изображений, PDF/A‑2b) и интегрируйте его в ваш сервис обработки документов. Если нужно пойти дальше, изучите библиотеку Aspose для работы с PDF — постобработка, цифровые подписи и т.д. + +Есть сценарии, которые хотите решить? Оставляйте комментарии или смотрите наши другие руководства по **манипуляции PDF**, **извлечению изображений** и **массовой конвертации**. Приятного кодинга! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-shapes/_index.md b/words/russian/net/programming-with-shapes/_index.md index 58a19ffdb4..67cedb7e73 100644 --- a/words/russian/net/programming-with-shapes/_index.md +++ b/words/russian/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ | [Создать прямоугольную форму в Word с помощью C# – пошаговое руководство](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Узнайте, как создать прямоугольную форму в документе Word с помощью C# в этом пошаговом руководстве. | | [Учебник по теням фигур Aspose.Words – Добавление тени к фигуре Word в C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Узнайте, как добавить тень к фигурам в документах Word с помощью Aspose.Words для .NET в этом пошаговом руководстве. | | [Создать пустой документ Word с фигурой прямоугольника с тенью – пошаговое руководство](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Узнайте, как создать пустой документ Word и добавить в него прямоугольную фигуру с теневым эффектом с помощью Aspose.Words для .NET. | +| [Как переместить тень в Aspose.Words – Полное руководство на C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Узнайте, как переместить тень фигуры в документах Word с помощью Aspose.Words для .NET в этом полном руководстве на C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/russian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..841f0cece1 --- /dev/null +++ b/words/russian/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Как переместить тень у фигуры в Aspose.Words с использованием C#. Узнайте, + как добавить тень к фигуре, изменить размытие, установить прозрачность и повернуть + тень за несколько минут. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: ru +og_description: Как переместить тень на фигуре в Aspose.Words с использованием C#. + Этот учебник показывает, как добавить тень к фигуре, изменить размытие, установить + прозрачность и повернуть тень. +og_title: Как переместить тень в Aspose.Words – Полное руководство по C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Как переместить тень в Aspose.Words – Полное руководство по C# +url: /ru/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как переместить тень в Aspose.Words – Полное руководство на C# + +Когда‑нибудь задавались вопросом **как переместить тень** у фигуры в документе Word, не открывая Word вручную? В своей повседневной работе я часто нуждался в программном изменении тени фигуры — будь то для отшлифованного отчёта или динамического шаблона. Хорошая новость: с Aspose.Words это можно сделать в паре строк кода, а также вы узнаете, как **добавить тень к фигуре**, **изменить размытие**, **установить прозрачность** и **повернуть тень** за один проход. + +В этом руководстве мы пройдём реальный сценарий: загрузим существующий DOCX, в котором уже есть фигура, настроим позицию тени, её мягкость, непрозрачность и направление, а затем сохраним результат. К концу вы получите переиспользуемый фрагмент, который можно вставить в любой .NET‑проект, и поймёте, зачем нужна каждая настройка. + +## Предварительные требования – Что нужно перед началом + +- **Aspose.Words for .NET** (версия 23.12 или новее). Установить можно через NuGet командой `Install-Package Aspose.Words`. +- Среда разработки .NET 6+ (Visual Studio, VS Code, Rider — что вам удобно). +- Входной Word‑файл (`input.docx`), уже содержащий хотя бы одну фигуру (прямоугольник, круг или изображение). +- Базовое знакомство с синтаксисом C# — ничего сложного. + +Если чего‑то не хватает, сделайте паузу и установите библиотеку; дальше в руководстве предполагается, что пакет уже подключён. + +## Шаг 1: Загрузка документа и получение целевой фигуры – **Как переместить тень** начинается здесь + +Первым делом загружаем исходный документ и находим фигуру, которую будем менять. Aspose.Words рассматривает каждый объект (абзацы, таблицы, фигуры) как узел дерева, поэтому его можно запросить напрямую. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Почему это важно:** Загрузка документа один раз и повторное использование того же экземпляра `Document` экономит ресурсы. Вызов `GetChild` безопасен, так как возвращает `null`, если индекс выходит за пределы, позволяя корректно обрабатывать отсутствие фигур. + +## Шаг 2: Регулировка радиуса размытия – Мастер‑класс **Как изменить размытие** + +Мягкая тень выглядит профессионально, а резкий край — дешево. Свойство `BlurRadius` управляет мягкостью в пунктах (1 pt ≈ 1/72 дюйма). Увеличим его до 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Совет профи:** Значение размытия по умолчанию — 0,5 pt. Всё, что выше 5 pt, обычно заметно, но будьте осторожны: слишком большое значение может оторвать фигуру от страницы. + +## Шаг 3: Установка прозрачности – Ответ на **Как установить прозрачность** + +Прозрачность определяет, насколько «прозрачна» тень. Значение `0` — полностью непрозрачная; `1` — полностью невидимая. Для нежного эффекта используем `0.3` (30 % прозрачности). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Зачем это может понадобиться:** Если фигура тёмная, полностью непрозрачная тень может «заглушить» подлежащий текст. Регулировка прозрачности сохраняет читаемость документа, добавляя глубину. + +## Шаг 4: Перемещение тени – Ядро **Как переместить тень** + +Свойство `Distance` задаёт, насколько далеко тень смещена от фигуры, измеряется в пунктах. Большое расстояние отодвигает тень дальше, создавая более драматичный эффект. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **А если нужен крошечный сдвиг?** Установка `Distance` в `0` разместит тень непосредственно за фигурой, что удобно для эффекта тиснения. + +## Шаг 5: Поворот источника света – Решаем **Как повернуть тень** + +Тени не всегда падают строго вниз; они следуют углу источника света. Свойство `Angle` (в градусах) вращает тень вокруг фигуры. Повернём её на 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Быстрый эксперимент:** Попробуйте `90` для тени справа или `-30` для тени, наклонённой влево. Визуальное изменение будет мгновенным. + +## Шаг 6: Сохранение документа – Видим результат **Добавить тень к фигуре** + +После настройки тени запишем документ обратно на диск. Можно перезаписать оригинал или создать новый файл; в примере используется новый выходной файл. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Ожидаемый результат:** Откройте `output.docx`. Тень фигуры станет мягче, слегка смещённой, полупрозрачной и наклонённой на 45°. Сравнив её бок о бок с `input.docx`, разницу будет невозможно не заметить. + +### Полный рабочий пример (готов к копированию) + +Ниже представлен весь код в одном блоке. Вставьте его в новый консольный проект, замените `YOUR_DIRECTORY` реальным путём к папке и запустите. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если в документе несколько фигур? + +Можно пройтись по всем фигурам в цикле: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Можно ли добавить тень к фигуре, у которой её нет? + +Конечно. Объект `ShadowFormat` всегда существует; нужно лишь включить его: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Работает ли это с изображениями и SmartArt? + +Да. Любой узел, наследующий `Shape` — включая картинки, диаграммы и SmartArt — имеет `ShadowFormat`. Те же свойства применимы. + +### Как управлять цветом тени? + +Используйте свойство `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Проблемы совместимости? + +Aspose.Words 23.12+ поддерживает .NET 6, .NET Core 3.1 и .NET Framework 4.6.2+. Показанный API стабилен во всех этих версиях. + +## Заключение + +Мы только что разобрали, **как переместить тень** у фигуры с помощью Aspose.Words, а также продемонстрировали **добавление тени к фигуре**, **изменение размытия**, **установку прозрачности** и **поворот тени**. Полный, готовый к запуску пример позволяет за секунды настроить любую тень, придавая вашим документам отполированный, профессиональный вид без открытия Word. + +Готовы к следующему шагу? Попробуйте комбинировать эти настройки тени с **условным форматированием** — например, применять более глубокую тень только к заголовкам или к диаграммам, превышающим определённый размер. Или исследуйте **градиентные заливки** самой фигуры, чтобы создать действительно бросающийся в глаза дизайн. + +Если возникнут трудности, оставляйте комментарий ниже. Приятного кодинга, и пусть ваши тени всегда падают именно туда, куда вы хотите! + +![Диаграмма, показывающая эффект перемещения тени у фигуры – пример как переместить тень](https://example.com/images/shadow-demo.png "пример как переместить тень") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/basic-conversions/_index.md b/words/spanish/net/basic-conversions/_index.md index 46bb7707c2..55d16f72b7 100644 --- a/words/spanish/net/basic-conversions/_index.md +++ b/words/spanish/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Conversiones Básicas te guía a través de las conversiones básicas de documen | [Cómo exportar LaTeX desde Word – Guía paso a paso](./how-to-export-latex-from-word-step-by-step-guide/) Aprenda a exportar contenido LaTeX desde Word usando Aspose.Words para .NET con esta guía paso a paso. | [Convertir Word a PDF en C# usando Aspose.Words – Guía](./convert-word-to-pdf-in-c-using-aspose-words-guide/) Aprenda a convertir documentos Word a PDF en C# con Aspose.Words. Guía paso a paso con ejemplos de código. | [Guardar Word como PDF con Aspose.Words – Guía completa en C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) Aprenda a guardar documentos Word como PDF usando Aspose.Words en C#. Guía paso a paso con ejemplos de código. | +| [Guardar Word como PDF con Aspose.Words – Guía completa](./save-word-as-pdf-with-aspose-words-complete-guide/) Aprenda a guardar documentos Word como PDF usando Aspose.Words. Guía completa paso a paso con ejemplos de código. | | [Guardar Docx como PDF con Aspose.Words – Guía completa en C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) Aprenda a guardar documentos Docx como PDF usando Aspose.Words en C#. Guía paso a paso con ejemplos de código. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/spanish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 1b044039d8..174bf3cb14 100644 --- a/words/spanish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/spanish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,23 +1,22 @@ --- category: general -date: 2025-12-29 -description: Cómo exportar LaTeX desde Word usando Aspose.Words – aprende a convertir - Word a LaTeX, guardar docx como txt y manejar ecuaciones en texto plano. +date: 2026-05-01 +description: Aprende a exportar LaTeX desde un archivo Word, convertir Word a txt + y conservar las tablas usando Aspose.Words en C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: es -og_description: Cómo exportar LaTeX desde Word con Aspose.Words. Esta guía muestra - cómo convertir Word a LaTeX, guardar docx como txt y mantener las ecuaciones intactas. -og_title: Cómo exportar LaTeX desde Word – Tutorial rápido de C# +og_description: Descubre cómo exportar LaTeX desde Word, convertir Word a texto plano + y mantener el diseño de la tabla intacto con Aspose.Words. +og_title: Cómo exportar LaTeX desde Word – Tutorial completo de C# tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Cómo exportar LaTeX desde Word – Guía paso a paso url: /es/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -27,163 +26,213 @@ url: /es/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Cómo exportar LaTeX desde Word – Guía paso a paso +# Cómo exportar LaTeX desde Word – Tutorial completo en C# -¿Alguna vez te has preguntado **cómo exportar LaTeX desde Word** sin perder esas complicadas ecuaciones de Office Math? No eres el único. Muchos desarrolladores se topan con un obstáculo cuando intentan *convertir Word a LaTeX* para artículos académicos, informes científicos o flujos de publicación automatizados. +¿Alguna vez te has preguntado **cómo exportar LaTeX** desde un documento Word sin perder ninguna de las ecuaciones matemáticas? No estás solo. Muchos desarrolladores necesitan convertir un .docx que contiene Office Math en LaTeX limpio y, además, **convertir Word a txt** para el procesamiento posterior. En esta guía recorreremos una solución práctica y lista para ejecutar que **preserva tablas**, te brinda un archivo de texto plano y mantiene el marcado LaTeX exactamente donde lo necesitas. -En este tutorial recorreremos un ejemplo completo y listo‑para‑ejecutar en C# que muestra **cómo exportar LaTeX** usando Aspose.Words, explica **cómo guardar archivos txt** con marcado LaTeX, y también cubre los matices de **convertir ecuaciones de Word a LaTeX** para que nada se pierda en la traducción. +Cubriremos todo, desde cargar el archivo fuente hasta ajustar `TxtSaveOptions` para que la salida sea tanto legible por humanos como amigable para máquinas. Al final podrás **guardar docx como txt**, **convertir Word a texto plano**, y saber **cómo preservar tablas** durante la exportación. Sin scripts externos, sin copiar‑pegar manual—solo código puro en C# que puedes incorporar a cualquier proyecto .NET. -> **Consejo profesional:** El mismo enfoque funciona para cualquier .docx que tengas—simplemente apunta el código a una ruta de archivo diferente. +## Qué necesitarás ---- - -## Lo que necesitarás - -Antes de sumergirnos, asegúrate de contar con los siguientes requisitos: - -| Prerequisite | Why it matters | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words está dirigido a runtimes .NET modernos. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | La biblioteca realiza el trabajo pesado de analizar Word y generar LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Para ver la conversión a LaTeX en acción. | -| **Visual Studio 2022** (or any IDE you like) | Facilita la depuración y ejecución del ejemplo. | - -Si aún no has instalado el paquete NuGet, ejecuta: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (última versión, 2024.x o posterior). El paquete NuGet es `Aspose.Words`. +- Un entorno de desarrollo .NET (Visual Studio, VS Code, Rider—cualquiera sirve). +- Un archivo Word (`.docx`) que contenga ecuaciones Office Math y al menos una tabla (para que podamos ver la magia de preservación de tablas). -Eso es todo—sin DLLs adicionales, sin interop COM, solo una biblioteca gestionada limpia. +Eso es todo. Si ya los tienes, sigue leyendo; de lo contrario, obtén el paquete NuGet y un DOCX de ejemplo antes de profundizar. -## Cómo exportar LaTeX desde Word – Visión general - -A continuación se muestra la visión general de lo que lograremos: +--- -1. **Cargar** el documento Word fuente (`.docx`). -2. **Configurar** `TxtSaveOptions` para que cualquier objeto Office Math se emita como código LaTeX. -3. **Guardar** el documento como un archivo de texto plano (`.txt`) que puedes alimentar directamente a cualquier compilador LaTeX. +## Cómo exportar LaTeX desde un documento Word -![Ejemplo de cómo exportar LaTeX desde Word](image.png "Cómo exportar LaTeX desde Word") +A continuación está el núcleo del tutorial—tres pasos concisos que responden a la pregunta **cómo exportar latex** mientras también manejan los objetivos secundarios de **convertir word a txt**, **convertir word a texto plano**, **guardar docx como txt**, y **cómo preservar tablas**. -## Paso 1: Cargar el documento Word +### Paso 1: Cargar el archivo DOCX -Primero lo primero—abre el .docx que deseas convertir. La clase `Document` abstrae todo el XML subyacente, proporcionándote un modelo de objetos amigable. +Primero necesitamos leer el documento Word en un objeto `Aspose.Words.Document`. Este paso es el mismo ya sea que luego **conviertas word a txt** o **guarda docx como txt**. ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**Por qué es importante:** +> **Por qué es importante:** Cargar el archivo crea una representación en memoria de todos los elementos de Word—párrafos, tablas y objetos Office Math. Sin este objeto no puedes manipular las opciones de exportación. -Cargar el archivo al principio nos permite inspeccionar su contenido (p.ej., contar ecuaciones) antes de decidir cómo serializarlo. Si el archivo está corrupto, `Document` lanzará una excepción clara, ahorrándote resultados misteriosos más adelante. +### Paso 2: Configurar `TxtSaveOptions` para LaTeX y diseño de tabla -## Paso 2: Configurar TxtSaveOptions para la exportación a LaTeX +La clase `TxtSaveOptions` te permite controlar exactamente cómo se genera el archivo de texto plano. Dos propiedades son clave para nuestro escenario: -La magia ocurre en `TxtSaveOptions`. Al establecer `OfficeMathExportMode` a `LaTeX`, cada objeto Office Math se transforma en su representación LaTeX correspondiente. +| Propiedad | Qué hace | Por qué lo necesitas | +|-----------|----------|----------------------| +| `OfficeMathExportMode` | Determina cómo se renderiza Office Math. Configurarlo a `LaTeX` convierte las ecuaciones a sintaxis LaTeX. | Esto es el núcleo de **cómo exportar latex**. | +| `PreserveTableLayout` | Cuando es `true`, Aspose agrega espacios en blanco para que las tablas mantengan una apariencia tipo cuadrícula. | Esto satisface **cómo preservar tablas** mientras **conviertes word a txt**. | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**Por qué elegimos estas configuraciones:** +> **Consejo profesional:** Si solo necesitas el LaTeX sin formato de tabla, establece `PreserveTableLayout` en `false`. El archivo será más pequeño, pero perderás la pista visual de la tabla. -- `OfficeMathExportMode.LaTeX` es el único modo que garantiza una traducción matemática fiel. -- `PreserveTableLayout` mantiene las tablas con el mismo aspecto que en Word, lo cual es útil cuando luego incrustas la salida en un entorno LaTeX `tabular`. -- UTF‑8 asegura que caracteres como “α”, “β” o “∑” sobrevivan al proceso de ida y vuelta. +### Paso 3: Guardar el documento como texto plano -Si alguna vez necesitas **convertir Word a LaTeX** sin el contenedor de texto plano, podrías cambiar a `SaveFormat.LaTeX`—solo un consejo rápido para escenarios avanzados. +Ahora escribimos el documento a un archivo `.txt` usando las opciones que acabamos de definir. Esta única línea logra **convertir word a texto plano**, **guardar docx como txt**, y, por supuesto, **cómo exportar latex** de una sola vez. -## Paso 3: Guardar el documento como archivo de texto +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -Ahora escribimos el texto con contenido LaTeX en el disco. El `.txt` resultante puede renombrarse a `.tex` más tarde, o enviarse directamente a un compilador LaTeX. +doc.Save(outputPath, saveOptions); +``` -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +Después de que la llamada finalice, abre `output.txt`. Verás: -// Save using the configured options -doc.Save(outputPath, txtOptions); +- Fragmentos de LaTeX como `\frac{a}{b}` para cada ecuación Office Math. +- Tablas renderizadas con los caracteres `|` y `-`, preservando la alineación de columnas. +- Párrafos normales como texto plano, listos para cualquier analizador posterior. -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +### Ejemplo completo funcional + +Juntando todo, aquí tienes un programa autocontenido que puedes compilar y ejecutar hoy: + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Lo que verás en `output.txt`:** +**Salida esperada** (extracto): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -Todos los demás párrafos aparecen como texto plano, mientras que cualquier ecuación Office Math se envuelve en un entorno LaTeX `equation` (o `inline` si estaba en línea en Word). Esto satisface perfectamente el requisito de **convertir ecuaciones de Word a LaTeX**. +Observa cómo la tabla mantiene su cuadrícula y la ecuación aparece como LaTeX limpio. Ese es el punto óptimo cuando **conviertes word a txt** y aún necesitas una representación fiel tanto de la estructura como de las matemáticas. -## Casos límite y preguntas frecuentes +--- -| Situation | What to do | -|-----------|------------| -| **No equations in the source** | La conversión sigue funcionando; simplemente obtendrás texto plano. No se agrega código LaTeX adicional. | -| **Very large documents (>100 MB)** | Considera transmitir la salida usando `MemoryStream` para evitar un alto consumo de memoria. | -| **Unsupported Math constructs** | Aspose.Words cubre el 99 % de Office Math. Para el raro caso límite, puede que necesites post‑procesar el LaTeX manualmente. | -| **Need a .tex file instead of .txt** | Cambia `outputPath` para que termine en `.tex` y opcionalmente establece `txtOptions.Encoding` a `Encoding.UTF8`. | -| **Running on Linux/macOS** | El mismo código funciona—solo asegúrate de que las rutas de archivo usen barras diagonales hacia adelante o `Path.Combine`. | +## Consejos para convertir Word a TXT y preservar tablas -## Cómo guardar TXT con ecuaciones LaTeX – Resumen rápido +Aunque el enfoque de tres pasos funciona para la mayoría de los casos, los proyectos del mundo real a menudo presentan desafíos. A continuación hay sugerencias prácticas que hacen que tu canal **convertir word a texto plano** sea robusto. -1. **Cargar** el .docx (`Document`). -2. **Establecer** `OfficeMathExportMode = LaTeX` en `TxtSaveOptions`. -3. **Guardar** el archivo (`doc.Save`) con esas opciones. +### Usa una codificación consistente -Ese es todo el flujo de trabajo para **cómo guardar archivos txt** que contienen ecuaciones formateadas en LaTeX. +`TxtSaveOptions` usa UTF‑8 por defecto, lo que maneja la mayoría de los caracteres. Si necesitas una página de códigos diferente (p. ej., sistemas heredados que esperan Windows‑1252), establece la propiedad `Encoding`: -## Bonus: Automatizando la conversión para varios archivos +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` + +### Recortar espacios en blanco excesivos -Si tienes una carpeta llena de documentos Word, envuelve la lógica anterior en un bucle simple: +Las tablas con muchas columnas pueden generar líneas largas. Después de guardar, podrías querer post‑procesar el archivo para colapsar múltiples espacios en una sola tabulación: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### Manejar tablas anidadas + +Si tu DOCX contiene tablas dentro de tablas, `PreserveTableLayout` seguirá manteniendo la jerarquía visual, pero la sangría puede verse extraña. Una solución rápida es reemplazar los espacios iniciales con un marcador personalizado (p. ej., `>>`) para que los analizadores posteriores puedan detectar los niveles de anidamiento. + +### Procesamiento por lotes de varios archivos - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +Cuando necesites **convertir word a txt** para decenas de documentos, envuelve la lógica en un bucle: + +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -Ahora puedes **convertir Word a LaTeX** en bloque—perfecto para grupos de investigación que reciben decenas de manuscritos diariamente. +De esa manera puedes **guardar docx como txt** en masa sin intervención manual. + +--- + +## Errores comunes y cómo evitarlos + +1. **Modo de exportación LaTeX ausente** – Si olvidas establecer `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, las ecuaciones volverán a texto plano (p. ej., “Equation 1”). Siempre verifica el bloque de opciones. +2. **Se pierde el diseño de tabla** – Establecer `PreserveTableLayout` en `false` es el valor predeterminado. Si tu salida parece una pared de texto, probablemente no activaste la bandera. +3. **Rutas de archivo con espacios** – Usar cadenas crudas (`@"C:\My Folder\input.docx"`) evita problemas de escape. De lo contrario obtendrás una `FileNotFoundException`. +4. **Desajuste de versión** – Las versiones antiguas de Aspose.Words (< 21.9) no soportan `OfficeMathExportMode`. Actualiza al paquete más reciente para asegurar que **cómo exportar latex** funcione. +5. **Errores de codificación para caracteres no ASCII** – Si ves símbolos �, establece explícitamente `options.Encoding` a UTF‑8 o la página de códigos adecuada. + +## Extender la solución: de TXT a Markdown o HTML + +A veces necesitas más que texto plano—quizá un archivo Markdown que aún contenga bloques LaTeX. Los mismos `TxtSaveOptions` pueden reemplazarse por `HtmlSaveOptions` o `MarkdownSaveOptions`: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +Ese pequeño cambio te permite **convertir word a txt**‑style output mientras mantienes la sintaxis markdown que te gusta. + +--- ## Conclusión -Hemos cubierto **cómo exportar LaTeX desde Word** paso a paso, demostrado **cómo guardar archivos txt** que preservan cada ecuación Office Math, e incluso te mostramos cómo **convertir ecuaciones de Word a LaTeX** sin perder fidelidad. +Hemos recorrido una respuesta completa y lista para producción a **cómo exportar latex** desde un documento Word, mientras simultáneamente te mostramos cómo **convertir word a txt**, **convertir word a texto plano**, **guardar docx como txt**, y **cómo preservar tablas**. Los puntos clave son: + +- Cargar el DOCX con `Aspose.Words.Document`. +- Establecer `TxtSaveOptions.OfficeMathExportMode = LaTeX` y `PreserveTableLayout = true`. +- Llamar a `doc.Save(outputPath, options)` para obtener un archivo de texto plano rico en LaTeX limpio. -Con solo unas pocas líneas de C# y la poderosa biblioteca Aspose.Words, puedes convertir cualquier .docx en texto listo para LaTeX, apto para su inclusión en artículos científicos, libros de texto o flujos de publicación automatizados. +Pruébalo con tus propios archivos, experimenta con ajustes de codificación, y siéntete libre de procesar por lotes carpetas completas. Si te encuentras con casos límite—tablas anidadas, caracteres exóticos o versiones antiguas de Aspose—consulta nuevamente las secciones de “Consejos” y “Errores comunes” para soluciones rápidas. -**¿Próximos pasos?** Prueba alimentar el `.txt` generado (o renómbralo a `.tex`) a `pdflatex` o `xelatex` para producir un PDF, o explora la opción `SaveFormat.LaTeX` para obtener un archivo `.tex` directo. Si necesitas **guardar docx como txt** preservando el formato, experimenta con `PreserveTableLayout` y el manejo personalizado de saltos de línea. +¿Listo para el siguiente paso? Intenta convertir el mismo DOCX a Markdown, o alimenta el `.txt` generado a un generador de sitios estáticos que renderice LaTeX en la web. Las posibilidades son infinitas, y ahora tienes una base sólida para cualquier flujo de trabajo **convertir word a txt**. -¿Tienes preguntas sobre casos límite, licencias o ajustes de rendimiento? Deja un comentario abajo—¡feliz codificación! +¡Feliz codificación, y que tu LaTeX siempre compile a la primera! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/spanish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/spanish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..b094b73032 --- /dev/null +++ b/words/spanish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Guardar Word como PDF usando Aspose.Words en C#. Aprende a convertir + docx a PDF, detectar fuentes faltantes y manejar advertencias de sustitución de + fuentes de manera eficiente. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: es +og_description: Guardar Word como PDF usando Aspose.Words. Este tutorial paso a paso + muestra cómo convertir docx a pdf y detectar fuentes faltantes. +og_title: Guardar Word como PDF con Aspose.Words – Guía completa +tags: +- Aspose.Words +- C# +- PDF conversion +title: Guardar Word como PDF con Aspose.Words – Guía completa +url: /es/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guardar Word como PDF con Aspose.Words – Guía Completa + +¿Alguna vez necesitaste **guardar Word como PDF** al instante y te preguntaste si perderías alguna fuente en el proceso? No estás solo—los desarrolladores se enfrentan constantemente a dolores de cabeza por fuentes faltantes al convertir documentos. En esta guía recorreremos una solución práctica que no solo **convierte docx a pdf**, sino que también **detecta fuentes faltantes** usando las advertencias de sustitución de fuentes de Aspose.Words. + +Cubrirémos todo, desde la configuración del recolector de advertencias hasta la interpretación del resultado, de modo que al final sepas exactamente cómo **guardar Word como PDF** sin sorpresas. Sin herramientas externas, sin configuraciones oscuras—solo código C# limpio que puedes insertar en cualquier proyecto .NET. + +## Lo que necesitarás + +- **Aspose.Words for .NET** (última versión, por ejemplo, 24.10) – puedes obtenerlo vía NuGet (`Install-Package Aspose.Words`). +- Un entorno de desarrollo .NET (Visual Studio, Rider o VS Code funciona bien). +- Un archivo DOCX de muestra que pueda contener fuentes no instaladas en la máquina de destino. +- Eso es todo. Si tienes esos requisitos básicos, estamos listos para comenzar. + +## Guardar Word como PDF – Visión general paso a paso + +A continuación tienes el programa completo y ejecutable. Siéntete libre de copiar‑pegarlo en un proyecto de aplicación de consola y pulsar **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Consejo profesional:** Reemplaza `YOUR_DIRECTORY` por una ruta absoluta o usa `Path.Combine(Environment.CurrentDirectory, "input.docx")` para un enfoque relativo y más seguro. + +### Por qué usamos un callback de advertencia + +Aspose.Words sustituye silenciosamente las fuentes faltantes por una alternativa (normalmente Arial). Sin un callback nunca sabrías que se realizó la sustitución, lo que puede provocar fallos de diseño en el PDF resultante. Al enganchar `IWarningCallback`, obtenemos una lista clara y programática de cada evento de fuente faltante—perfecta para registrar o notificar a los usuarios finales. + +### Detectar fuentes faltantes – Qué buscar + +Al ejecutar el programa, cualquier fuente faltante generará una línea en la consola similar a: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Si la lista está vacía, felicidades—**guardar word como pdf** se completó con todas las fuentes originales intactas. + +## Convertir Docx a PDF – Personalizando la salida + +A veces necesitas una versión específica de PDF, calidad de imagen o nivel de cumplimiento. Aspose.Words te permite ajustar el objeto `PdfSaveOptions` antes de llamar a `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Por qué es importante:** Si estás generando PDFs para archivos legales, establecer `PdfA1b` garantiza que el archivo cumpla con normas estrictas. La misma conversión sigue respetando nuestro callback de advertencia, por lo que aún **detectarás fuentes faltantes**. + +## Sustitución de fuentes en Aspose Words – Manejo de casos extremos + +### Escenario 1: Múltiples fuentes faltantes + +Si tu documento fuente usa varias fuentes personalizadas, el recolector de advertencias contendrá una entrada por fuente. Puedes agregarlas: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Escenario 2: Proporcionar un directorio de fuentes de respaldo + +Aspose.Words puede buscar fuentes en carpetas adicionales. Configura la propiedad `FontsFolder` en `FontSettings` antes de cargar el documento: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Ahora la biblioteca intentará primero tu carpeta personalizada, reduciendo la probabilidad de sustituciones no deseadas. + +### Escenario 3: Ignorar sustituciones + +Si prefieres que la conversión falle cuando falta una fuente (en lugar de sustituir silenciosamente), lanza una excepción dentro del callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Esto te obliga a solucionar la fuente faltante antes de continuar—útil en pipelines CI donde los fallos silenciosos son inaceptables. + +## Ejemplo completo de extremo a extremo + +Juntando todo, aquí tienes una versión compacta que demuestra **cómo convertir Word a PDF**, establece opciones PDF personalizadas y registra cualquier problema de fuentes: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Salida esperada en la consola** (si Calibri falta): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Si no aparecen advertencias, tu operación de **guardar word como pdf** utilizó exactamente las mismas fuentes que el DOCX original. + +## Resumen visual + +![Diagrama del flujo de trabajo Guardar Word como PDF](https://example.com/diagram.png "Flujo de trabajo Guardar Word como PDF") + +*Texto alternativo de la imagen:* **guardar word como pdf** flujo que muestra la carga, la recopilación de advertencias y la salida PDF. + +## Preguntas frecuentes y respuestas + +| Pregunta | Respuesta | +|----------|-----------| +| **¿Necesito una licencia para Aspose.Words?** | Una licencia de evaluación gratuita funciona para pruebas, pero el uso en producción requiere una licencia de pago para eliminar la marca de agua de evaluación. | +| **¿Funcionará esto en .NET Core / .NET 6+?** | Absolutamente—Aspose.Words está dirigido a .NET Standard 2.0, por lo que cualquier runtime .NET reciente es compatible. | +| **¿Puedo convertir varios archivos DOCX en un bucle?** | Sí, simplemente instancia un nuevo `Document` para cada archivo y reutiliza el mismo `WarningInfoCollector` si deseas resultados agregados. | +| **¿Qué pasa si la carpeta de salida no existe?** | `Document.Save` lanzará `DirectoryNotFoundException`. Crea la carpeta primero o usa `Directory.CreateDirectory`. | +| **¿Hay una forma de incrustar las fuentes faltantes en el PDF?** | Aspose.Words puede incrustar fuentes automáticamente si están disponibles en la máquina; establece `PdfSaveOptions.EmbedFullFonts = true`. | + +## Conclusión + +Ahora tienes un patrón sólido y listo para producción para **guardar Word como PDF** mientras **detectas fuentes faltantes** y manejas escenarios de **sustitución de fuentes de Aspose.Words**. Al adjuntar un callback de advertencia, personalizar carpetas de fuentes y, opcionalmente, ajustar `PdfSaveOptions`, puedes **convertir docx a pdf** de forma fiable y mantener a tus usuarios informados sobre cualquier problema de fuentes que pueda afectar la fidelidad del diseño. + +¿Listo para el siguiente paso? Intenta generar PDFs a partir de varios documentos en paralelo, o explora añadir marcas de agua y firmas digitales—ambas son extensiones sencillas del código que acabas de dominar. ¡Feliz codificación, y que tus PDFs siempre se vean exactamente como esperas! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-loadoptions/_index.md b/words/spanish/net/programming-with-loadoptions/_index.md index 8900f9eb26..bae3d54d2c 100644 --- a/words/spanish/net/programming-with-loadoptions/_index.md +++ b/words/spanish/net/programming-with-loadoptions/_index.md @@ -39,6 +39,7 @@ En estos tutoriales, aprenderá a usar LoadOptions para cargar documentos de Wor | [Cómo recuperar docx – establecer modo de recuperación y abrir archivos Word dañados](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) Aprenda a establecer el modo de recuperación y abrir documentos Word corruptos usando Aspose.Words para .NET. | | [Cómo usar LoadOptions en Aspose.Words – Guía completa](./how-to-use-loadoptions-in-aspose-words-complete-guide/) Aprenda paso a paso a utilizar LoadOptions en Aspose.Words para .NET y personalizar la carga de documentos. | | [Recuperar documento corrupto en C# – Establecer modo de recuperación y solicitar al usuario](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) Aprenda a recuperar documentos corruptos en C# usando Aspose.Words, configurando el modo de recuperación y mostrando un mensaje al usuario. | +| [Recuperar docx corrupto – Guía completa para cargar archivos Word dañados en C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) Aprenda a cargar y reparar archivos DOCX dañados en C# usando Aspose.Words, con pasos detallados y ejemplos claros. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/spanish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..85be97f9ee --- /dev/null +++ b/words/spanish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: Recupere archivos docx corruptos rápidamente con Aspose.Words. Aprenda + cómo establecer el modo de recuperación, cargar docx de forma segura y leer archivos + Word dañados en solo unos pocos pasos. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: es +og_description: Recupere archivos docx corruptos en C#. Establezca el modo de recuperación, + cargue el docx de forma segura y lea archivos Word dañados con Aspose.Words. +og_title: Recuperar docx corrupto – Guía rápida de C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Recuperar docx corrupto – Guía completa para cargar archivos Word dañados en + C# +url: /es/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Recuperar docx corrupto – Guía rápida de C# + +¿Alguna vez intentaste abrir un archivo de Word que simplemente no cargaba y te preguntaste si el contenido se había perdido para siempre? En muchos proyectos del mundo real, **recuperar docx corruptos** sin pedir al usuario que reenvíe el archivo adjunto. La buena noticia es que Aspose.Words lo hace muy fácil: simplemente estableces el modo de recuperación y dejas que la biblioteca haga el trabajo pesado. + +## Lo que necesitarás + +- **Aspose.Words for .NET** (cualquier versión reciente; la API que usamos funciona con 23.5 y superiores). +- Un entorno de desarrollo .NET (Visual Studio, VS Code o Rider). +- El `.docx` corrupto o parcialmente dañado que deseas rescatar. + +No se requieren permisos especiales, ni interop COM, y no es necesario instalar Microsoft Office en el servidor. Simple, ¿verdad? + +## Paso 1: Establecer el modo de recuperación a Auto‑Recover + +Cuando un archivo de Word está dañado, el comportamiento de carga predeterminado lanza una excepción y aborta. Configurando un objeto `LoadOptions` le indicas a Aspose.Words que **establezca el modo de recuperación** a `AutoRecover`, lo que escanea el paquete zip, omite las partes ilegibles y devuelve todo lo que pueda reconstruir. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **¿Por qué AutoRecover?** +> Intenta leer la mayor cantidad posible manteniendo el objeto documento utilizable. Si eliges `RecoveryMode.NoRecovery`, la carga fallará en la primera corrupción, lo que anula el propósito de los escenarios de **recuperar docx corruptos**. + +## Paso 2: Cargar el documento con las opciones configuradas + +Ahora que el modo de recuperación está establecido, puedes intentar abrir el archivo de forma segura. Reemplaza `"YOUR_DIRECTORY/input.docx"` con la ruta real a tu archivo dañado. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Si el archivo está solo parcialmente corrupto, la instancia `Document` aún se creará. Puedes comprobar `document.IsStructureValid` más adelante si necesitas una validación extra. + +## Paso 3: Verificar el formato detectado + +Aspose.Words detecta automáticamente el formato original (DOC, DOCX, ODT, etc.). Imprimir este valor te ayuda a confirmar que la biblioteca reconoció el archivo correctamente, lo que constituye una rápida comprobación de sanidad después de una operación de **recuperar docx corruptos**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Salida típica: + +``` +Loaded with Docx format. +``` + +Incluso si faltan algunas partes, la detección de formato sigue teniendo éxito—otro punto a favor de los flujos de trabajo de **recuperar docx corruptos**. + +## Paso 4: Extraer lo que puedas + +Una vez cargado el documento, puedes tratarlo como cualquier archivo Word saludable. A continuación tienes un ejemplo compacto que extrae texto plano y lo escribe en la consola. Esto demuestra que puedes **leer archivo Word dañado** sin que se produzcan fallos. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Si el archivo original contenía tablas o imágenes que estaban corruptas, simplemente se omitirán en la salida de texto. El resto del documento permanece intacto. + +## Paso 5: Guardar una copia limpia (opcional) + +Con frecuencia querrás ofrecer al usuario una nueva versión limpia del archivo después de la recuperación. Guardar con el mismo formato garantiza la compatibilidad con cualquier proceso posterior. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Ahora tienes un archivo **recuperado docx dañado** que puedes adjuntar de forma segura a un correo electrónico o pasar a otro servicio. + +## Ejemplo completo y funcional + +Juntándolo todo, aquí tienes el programa completo listo para ejecutar. Pégalo en un nuevo proyecto de consola, ajusta las rutas de archivo y pulsa F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Salida esperada** (suponiendo que el archivo contiene un solo párrafo “Hello world!” y algo de XML corrupto): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Observa cómo el programa nunca se bloquea—aunque el archivo fuente estaba parcialmente roto. Esa es la esencia de **recuperar docx corruptos** usando Aspose.Words. + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si el archivo es completamente ilegible? + +Incluso `AutoRecover` tiene límites. Si el contenedor zip está corrupto más allá de reparación, Aspose.Words lanzará una `CorruptedFileException`. En ese caso podrías necesitar una herramienta de reparación de zip de terceros antes de intentar **recuperar docx corruptos** nuevamente. + +### ¿Puedo recuperar otros formatos (p. ej., `.doc`, `.odt`)? + +Absolutamente. El mismo `LoadOptions` funciona para cualquier formato que Aspose.Words admita. Simplemente cambia la extensión del archivo y la biblioteca detectará automáticamente el formato original. Esto significa que también puedes **recuperar docx dañados**‑like files como `.doc` o `.rtf` con el mismo código. + +### ¿Cómo manejo documentos muy grandes sin cargar todo en memoria? + +Para archivos de varios gigabytes puedes habilitar **opciones de carga** como `LoadOptions.LoadFormat` o transmitir el documento página a página. Sin embargo, el algoritmo de recuperación aún necesita leer todo el paquete, por lo que se espera un mayor consumo de memoria para archivos corruptos muy grandes. + +### ¿Hay alguna forma de saber qué partes se perdieron? + +Después de cargar, puedes inspeccionar `document.GetChildNodes(NodeType.Any, true)` y comparar el recuento con una referencia esperada. Tablas, imágenes o encabezados que falten simplemente estarán ausentes en la colección de nodos. Esto te permite registrar exactamente qué se **recuperó docx dañado** y notificar al usuario. + +## Consejos profesionales para una recuperación fiable + +- **Valida el tamaño del archivo de entrada** antes de cargarlo; un archivo de cero bytes siempre fallará. +- **Registra el resultado de `RecoveryMode`** capturando `DocumentLoadingException` y almacenando el mensaje de la excepción; a menudo contiene pistas sobre qué partes se omitieron. +- **Ejecuta la recuperación en un hilo en segundo plano** si procesas cargas en un servicio web—esto mantiene la solicitud responsiva. +- **Combínalo con una suma de verificación** (p. ej., MD5) para detectar si el archivo recuperado difiere del original; así puedes decidir si conservar ambas versiones. + +## Conclusión + +Acabamos de mostrar cómo **recuperar docx corruptos** en C# mediante **establecer el modo de recuperación** a `AutoRecover`, cargar el documento de forma segura, extraer el texto que sobreviva y, opcionalmente, guardar una copia limpia. Este enfoque te permite **cargar docx** que de otro modo lanzarían excepciones y te brinda una manera fiable de **leer archivo Word dañado** sin herramientas externas. + +¿Próximos pasos? Prueba a cambiar `RecoveryMode.AutoRecover` por `RecoveryMode.NoRecovery` para ver la diferencia, o experimenta con las propiedades de `LoadOptions` que controlan el manejo de contraseñas y la sustitución de fuentes. También podrías integrar la rutina de recuperación en una API ASP.NET Core que acepte cargas y devuelva un archivo reparado—perfecto para pipelines empresariales de gestión documental. + +¿Tienes más preguntas sobre la recuperación de documentos Word, o quieres ver cómo **recuperar docx dañados** con callbacks personalizados? ¡Deja un comentario abajo y feliz codificación! + +![Ilustración de un documento recuperado – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recuperar docx corrupto") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-markdownsaveoptions/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/_index.md index 22923377ed..a17232c9c3 100644 --- a/words/spanish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/spanish/net/programming-with-markdownsaveoptions/_index.md @@ -42,6 +42,8 @@ Procesamiento de textos con MarkdownSaveOptions es un recurso detallado que te g ### [Guardar docx como markdown con Aspose.Words – Guía completa en C#](./save-docx-as-markdown-with-aspose-words-full-c-guide/) Aprenda a guardar archivos DOCX como Markdown usando Aspose.Words con una guía completa en C#. ### [Guardar imágenes de Word – Convertir Word a Markdown con Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) Aprenda a extraer y guardar imágenes de documentos Word al convertirlos a Markdown usando Aspose.Words. ### [Convertir Word a Markdown en C# – Guía completa con extracción de imágenes](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) Aprenda a convertir documentos Word a Markdown y extraer imágenes usando Aspose.Words para .NET. +### [Guardar docx como markdown – Exportar matemáticas de Word a LaTeX con Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) Aprenda a convertir ecuaciones de Word a LaTeX al guardar documentos DOCX como archivos Markdown usando Aspose.Words. +### [Subir imágenes a la nube al convertir Word a Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) Aprenda a subir imágenes a la nube automáticamente al convertir documentos Word a Markdown con Aspose.Words para .NET. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..e08eb5398f --- /dev/null +++ b/words/spanish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Guarda docx como markdown usando Aspose.Words – aprende a convertir Word + a markdown, exportar ecuaciones a LaTeX y establecer la resolución de imágenes en + markdown en un flujo de trabajo fluido. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: es +og_description: Guardar docx como markdown con Aspose.Words. Este tutorial muestra + cómo convertir Word a markdown, exportar ecuaciones a LaTeX y establecer la resolución + de imágenes en markdown. +og_title: guardar docx como markdown – Guía completa para exportar fórmulas de Word + a LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: guardar docx como markdown – Exportar matemáticas de Word a LaTeX con Aspose.Words +url: /es/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# guardar docx como markdown – Exportar Office Math a LaTeX con Aspose.Words + +¿Alguna vez necesitaste **guardar docx como markdown** y te quedaste atascado sin saber cómo mantener esas ecuaciones de Office Math nítidas? No eres el único. La mayoría de los desarrolladores se topan con una pared cuando la conversión predeterminada deja las ecuaciones como imágenes borrosas, obligando a reescribirlas manualmente en LaTeX. + +Buenas noticias: Aspose.Words puede hacer el trabajo pesado por ti. En este tutorial **convertiremos word a markdown**, indicaremos al motor que **exporte ecuaciones a latex**, e incluso **estableceremos la resolución de imágenes en markdown** para el resto del documento. Al final tendrás un solo comando que genera un archivo `.md` limpio con matemáticas listas para LaTeX e imágenes de alta resolución. + +## Lo que aprenderás + +- Cómo cargar un `.docx` que contiene objetos Office Math. +- Qué propiedades de `MarkdownSaveOptions` controlan **export equations to latex** y **set markdown image resolution**. +- Un fragmento completo y ejecutable en C# que puedes pegar en cualquier proyecto .NET. +- Consejos para solucionar problemas comunes, como fuentes faltantes o características de ecuaciones no compatibles. + +**Requisitos previos**: .NET 6+ (o .NET Framework 4.6+), una licencia de Aspose.Words for .NET y conocimientos básicos de C#. Si sabes crear una aplicación de consola, estás listo para comenzar. + +--- + +## Paso 1 – Guardar docx como markdown: Carga tu archivo Word + +Lo primero que necesitamos es un objeto `Document` que apunte al `.docx` de origen. Piensa en ello como abrir el libro antes de empezar a copiar capítulos. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Por qué importa*: Si el documento no contiene ninguna ecuación, el paso **export equations to latex** no hará nada, pero el resto de la conversión seguirá ejecutándose. La comprobación te evita preguntarte por qué tu Markdown de salida carece de bloques LaTeX. + +--- + +## Paso 2 – Configurar Export Equations to LaTeX + +Aspose.Words te permite decidir cómo se renderizan los Office Math. Por defecto los convierte en imágenes PNG, razón por la cual muchos tutoriales terminan con un archivo markdown granulado. Cambiar `OfficeMathExportMode` a `LaTeX` te brinda ecuaciones limpias, listas para copiar y pegar. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*¿Por qué `OfficeMathExportMode.LaTeX`?* LaTeX es la lingua franca de la publicación científica. Cuando más adelante renderices el markdown con un generador de sitios estáticos o un cuaderno Jupyter, las ecuaciones aparecerán nítidas a cualquier nivel de zoom. + +--- + +## Paso 3 – Establecer la Resolución de Imágenes en Markdown (para contenido no matemático) + +Aunque nos centramos en las ecuaciones, la mayoría de los documentos Word también contienen fotos, gráficos o SVG incrustados. La propiedad `ImageResolution` controla cómo Aspose.Words rasteriza esos recursos. Un valor de **300 DPI** es un buen punto medio para pantalla e impresión. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Consejo profesional*: Si tu markdown solo se mostrará en la web, puedes reducirlo a 150 DPI para disminuir el tamaño del archivo. Por el contrario, para PDFs listos para imprimir, súbelo a 600 DPI. + +--- + +## Paso 4 – Ejecutar la Conversión – Convert Word Math LaTeX + +Una vez que todo está configurado, la conversión real es una sola línea. Aspose.Words hace el trabajo pesado tras bambalinas. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Salida esperada**: Abre el archivo `.md` generado y deberías ver algo como: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Observa los bloques LaTeX (`$...$` y `$$...$$`) que sustituyen a los fragmentos PNG anteriores. La imagen al final sigue siendo un PNG, renderizada a 300 DPI como solicitamos. + +--- + +## Paso 5 – Casos límite comunes y cómo manejarlos + +| Situación | Qué ocurre | Cómo solucionarlo | +|-----------|------------|-------------------| +| **Fuentes faltantes** (p. ej., Cambria Math no instalada) | La salida LaTeX puede contener símbolos desconocidos. | Instala la fuente faltante en el servidor o incrústala en el documento antes de la conversión. | +| **Ecuaciones complejas** (matriz con delimitadores personalizados) | Aspose.Words puede volver a una imagen pese al modo `LaTeX`. | Actualiza a la última versión de Aspose.Words; la biblioteca mejora continuamente la cobertura de ecuaciones. | +| **Documentos grandes** ( > 50 MB ) | La presión de memoria puede provocar `OutOfMemoryException`. | Usa `LoadOptions` con `LoadFormat.Docx` y transmite el archivo, o divide el documento en secciones antes de convertir. | +| **Tamaño de imagen demasiado grande** | El archivo Markdown se vuelve enorme, ralentizando las compilaciones del sitio estático. | Reduce `ImageResolution` a 150 DPI para escenarios solo web (ver Paso 3). | + +--- + +## Paso 6 – Juntarlo todo: Ejemplo completo funcional + +A continuación tienes el programa *completo* de consola que puedes copiar‑pegar en `Program.cs`. Incluye todos los fragmentos que discutimos, más un poco de manejo de errores adicional. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Ejecuta el programa (`dotnet run`) y obtendrás un archivo markdown que **save docx as markdown** mientras preserva cada ecuación como LaTeX. Sin copias manuales, sin imágenes rasterizadas feas para las matemáticas. + +--- + +## Conclusión + +Hemos recorrido todo el proceso de **saving docx as markdown** con Aspose.Words, desde cargar el archivo Word hasta configurar **export equations to latex** y **set markdown image resolution**. El fragmento final está listo para producción, y puedes insertarlo en cualquier proyecto .NET que necesite **convert word to markdown** sobre la marcha. + +¿Qué sigue? Prueba a alimentar el `.md` generado a un generador de sitios estáticos como Hugo o Jekyll y observa cómo tus ecuaciones se renderizan hermosamente. Si necesitas **convert word math latex** a otros formatos (PDF, HTML), simplemente cambia `MarkdownSaveOptions` por `PdfSaveOptions` o `HtmlSaveOptions`; la misma bandera `OfficeMathExportMode` funciona en todos ellos. + +¿Tienes alguna variante en tu flujo de trabajo, como obtener archivos Word desde Azure Blob storage o transmitirlos desde una API? El mismo patrón se aplica; solo reemplaza el constructor `Document` basado en el sistema de archivos por uno basado en streams. + +¡Experimenta y cuéntanos en los comentarios cómo este enfoque resolvió tus dolores de conversión! ¡Feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..7bf3f8affb --- /dev/null +++ b/words/spanish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-05-01 +description: Sube imágenes a la nube mientras conviertes un documento Word a markdown. + Aprende cómo extraer imágenes de docx y almacenarlas en Azure Blob storage. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: es +og_description: Sube imágenes a la nube mientras conviertes un documento de Word a + markdown. Esta guía muestra cómo extraer imágenes de un docx y almacenarlas en Azure + Blob Storage. +og_title: Subir imágenes a la nube al convertir Word a Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Subir imágenes a la nube al convertir Word a Markdown +url: /es/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Subir imágenes a la nube al convertir Word a Markdown + +¿Alguna vez necesitaste **subir imágenes a la nube** mientras conviertes un archivo Word a markdown? No eres el único—los desarrolladores constantemente manejan la conversión de documentos y la gestión de recursos, y hacer ambas cosas en un flujo fluido puede sentirse como perseguir un objetivo en movimiento. + +¿La buena noticia? Con Aspose.Words puedes extraer cada imagen, gráfico o diagrama de un .docx, enviarlo directamente a Azure Blob Storage y dejar que el markdown generado haga referencia a esas URL en la nube en lugar de archivos locales. En este tutorial recorreremos todo el proceso, desde cargar el documento fuente hasta obtener un archivo markdown limpio que apunte a tu contenedor de Azure. + +Al final de esta guía podrás **convertir docx a markdown**, **extraer imágenes de docx** y **almacenar imágenes Azure Blob**—todo con solo unas pocas líneas de C#. Sin herramientas externas, sin copiar‑pegar manual y, por supuesto, sin enlaces de imagen rotos. + +## Lo que necesitarás + +- **.NET 6.0** o posterior (el código funciona también en .NET Core y .NET Framework) +- **Aspose.Words for .NET** (paquete NuGet `Aspose.Words`) +- Una **cuenta de Azure Storage** con un contenedor (p. ej., `images`) y una clave de acceso compartido – necesitarás la cadena de conexión para subir archivos. +- Un conocimiento básico de C# y async/await (opcional pero útil). + +Si ya tienes estas piezas en su lugar, genial—pasemos directamente a la solución. Si no, la sección “Prerequisites” al final te indicará los pasos rápidos de configuración. + +## Paso 1: Configurar el ayudante de Azure Blob (Por qué es importante) + +Antes de tocar el documento Word, necesitamos un pequeño ayudante que sepa cómo enviar un arreglo de bytes a Azure Blob Storage y devolver una URL pública. Esta abstracción mantiene la lógica de conversión limpia y facilita cambiar de proveedor de almacenamiento más adelante. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**¿Por qué este ayudante?** +1. **Separación de responsabilidades** – el código de conversión a markdown se mantiene enfocado en el manejo del documento, no en los detalles HTTP. +2. **Reutilización** – puedes llamar a `UploadAsync` desde cualquier otro lugar de tu aplicación (p. ej., para imágenes subidas por usuarios). +3. **Preparación para el futuro** – cambiar a Amazon S3 o Google Cloud Storage solo requiere una nueva implementación de la misma interfaz. + +> **Consejo profesional:** Configura el nivel de acceso del contenedor a `Blob` (público) solo si estás de acuerdo con que cualquiera pueda leer las imágenes. Para escenarios privados, genera tokens SAS por carga e incrusta esas URL en su lugar. + +## Paso 2: Definir una devolución de llamada de guardado de recursos (El núcleo de Subir‑mientras‑conviertes) + +Aspose.Words te permite interceptar cada recurso (imagen, gráfico, etc.) que normalmente se escribiría en disco al guardar un documento como markdown. Al proporcionar un `ResourceSavingCallback`, podemos subir cada recurso a Azure Blob y reemplazar el nombre de archivo local con la URL en la nube. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**¿Qué está ocurriendo aquí?** + +- **Extract** – Aspose.Words nos da un stream para cada imagen. +- **Upload** – Pasamos ese stream a `AzureBlobUploader`. +- **Replace** – El escritor de markdown recibe la URL pública y la escribe en la sintaxis de imagen markdown (`![](https://…)`). + +Como establecemos `args.AlreadyExists = true`, no quedan archivos temporales que ensucien el sistema de archivos—una operación limpia y sin estado, perfecta para funciones serverless. + +## Paso 3: Configurar las opciones de guardado de Markdown (Unir todo) + +Ahora integramos la devolución de llamada en `MarkdownSaveOptions` de Aspose.Words. Los indicadores cruciales son `ExportImagesAsBase64 = false` (para obtener enlaces externos) y `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**¿Por qué desactivamos Base64?** +Cuando `ExportImagesAsBase64` es true, Aspose incrusta cada imagen directamente en el markdown como un data URI. Eso anula el propósito de **subir imágenes a la nube** porque el archivo markdown se inflama y las imágenes permanecen ocultas al CDN. Al desactivarlo obtenemos enlaces externos limpios que apuntan a Azure Blob—exactamente lo que espera un generador de sitios estáticos moderno. + +## Paso 4: Juntar todo – Una aplicación de consola mínima + +A continuación tienes un programa de consola completo y listo para ejecutar. Reemplaza los marcadores de posición con tu cadena de conexión de Azure y el nombre del contenedor. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Salida esperada + +Ejecutar el programa con `sample.docx` que contiene dos imágenes producirá: + +- `output.md` que contiene sintaxis de imagen markdown como: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-pdfsaveoptions/_index.md b/words/spanish/net/programming-with-pdfsaveoptions/_index.md index c4181042c4..cbb9424572 100644 --- a/words/spanish/net/programming-with-pdfsaveoptions/_index.md +++ b/words/spanish/net/programming-with-pdfsaveoptions/_index.md @@ -38,7 +38,7 @@ Si desea convertir documentos de Word a PDF para distribuirlos en línea, archiv | [Incrustar subconjuntos de fuentes en un documento PDF](./embedded-subset-fonts/) Reduzca el tamaño de sus archivos PDF incrustando solo los subconjuntos de fuentes necesarios con Aspose.Words para .NET. Siga nuestra guía paso a paso para optimizar sus archivos PDF eficientemente. | [Reducir el tamaño del PDF deshabilitando las fuentes incrustadas](./disable-embed-windows-fonts/) Reduzca el tamaño de sus archivos PDF deshabilitando las fuentes incrustadas con Aspose.Words para .NET. Siga la guía paso a paso para optimizar sus documentos y optimizar su almacenamiento y uso compartido. | [Optimice el tamaño de PDF con fuentes Arial y Times Roman incrustadas](./skip-embedded-arial-and-times-roman-fonts/) Optimice el tamaño de sus archivos PDF omitiendo las fuentes Arial y Times Roman incrustadas con Aspose.Words para .NET. Siga esta guía paso a paso para optimizar sus archivos PDF. -| [Reducir el tamaño del archivo PDF al no incrustar fuentes principales](./avoid-embedding-core-fonts/) Aprenda a reducir el tamaño de sus archivos PDF sin incrustar fuentes principales con Aspose.Words para .NET. Siga nuestra guía paso a paso para optimizar sus archivos PDF. +| [Reducir el tamaño del archivo PDF al no incrustar fuentes principales](./avoid-embedding-core-fonts/) Aprenda a reducir el tamaño de sus archivos PDF sin incrustar fuentes principales con Aspose.Words para .NET. Siga la guía paso a paso para optimizar sus archivos PDF. | [Escapar URI en un documento PDF](./escape-uri/) Aprenda a escapar URIs en archivos PDF con Aspose.Words para .NET. Esta guía detallada le guiará paso a paso por el proceso. | [Exportar marcadores de encabezado y pie de página de un documento de Word a un documento PDF](./export-header-footer-bookmarks/) | Aprenda a exportar marcadores de encabezado y pie de página de un documento de Word a PDF usando Aspose.Words para .NET con nuestra guía paso a paso. | | [Reducir el tamaño de un PDF con la función Escalar fuentes WMF al tamaño de un metarchivo](./scale-wmf-fonts-to-metafile-size/) | Guía paso a paso para reducir el tamaño de PDF con escala de fuentes wmf al tamaño de metarchivo al convertir a PDF con Aspose.Words para .NET. | @@ -54,11 +54,11 @@ Si desea convertir documentos de Word a PDF para distribuirlos en línea, archiv | [Interpolar imágenes en un documento PDF](./interpolate-images/) Aprenda a interpolar imágenes en un documento PDF con Aspose.Words para .NET con nuestra guía paso a paso. Mejore fácilmente la calidad de imagen de su PDF. | | [Guardar docx como pdf con Aspose.Words – Guía completa en C#](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Guía paso a paso para guardar documentos DOCX como PDF usando Aspose.Words en C#. | | [Crear PDF accesible desde Word con C# – Guía paso a paso](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | Aprenda a crear PDFs accesibles desde documentos Word usando Aspose.Words para .NET y C# con esta guía paso a paso. | -| [Exportar la estructura de un documento de Word a un documento PDF](./export-document-structure/) Exporte la estructura de un documento de Word a PDF con Aspose.Words para .NET. Siga la guía paso a paso para conservar el diseño del documento y mejorar la navegación en PDF. -| [Compresión de imágenes en un documento PDF](./image-compression/) Aprenda a comprimir imágenes en documentos PDF con Aspose.Words para .NET. Siga esta guía para optimizar el tamaño y la calidad de los archivos. +| [Exportar la estructura de un documento de Word a un documento PDF](./export-document-structure/) Exporte la estructura de un documento de Word a PDF con Aspose.Words para .NET. Siga la guía paso a paso para conservar el diseño del documento y mejorar la navegación en PDF. | +| [Compresión de imágenes en un documento PDF](./image-compression/) Aprenda a comprimir imágenes en documentos PDF con Aspose.Words para .NET. Siga esta guía para optimizar el tamaño y la calidad de los archivos. | | [Actualizar la última propiedad impresa en un documento PDF](./update-last-printed-property/) | Aprenda a actualizar la última propiedad impresa en un documento PDF usando Aspose.Words para .NET con nuestra guía paso a paso. | | [Renderizar efectos 3D DML 3D en un documento PDF](./dml-3deffects-rendering/) | Aprenda a renderizar impresionantes efectos DML 3D en documentos PDF usando Aspose.Words para .NET con esta completa guía paso a paso. | -| [Interpolar imágenes en un documento PDF](./interpolate-images/) Aprenda a interpolar imágenes en un documento PDF con Aspose.Words para .NET con nuestra guía paso a paso. Mejore fácilmente la calidad de imagen de su PDF. +| [Interpolar imágenes en un documento PDF](./interpolate-images/) | Aprenda a interpolar imágenes en un documento PDF con Aspose.Words para .NET con nuestra guía paso a paso. Mejore fácilmente la calidad de imagen de su PDF. | | [Crear PDF accesible en C# – Tutorial de accesibilidad PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Aprenda a generar PDFs accesibles en C# con Aspose.Words, cumpliendo normas de accesibilidad y mejorando la usabilidad para todos los usuarios. | | [Agregar firma digital a PDF usando el titular del certificado](./digitally-signed-pdf-using-certificate-holder/) | Proteja sus archivos PDF con una firma digital usando Aspose.Words para .NET. Siga esta guía paso a paso para agregar una firma digital a sus PDF fácilmente. | | [Incrustar fuentes en un documento PDF](./embedded-all-fonts/) | Incruste fuentes en documentos PDF fácilmente con Aspose.Words para .NET con esta guía detallada paso a paso. Asegúrese de que la apariencia sea uniforme en todos los dispositivos. | @@ -81,13 +81,12 @@ Si desea convertir documentos de Word a PDF para distribuirlos en línea, archiv | [Interpolar imágenes en un documento PDF](./interpolate-images/) | Aprenda a interpolar imágenes en un documento PDF con Aspose.Words para .NET con nuestra guía paso a paso. Mejore fácilmente la calidad de imagen de su PDF. | | [Crear PDF accesible desde Word – Guía completa](./create-accessible-pdf-from-word-complete-guide/) | Aprenda a crear PDFs accesibles desde documentos Word con Aspose.Words para .NET siguiendo esta guía completa paso a paso. | | [Crear PDF accesible – Guía paso a paso para cumplimiento PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Guía paso a paso para crear PDFs accesibles cumpliendo con PDF/UA usando Aspose.Words para .NET. | +| [Guardar documento como PDF con Aspose.Words – Guía completa en C#](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Guía paso a paso para guardar documentos como PDF usando Aspose.Words en C#. | {{< /blocks/products/pf/tutorial-page-section >}} - {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} - {{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/spanish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..bf025e447a --- /dev/null +++ b/words/spanish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Aprende cómo guardar un documento como PDF usando Aspose.Words en C#. + El tutorial también cubre la conversión de Word a PDF, la exportación de fórmulas + en LaTeX y el manejo de fuentes faltantes. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: es +og_description: Guarda el documento como PDF sin esfuerzo con Aspose.Words. Esta guía + también muestra cómo convertir Word a PDF, exportar LaTeX matemático y manejar fuentes + faltantes. +og_title: Guardar documento como PDF con Aspose.Words – Guía completa de C# +tags: +- Aspose.Words +- C# +- PDF generation +title: Guardar documento como PDF con Aspose.Words – Guía completa de C# +url: /es/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guardar documento como PDF con Aspose.Words – Guía completa en C# + +¿Alguna vez te has preguntado **cómo guardar documento como pdf** directamente desde un archivo Word sin perder características de accesibilidad? No eres el único—los desarrolladores preguntan constantemente por una forma fiable de convertir Word a PDF mientras se preservan las ecuaciones matemáticas y se manejan las fuentes faltantes de manera elegante. + +En este tutorial recorreremos una solución paso a paso que no solo **save document as pdf** sino que también demuestra **convert word to pdf**, **export math latex**, y **handle missing fonts** usando la última versión de Aspose.Words para .NET. Al final tendrás un programa C# listo para ejecutar que produce archivos compatibles con PDF/UA‑2, perfectos para auditorías de accesibilidad. + +## Lo que necesitarás + +- .NET 6 o posterior (el código funciona también con .NET Core y .NET Framework) +- Aspose.Words para .NET 25.10 o más reciente – puedes obtener una prueba gratuita en el sitio web de Aspose +- Un documento Word modesto (`input.docx`) que contenga al menos una forma flotante y una ecuación matemática (para ver la función export‑math‑latex en acción) +- Visual Studio 2022 (o cualquier IDE que prefieras) + +> **Consejo profesional:** Si estás en una canalización CI/CD, agrega el paquete NuGet de Aspose.Words a tu archivo de proyecto: + +```xml + +``` + +Ahora sumerjámonos en el código. + +## Paso 1: Cargar el documento fuente con recuperación automática + +Al trabajar con archivos Word del mundo real, podrías encontrar secciones corruptas o recursos faltantes. Habilitar la recuperación automática garantiza que el proceso de carga nunca lance una excepción. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Por qué es importante:** +`RecoveryMode.AutoRecover` protege tu canalización de fallos ante entradas mal formadas, lo cual es especialmente útil cuando **convert word to pdf** en lote. + +## Paso 2: Configurar las opciones de guardado PDF para plena accesibilidad + +PDF/UA‑2 es el estándar ISO para PDFs accesibles. Configurando algunas banderas obtenemos un archivo que los lectores de pantalla pueden navegar, y también nos aseguramos de que las ecuaciones matemáticas se exporten como LaTeX oculto. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Puntos clave:** + +- **ExportFloatingShapesAsInlineTag** – asegura que el PDF resultante respete el diseño original manteniéndose semánticamente correcto. +- **OfficeMathExportMode.LaTeX** – satisface el requisito de **export math latex**, permitiendo que herramientas posteriores extraigan las ecuaciones si es necesario. + +## Paso 3: Capturar advertencias (p. ej., fuentes faltantes) + +Las fuentes faltantes son un dolor de cabeza común al convertir documentos. Aspose.Words puede reportar estos problemas mediante un `WarningCallback`. Los recopilaremos para que puedas registrarlos o actuar sobre ellos más tarde. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Por qué te importa:** +Si la fuente del origen no está instalada en el servidor, el PDF recurrirá a una fuente predeterminada, lo que podría romper el diseño. Al **handle missing fonts** podemos alertar al usuario o incrustar un sustituto. + +## Paso 4: Guardar el documento como PDF accesible + +Ahora llega el momento de la verdad—realizar la conversión. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Si todo transcurre sin problemas, terminarás con un archivo PDF/UA‑2 que contiene LaTeX oculto para cada ecuación y etiquetado adecuado para las formas flotantes. + +## Paso 5: Revisar las advertencias capturadas (Opcional pero recomendado) + +Después de la operación de guardado, puedes iterar sobre las advertencias recopiladas y registrarlas. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +La salida típica podría verse así: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Ver estos mensajes temprano te ayuda a **handle missing fonts** antes de que afecten a los usuarios finales. + +## Ejemplo completo en funcionamiento + +Juntando todo, aquí tienes el programa completo y listo para ejecutar. Reemplaza las rutas de marcador de posición con las tuyas. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Resultado esperado:** +- `output.pdf` cumple con PDF/UA‑2. +- Todas las formas flotantes están etiquetadas como figuras en línea. +- Cada objeto Office Math aparece como LaTeX oculto (visible al inspeccionar la estructura del PDF). +- Cualquier problema relacionado con fuentes se imprime en la consola, dándote la oportunidad de **handle missing fonts** antes de distribuir el archivo. + +![Diagrama que muestra el flujo de Word → Aspose.Words → PDF accesible (guardar documento como pdf)](conversion-diagram.png "Diagrama de flujo para guardar documento como pdf") + +*Texto alternativo de la imagen:* **Diagrama de cómo guardar documento como pdf usando Aspose.Words** + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si estoy usando una versión anterior de Aspose.Words? + +La bandera `OfficeMathExportMode.LaTeX` se introdujo en la versión 25.10. En versiones anteriores aún puedes **convert word to pdf**, pero las ecuaciones se rasterizarán en lugar de exportarse como LaTeX. Actualiza para obtener la mejor accesibilidad. + +### ¿Puedo incrustar fuentes personalizadas para evitar el fallback? + +Sí. Configura `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` antes de llamar a `Save`. Esto también ayuda a **handle missing fonts** forzando que el PDF contenga los glifos requeridos. + +### ¿Cómo verifico la conformidad con PDF/UA‑2? + +Abre el archivo en Adobe Acrobat Pro → “Print Production” → “Preflight”. Elige el perfil “PDF/A‑2b” o “PDF/UA‑2”; Acrobat informará cualquier infracción. + +### ¿Qué pasa con los archivos Word protegidos con contraseña? + +Carga el documento con un `LoadOptions` que incluya `Password`. Ejemplo: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +El resto de la canalización permanece sin cambios. + +## Conclusión + +Hemos cubierto todo lo que necesitas para **save document as pdf** usando Aspose.Words en C#. El tutorial también demostró cómo **convert word to pdf**, **export math latex**, y **handle missing fonts**, todo mientras se produce un archivo PDF/UA‑2 accesible. + +Ejecuta el código, experimenta con diferentes `PdfSaveOptions` (p. ej., compresión de imágenes, PDF/A‑2b), e intégralo en tu servicio de procesamiento de documentos. Si necesitas ir más allá, considera explorar la biblioteca específica de PDF de Aspose para post‑procesamiento o firmas digitales. + +¿Tienes más escenarios que te gustaría abordar? No dudes en dejar un comentario o consultar nuestras otras guías sobre **PDF manipulation**, **image extraction**, y **batch conversion**. ¡Feliz codificación! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-shapes/_index.md b/words/spanish/net/programming-with-shapes/_index.md index c438c37bd5..e4cb6ce79e 100644 --- a/words/spanish/net/programming-with-shapes/_index.md +++ b/words/spanish/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Al usar Aspose.Words para .NET y seguir estos tutoriales, dominará la manipulac | [Crear forma de rectángulo en Word usando C# – Guía paso a paso](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Aprenda a crear una forma rectangular en documentos Word con C# usando Aspose.Words paso a paso. | | [Tutorial de sombra de forma Aspose.Words – Agregar una sombra a una forma de Word en C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Aprenda a agregar sombras a formas en documentos de Word usando Aspose.Words para .NET con este tutorial paso a paso. | | [Crear documento Word en blanco con forma de rectángulo sombreada – Guía paso a paso](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Aprenda a crear un documento Word en blanco con una forma de rectángulo sombreada usando Aspose.Words para .NET. | +| [Cómo mover la sombra en Aspose.Words – Guía completa en C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Aprenda a mover la sombra de una forma en documentos Word usando Aspose.Words con C# paso a paso. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/spanish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..98e20b323a --- /dev/null +++ b/words/spanish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Cómo mover la sombra en una forma en Aspose.Words usando C#. Aprende + a agregar sombra a una forma, cambiar el desenfoque, establecer la transparencia + y rotar la sombra en minutos. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: es +og_description: Cómo mover la sombra en una forma en Aspose.Words usando C#. Este + tutorial muestra cómo agregar sombra a una forma, cambiar el desenfoque, establecer + la transparencia y rotar la sombra. +og_title: Cómo mover la sombra en Aspose.Words – Guía completa de C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Cómo mover la sombra en Aspose.Words – Guía completa en C# +url: /es/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo mover la sombra en Aspose.Words – Guía completa en C# + +¿Alguna vez te has preguntado **cómo mover la sombra** de una forma dentro de un documento Word sin abrir Word manualmente? En mi trabajo diario, a menudo he necesitado ajustar la sombra de una forma de forma programática—ya sea para un informe pulido o una plantilla dinámica. ¿La buena noticia? Con Aspose.Words puedes hacerlo en unas pocas líneas, y también aprenderás **añadir sombra a una forma**, **cómo cambiar el desenfoque**, **cómo establecer la transparencia** y **cómo rotar la sombra** en el mismo paso. + +En este tutorial recorreremos un escenario del mundo real: cargar un DOCX existente que ya contiene una forma, ajustar la posición, suavidad, opacidad y dirección de la sombra, y finalmente guardar el resultado. Al final tendrás un fragmento reutilizable que puedes insertar en cualquier proyecto .NET, y comprenderás por qué cada propiedad es importante. + +## Prerrequisitos – Lo que necesitas antes de comenzar + +- **Aspose.Words for .NET** (versión 23.12 o posterior). Puedes obtenerlo desde NuGet con `Install-Package Aspose.Words`. +- Un entorno de desarrollo .NET 6+ (Visual Studio, VS Code, Rider—lo que prefieras). +- Un archivo Word de entrada (`input.docx`) que ya contenga al menos una forma (un rectángulo, círculo o imagen sirve). +- Familiaridad básica con la sintaxis de C#—nada complicado. + +Si te falta alguno de estos, haz una pausa e instala la biblioteca; el resto de la guía asume que el paquete ya está referenciado. + +## Paso 1: Cargar el documento y obtener la forma objetivo – **Cómo mover la sombra** comienza aquí + +Lo primero que hacemos es cargar el documento fuente y localizar la forma que queremos modificar. Aspose.Words trata cada objeto (párrafos, tablas, formas) como un nodo en un árbol, por lo que podemos consultarlo directamente. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Por qué importa:** Cargar el documento una sola vez y reutilizar la misma instancia de `Document` es eficiente. La llamada a `GetChild` es segura porque devuelve `null` si el índice está fuera de rango, lo que nos permite manejar formas ausentes de forma elegante. + +## Paso 2: Ajustar el radio de desenfoque – Maestro **Cómo cambiar el desenfoque** + +Una sombra suave se ve profesional, mientras que un borde duro puede resultar barato. La propiedad `BlurRadius` controla la suavidad en puntos (1 pt ≈ 1/72 pulgada). Vamos a aumentarla a 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Consejo profesional:** El desenfoque predeterminado es 0.5 pt. Cualquier valor superior a 5 pt suele ser perceptible, pero ten cuidado de no hacerlo demasiado grande—puede hacer que la forma parezca desprendida de la página. + +## Paso 3: Establecer la transparencia – La respuesta a **Cómo establecer la transparencia** + +La transparencia determina cuán translúcida es la sombra. Un valor de `0` significa totalmente opaco; `1` significa completamente invisible. Para un efecto sutil usaremos `0.3` (30 % transparente). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Por qué te puede importar:** Si la forma es oscura, una sombra totalmente opaca puede ahogar el texto subyacente. Ajustar la transparencia mantiene el documento legible mientras sigue proporcionando profundidad. + +## Paso 4: Mover la sombra – El núcleo de **Cómo mover la sombra** + +La propiedad `Distance` define qué tan lejos está la sombra de la forma, medida en puntos. Una distancia mayor desplaza la sombra más lejos, creando un efecto más dramático. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **¿Qué pasa si necesitas un desplazamiento mínimo?** Establecer `Distance` a `0` hará que la sombra quede justo detrás de la forma, lo que puede ser útil para efectos de relieve. + +## Paso 5: Rotar la fuente de luz – Resolviendo **Cómo rotar la sombra** + +Las sombras no siempre van directamente hacia abajo; siguen el ángulo de la fuente de luz. La propiedad `Angle` (en grados) rota la sombra alrededor de la forma. Inclinémosla 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Experimento rápido:** Prueba `90` para una sombra a la derecha o `-30` para una inclinada a la izquierda. El cambio visual es inmediato. + +## Paso 6: Guardar el documento – Ver el resultado de **Añadir sombra a una forma** + +Ahora que hemos ajustado la sombra, escribiremos el documento de nuevo en disco. Puedes sobrescribir el original o crear un nuevo archivo; el ejemplo usa un archivo de salida nuevo. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Salida esperada:** Abre `output.docx`. La sombra de la forma aparecerá más suave, ligeramente desplazada, semi‑transparente y con un ángulo de 45°. Si la comparas lado a lado con `input.docx`, la diferencia es inconfundible. + +### Ejemplo completo (listo para copiar y pegar) + +A continuación tienes todo el programa en un solo bloque. Pégalo en un nuevo proyecto de consola, reemplaza `YOUR_DIRECTORY` con una ruta de carpeta real y ejecútalo. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si el documento tiene múltiples formas? + +Puedes iterar sobre todas las formas: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### ¿Puedo añadir una sombra a una forma que actualmente no tiene ninguna? + +Claro. El objeto `ShadowFormat` siempre está presente; solo necesitas habilitarlo: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### ¿Funciona con imágenes y SmartArt? + +Sí. Cualquier nodo que derive de `Shape`—incluyendo imágenes, gráficos y SmartArt—expondrá `ShadowFormat`. Las mismas propiedades se aplican. + +### ¿Cómo controlo el color de la sombra? + +Usa la propiedad `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### ¿Problemas de compatibilidad? + +Aspose.Words 23.12+ soporta .NET 6, .NET Core 3.1 y .NET Framework 4.6.2+. La API mostrada es estable en estas versiones. + +## Conclusión + +Acabamos de cubrir **cómo mover la sombra** de una forma usando Aspose.Words, y en el proceso también demostramos **añadir sombra a una forma**, **cómo cambiar el desenfoque**, **cómo establecer la transparencia** y **cómo rotar la sombra**. El ejemplo completo y ejecutable te permite ajustar la sombra de cualquier forma en cuestión de segundos, dando a tus documentos un aspecto pulido y profesional sin abrir Word. + +¿Listo para el siguiente paso? Prueba combinar estos ajustes de sombra con **formato condicional**—por ejemplo, aplicar una sombra más profunda solo a encabezados o a gráficos que superen cierto tamaño. O explora **rellenos degradados** para la propia forma y crea un diseño realmente llamativo. + +Si encuentras algún obstáculo, deja un comentario abajo. ¡Feliz codificación, y que tus sombras siempre caigan justo donde deseas! + +![Diagrama que muestra el efecto de mover una sombra en una forma – ejemplo de cómo mover la sombra](https://example.com/images/shadow-demo.png "ejemplo de cómo mover la sombra") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/basic-conversions/_index.md b/words/swedish/net/basic-conversions/_index.md index 3ad28c09d8..efd80b0199 100644 --- a/words/swedish/net/basic-conversions/_index.md +++ b/words/swedish/net/basic-conversions/_index.md @@ -36,6 +36,7 @@ Grundläggande konverteringar guidar dig genom grundläggande dokumentkonverteri | [Konvertera Word till PDF i C# med Aspose.Words – Guide](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Lär dig hur du konverterar Word-dokument till PDF i C# med Aspose.Words. Steg‑för‑steg‑guide med kodexempel. | | [Spara Word som PDF med Aspose.Words – Komplett C#-guide](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Lär dig hur du sparar Word-dokument som PDF med Aspose.Words i C#. Steg‑för‑steg‑guide med kodexempel. | | [Spara docx som PDF med Aspose.Words – Komplett C#-guide](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Lär dig hur du sparar DOCX-filer som PDF med Aspose.Words i C#. Steg‑för‑steg‑guide med kodexempel. | +| [Spara Word som PDF med Aspose.Words – Komplett guide](./save-word-as-pdf-with-aspose-words-complete-guide/) | Lär dig hur du sparar Word-dokument som PDF med Aspose.Words i en komplett guide med kodexempel. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/swedish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index 90bb3d09a4..891f2b801c 100644 --- a/words/swedish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/swedish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,24 +1,22 @@ --- category: general -date: 2025-12-29 -description: Hur man exporterar LaTeX från Word med Aspose.Words – lär dig konvertera - Word till LaTeX, spara docx som txt och hantera ekvationer i ren text. +date: 2026-05-01 +description: Lär dig hur du exporterar LaTeX från en Word‑fil, konverterar Word till + txt och bevarar tabeller med Aspose.Words i C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: sv -og_description: Hur man exporterar LaTeX från Word med Aspose.Words. Denna guide visar - hur du konverterar Word till LaTeX, sparar docx som txt och behåller ekvationerna - intakta. -og_title: Hur man exporterar LaTeX från Word – Snabb C#-handledning +og_description: Upptäck hur du exporterar LaTeX från Word, konverterar Word till ren + text och behåller tabellens layout intakt med Aspose.Words. +og_title: Hur man exporterar LaTeX från Word – Komplett C#‑handledning tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Hur man exporterar LaTeX från Word – Steg‑för‑steg‑guide url: /sv/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -28,178 +26,215 @@ url: /sv/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Så exporterar du LaTeX från Word – Steg‑för‑steg‑guide +# Så exporterar du LaTeX från Word – Komplett C#-handledning -Har du någonsin undrat **hur man exporterar LaTeX från Word** utan att förlora de knepiga Office Math‑ekvationerna? Du är inte ensam. Många utvecklare stöter på problem när de försöker *konvertera Word till LaTeX* för akademiska artiklar, vetenskapliga rapporter eller automatiserade publiceringspipelines. +Har du någonsin undrat **how to export LaTeX** från ett Word‑dokument utan att förlora några av matematikekvationerna? Du är inte ensam. Många utvecklare behöver omvandla en .docx som innehåller Office Math till ren LaTeX samtidigt som de **convert Word to txt** för efterföljande bearbetning. I den här guiden går vi igenom en praktisk, färdig‑att‑köra lösning som **preserves tables**, ger dig en ren textfil och behåller LaTeX‑markup exakt där du behöver den. -I den här handledningen går vi igenom ett komplett, färdigt C#‑exempel som visar **hur man exporterar LaTeX** med Aspose.Words, förklarar **hur man sparar txt**‑filer med LaTeX‑markup, och tar även upp nyanserna kring **convert word equations latex** så att inget går förlorat i översättningen. +Vi kommer att gå igenom allt från att läsa in källfilen till att justera `TxtSaveOptions` så att resultatet är både mänskligt läsbart och maskinvänligt. I slutet kommer du att kunna **save docx as txt**, **convert Word to plain text**, och veta **how to preserve tables** under exporten. Inga externa skript, ingen manuell kopiering‑och‑klistring—bara ren C#‑kod som du kan släppa in i vilket .NET‑projekt som helst. -> **Proffstips:** Samma metod fungerar för vilken .docx‑fil du har – peka bara koden mot en annan filsökväg. +## Vad du behöver + +- **Aspose.Words for .NET** (senaste versionen, 2024.x eller nyare). NuGet‑paketet är `Aspose.Words`. +- En .NET‑utvecklingsmiljö (Visual Studio, VS Code, Rider—vad som helst fungerar). +- En Word‑fil (`.docx`) som innehåller Office Math‑ekvationer och minst en tabell (så att vi kan se den tabell‑bevarande magin). + +Det är allt. Om du redan har dem, fortsätt läsa; annars hämta NuGet‑paketet och ett exempel‑DOCX innan vi dyker djupare. --- -## Vad du behöver +## Så exporterar du LaTeX från ett Word‑dokument -Innan vi dyker ner, se till att du har följande förutsättningar: +Nedan är kärnan i handledningen—tre koncisa steg som svarar på frågan **how to export latex** samtidigt som de hanterar de sekundära målen **convert word to txt**, **convert word to plain text**, **save docx as txt**, och **how to preserve tables**. -| Förutsättning | Varför det är viktigt | -|---------------|-----------------------| -| **.NET 6.0+** (eller .NET Framework 4.6+) | Aspose.Words riktar sig mot moderna .NET‑runtime. | -| **Aspose.Words for .NET** NuGet‑paket (`Aspose.Words`) | Biblioteket gör det tunga arbetet med att parsra Word och generera LaTeX. | -| **Ett exempel‑.docx** som innehåller minst en Office Math‑ekvation | För att se LaTeX‑konverteringen i aktion. | -| **Visual Studio 2022** (eller någon IDE du föredrar) | Gör felsökning och körning av exemplet enkelt. | +### Steg 1: Läs in DOCX‑filen -Om du ännu inte har installerat NuGet‑paketet, kör: +Först måste vi läsa in Word‑dokumentet i ett `Aspose.Words.Document`‑objekt. Detta steg är detsamma oavsett om du senare **convert word to txt** eller **save docx as txt**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -Det är allt – inga extra DLL‑filer, ingen COM‑interop, bara ett rent hanterat bibliotek. +> **Why this matters:** Att läsa in filen skapar en minnesrepresentation av alla Word‑element—paragrafer, tabeller och Office Math‑objekt. Utan detta objekt kan du inte manipulera exportalternativen. ---- +### Steg 2: Konfigurera `TxtSaveOptions` för LaTeX och tabelllayout -## Så exporterar du LaTeX från Word – Översikt +`TxtSaveOptions`‑klassen låter dig exakt styra hur ren‑text‑filen genereras. Två egenskaper är nyckeln för vårt scenario: -Nedan är den stora bilden av vad vi ska åstadkomma: +| Property | Vad den gör | Varför du behöver den | +|----------|--------------|-----------------------| +| `OfficeMathExportMode` | Bestämmer hur Office Math renderas. Att sätta den till `LaTeX` konverterar ekvationer till LaTeX‑syntax. | Detta är kärnan i **how to export latex**. | +| `PreserveTableLayout` | När `true` lägger Aspose till blanksteg så att tabeller behåller ett rutnätsliknande utseende. | Detta uppfyller **how to preserve tables** medan du **convert word to txt**. | -1. **Läs in** källdokumentet Word (`.docx`). -2. **Konfigurera** `TxtSaveOptions` så att alla Office Math‑objekt exporteras som LaTeX‑kod. -3. **Spara** dokumentet som en ren‑text (`.txt`)‑fil som du kan skicka direkt till någon LaTeX‑kompilator. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![How to export LaTeX from Word example](image.png "How to export LaTeX from Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro tip:** Om du bara behöver den råa LaTeX utan någon tabellformatering, sätt `PreserveTableLayout` till `false`. Filen blir mindre, men du förlorar den visuella tabellindikatorn. -## Steg 1: Läs in Word‑dokumentet +### Steg 3: Spara dokumentet som ren text -Först och främst – öppna .docx‑filen du vill konvertera. Klassen `Document` abstraherar bort all underliggande XML och ger dig en användarvänlig objektmodell. +Nu skriver vi dokumentet till en `.txt`‑fil med de alternativ vi just definierade. Denna enda rad utför **convert word to plain text**, **save docx as txt**, och naturligtvis **how to export latex** på en gång. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Varför detta är viktigt:** -Att läsa in filen tidigt låter oss inspektera dess innehåll (t.ex. räkna ekvationer) innan vi bestämmer hur vi ska serialisera den. Om filen är korrupt kastar `Document` ett tydligt undantag, vilket sparar dig från mystiska resultat senare. +När anropet är klart, öppna `output.txt`. Du kommer att se: ---- +- LaTeX‑snuttar som `\frac{a}{b}` för varje Office Math‑ekvation. +- Tabeller renderade med `|`‑ och `-`‑tecken, som bevarar kolumnjusteringen. +- Vanliga stycken som ren text, redo för vilken efterföljande parser som helst. -## Steg 2: Konfigurera TxtSaveOptions för LaTeX‑export +### Fullt fungerande exempel -Magin sker i `TxtSaveOptions`. Genom att sätta `OfficeMathExportMode` till `LaTeX` omvandlas varje Office Math‑objekt till sin motsvarande LaTeX‑representation. +Sätter vi ihop allt, här är ett självständigt program som du kan kompilera och köra idag: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Varför vi väljer dessa inställningar:** +**Förväntad output** (utdrag): -- `OfficeMathExportMode.LaTeX` är det enda läget som garanterar en trogen matematisk översättning. -- `PreserveTableLayout` behåller tabeller så de ser ut som i Word, vilket är praktiskt när du senare bäddar in resultatet i ett LaTeX‑`tabular`‑miljö. -- UTF‑8 säkerställer att tecken som “α”, “β” eller “∑” överlever rundresan. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Om du någonsin behöver **convert word to latex** utan txt‑omslag, kan du byta till `SaveFormat.LaTeX` istället – ett snabbt tips för avancerade scenarier. +Lägg märke till hur tabellen behåller sitt rutnät och ekvationen visas som ren LaTeX. Det är den perfekta balansen när du **convert word to txt** och fortfarande behöver en trogen representation av både struktur och matematik. --- -## Steg 3: Spara dokumentet som en textfil +## Tips för att konvertera Word till TXT och bevara tabeller -Nu skriver vi den LaTeX‑rika texten till disk. Den resulterande `.txt`‑filen kan senare döpas om till `.tex`, eller pipas direkt in i en LaTeX‑kompilator. +Även om tre‑stegs‑metoden fungerar för de flesta fall, kastar verkliga projekt ofta kurvbollar. Nedan följer praktiska förslag som gör din **convert word to plain text**‑pipeline robust. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Använd en konsekvent kodning -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` har UTF‑8 som standard, vilket hanterar de flesta tecken. Om du behöver en annan kodsida (t.ex. äldre system som förväntar Windows‑1252), sätt `Encoding`‑egenskapen: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Vad du kommer att se i `output.txt`:** +### Trimma överflödigt blanksteg -``` -\begin{equation} -E = mc^{2} -\end{equation} +Tabeller med många kolumner kan generera långa rader. Efter sparning kan du vilja efterbearbeta filen för att kollapsa flera mellanslag till ett enda tab‑tecken: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Alla andra stycken visas som vanlig text, medan varje Office Math‑ekvation omsluts av ett LaTeX‑`equation`‑miljö (eller `inline` om den var inline i Word). Detta uppfyller kravet **convert word equations latex** perfekt. +### Hantera nästlade tabeller ---- +Om ditt DOCX innehåller tabeller inuti tabeller, kommer `PreserveTableLayout` fortfarande behålla den visuella hierarkin, men indraget kan se konstigt ut. En snabb lösning är att ersätta inledande mellanslag med en anpassad markör (t.ex. `>>`) så att efterföljande parsers kan upptäcka nästlingsnivåer. -## Edge Cases & Vanliga frågor +### Batch‑bearbetning av flera filer -| Situation | Vad du gör | -|-----------|------------| -| **Inga ekvationer i källan** | Konverteringen fungerar ändå; du får bara ren text. Ingen extra LaTeX‑kod läggs till. | -| **Mycket stora dokument (>100 MB)** | Överväg att streama utdata med `MemoryStream` för att undvika hög minnesanvändning. | -| **Ej stödda matematiska konstruktioner** | Aspose.Words täcker 99 % av Office Math. För det sällsynta undantaget kan du behöva efterbearbeta LaTeX manuellt. | -| **Behöver en .tex‑fil istället för .txt** | Ändra `outputPath` så att den slutar på `.tex` och sätt eventuellt `txtOptions.Encoding` till `Encoding.UTF8`. | -| **Kör på Linux/macOS** | Samma kod fungerar – se bara till att filsökvägar använder framåtsnedstreck eller `Path.Combine`. | +När du behöver **convert word to txt** för dussintals dokument, slå in logiken i en loop: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +På så sätt kan du **save docx as txt** massivt utan manuell inblandning. -## Så sparar du TXT med LaTeX‑ekvationer – Snabb sammanfattning +--- -1. **Läs in** .docx‑filen (`Document`). -2. **Ställ in** `OfficeMathExportMode = LaTeX` i `TxtSaveOptions`. -3. **Spara** filen (`doc.Save`) med dessa alternativ. +## Vanliga fallgropar och hur du undviker dem -Det är hela arbetsflödet för **how to save txt**‑filer som innehåller LaTeX‑formaterade ekvationer. +1. **Missing LaTeX Export Mode** – Om du glömmer att sätta `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, kommer ekvationer att falla tillbaka till ren text (t.ex. “Equation 1”). Kontrollera alltid alternativblocket noggrant. +2. **Table Layout Gets Lost** – Att sätta `PreserveTableLayout` till `false` är standard. Om ditt resultat ser ut som en textvägg har du förmodligen inte växlat flaggan. +3. **File Paths with Spaces** – Att använda råa strängar (`@"C:\My Folder\input.docx"`) undviker escapingsproblem. Annars får du ett `FileNotFoundException`. +4. **Version Mismatch** – Äldre Aspose.Words‑versioner (< 21.9) stödjer inte `OfficeMathExportMode`. Uppgradera till det senaste paketet för att säkerställa att **how to export latex** fungerar. +5. **Encoding Errors for Non‑ASCII Characters** – Om du ser �‑symboler, sätt explicit `options.Encoding` till UTF‑8 eller rätt kodsida. --- -## Bonus: Automatisera konverteringen för flera filer +## Utöka lösningen: Från TXT till Markdown eller HTML -Om du har en mapp full av Word‑dokument, slå in logiken i en enkel loop: +Ibland behöver du mer än ren text—kanske en Markdown‑fil som fortfarande innehåller LaTeX‑block. Samma `TxtSaveOptions` kan bytas ut mot `HtmlSaveOptions` eller `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Nu kan du **convert word to latex** i bulk – perfekt för forskargrupper som får hand om dussintals manuskript dagligen. +Den lilla förändringen låter dig **convert word to txt**‑liknande output samtidigt som du behåller den markdown‑syntax du älskar. --- ## Slutsats -Vi har gått igenom **how to export LaTeX from Word** steg för steg, demonstrerat **how to save txt**‑filer som bevarar varje Office Math‑ekvation, och även visat hur du **convert word equations utan att förlora noggrannhet. +Vi har gått igenom ett komplett, produktionsklart svar på **how to export latex** från ett Word‑dokument, samtidigt som vi visade dig hur du **convert word to txt**, **convert word to plain text**, **save docx as txt**, och **how to preserve tables**. De viktigaste slutsatserna är: + +- Läs in DOCX med `Aspose.Words.Document`. +- Sätt `TxtSaveOptions.OfficeMathExportMode = LaTeX` och `PreserveTableLayout = true`. +- Anropa `doc.Save(outputPath, options)` för att få en ren LaTeX‑rik ren‑text‑fil. -Med bara några rader C# och det kraftfulla Aspose.Words‑biblioteket kan du förvandla vilken .docx som helst till LaTeX‑klar text, redo för inkludering i vetenskapliga artiklar, läroböcker eller automatiserade publiceringspipelines. +Prova det på dina egna filer, experimentera med kodningsjusteringar, och känn dig fri att batch‑processa hela mappar. Om du stöter på kantfall—nästlade tabeller, exotiska tecken eller äldre Aspose‑versioner—referera tillbaka till avsnitten “Tips” och “Fallgropar” för snabba lösningar. -**Nästa steg?** Prova att skicka den genererade `.txt`‑filen (eller döp om den till `.tex`) till `pdflatex` eller `xelatex` för att producera en PDF, eller utforska `SaveFormat.LaTeX`‑alternativet för en direkt `.tex`‑fil. Om du behöver **save docx as txt** samtidigt som du bevarar formatering, experimentera med `PreserveTableLayout` och egen radbrytningshantering. +Redo för nästa steg? Försök konvertera samma DOCX till Markdown, eller mata in den genererade `.txt` i en statisk webbplatsgenerator som renderar LaTeX på webben. Möjligheterna är oändliga, och nu har du en solid grund för vilket **convert word to txt**‑arbetsflöde som helst. -Har du frågor om edge cases, licensiering eller prestandajusteringar? Lägg en kommentar nedan – happy coding! +Lycklig kodning, och må din LaTeX alltid kompilera på första försöket! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/swedish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/swedish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..ac2a1a10fc --- /dev/null +++ b/words/swedish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-01 +description: Spara Word som PDF med Aspose.Words i C#. Lär dig konvertera docx till + PDF, upptäcka saknade teckensnitt och hantera varningar om teckensnittsbyte effektivt. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: sv +og_description: Spara Word som PDF med Aspose.Words. Denna steg‑för‑steg‑handledning + visar hur du konverterar docx till pdf och upptäcker saknade teckensnitt. +og_title: Spara Word som PDF med Aspose.Words – Komplett guide +tags: +- Aspose.Words +- C# +- PDF conversion +title: Spara Word som PDF med Aspose.Words – Komplett guide +url: /sv/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Spara Word som PDF med Aspose.Words – Komplett guide + +Har du någonsin behövt **spara Word som PDF** i farten och undrat om du skulle missa ett teckensnitt på vägen? Du är inte ensam—utvecklare kämpar ständigt med huvudvärk kring saknade teckensnitt när de konverterar dokument. I den här guiden går vi igenom en praktisk lösning som inte bara **konverterar docx till pdf** utan också **detekterar saknade teckensnitt** med hjälp av Aspose.Words varningsmeddelanden för teckensnittssubstitution. + +Vi täcker allt från att konfigurera varningssamlaren till att tolka resultatet, så i slutet vet du exakt hur du **sparar Word som PDF** utan överraskningar. Inga externa verktyg, inga kryptiska inställningar—bara ren C#-kod som du kan slänga in i vilket .NET-projekt som helst. + +## Vad du behöver + +- **Aspose.Words for .NET** (senaste versionen, t.ex. 24.10) – du kan hämta den via NuGet (`Install-Package Aspose.Words`). +- En .NET‑utvecklingsmiljö (Visual Studio, Rider eller VS Code fungerar bra). +- En exempel‑DOCX‑fil som kan innehålla teckensnitt som inte är installerade på målmaskinen. +Det är allt. Om du har dessa grunder är vi redo att dyka ner. + +## Spara Word som PDF – Steg‑för‑steg‑översikt + +Nedan är det fullständiga, körbara programmet. Kopiera och klistra in det i ett konsolapp‑projekt och tryck **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Proffstips:** Ersätt `YOUR_DIRECTORY` med en absolut sökväg eller använd `Path.Combine(Environment.CurrentDirectory, "input.docx")` för ett relativt, säkrare tillvägagångssätt. + +### Varför vi använder en varnings‑callback + +Aspose.Words ersätter tyst saknade teckensnitt med ett reservteckensnitt (vanligtvis Arial). Utan en callback skulle du aldrig veta att en ersättning skedde, vilket kan leda till layoutfel i den resulterande PDF‑filen. Genom att ansluta `IWarningCallback` får vi en tydlig, programmerbar lista över varje saknat‑teckensnitt‑händelse—perfekt för loggning eller för att meddela slutanvändare. + +### Detektera saknade teckensnitt – Vad du ska leta efter + +När du kör programmet kommer varje saknat teckensnitt att producera en konsollinje liknande: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Om listan är tom, grattis—**spara word som pdf** lyckades med alla ursprungliga teckensnitt intakta. + +## Konvertera Docx till PDF – Anpassa utdata + +Ibland behöver du en specifik PDF‑version, bildkvalitet eller efterlevnadsnivå. Aspose.Words låter dig justera `PdfSaveOptions`‑objektet innan du anropar `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Varför detta är viktigt:** Om du genererar PDF‑filer för juridiska arkiv säkerställer inställningen `PdfA1b` att filen uppfyller strikta standarder. Samma konvertering respekterar fortfarande vår varnings‑callback, så du kommer fortfarande **detektera saknade teckensnitt**. + +## Aspose Words teckensnittssubstitution – Hantera kantfall + +### Scenario 1: Flera saknade teckensnitt + +Om ditt källdokument använder flera anpassade teckensnitt kommer varningssamlaren att innehålla ett post per teckensnitt. Du kan samla dem: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Scenario 2: Tillhandahålla en reservteckensnittsmapp + +Aspose.Words kan söka i ytterligare mappar efter teckensnitt. Ställ in egenskapen `FontsFolder` på `FontSettings` innan du laddar dokumentet: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Nu kommer biblioteket att prova din anpassade mapp först, vilket minskar risken för oönskad ersättning. + +### Scenario 3: Ignorera ersättningar + +Om du föredrar att konverteringen ska misslyckas när ett teckensnitt saknas (istället för att tyst ersätta), kasta ett undantag i callback‑metoden: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Det tvingar dig att åtgärda det saknade teckensnittet innan du fortsätter—användbart i CI‑pipelines där tysta fel är oacceptabla. + +## Fullt end‑to‑end‑exempel + +När vi sätter ihop allt, här är en kompakt version som demonstrerar **hur man konverterar Word till PDF**, ställer in anpassade PDF‑alternativ och loggar eventuella teckensnittsproblem: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Förväntad konsolloutput** (om Calibri saknas): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Om inga varningar visas, har din **spara word som pdf**‑operation använt exakt samma teckensnitt som källdokumentet DOCX. + +## Visuell sammanfattning + +![Save Word as PDF workflow diagram](https://example.com/diagram.png "Save Word as PDF workflow") + +*Bildens alt‑text:* **save word as pdf** arbetsflöde som visar inläsning, varningssamling och PDF‑utdata. + +## Vanliga frågor & svar + +| Fråga | Svar | +|----------|--------| +| **Behöver jag en licens för Aspose.Words?** | En gratis evalueringslicens fungerar för testning, men produktionsanvändning kräver en betald licens för att ta bort evalueringsvattentecknet. | +| **Fungerar detta på .NET Core / .NET 6+?** | Absolut—Aspose.Words riktar sig mot .NET Standard 2.0, så någon nyare .NET‑runtime är kompatibel. | +| **Kan jag konvertera flera DOCX‑filer i en loop?** | Ja, bara skapa en ny `Document` för varje fil och återanvänd samma `WarningInfoCollector` om du vill ha aggregerade resultat. | +| **Vad händer om mål‑mappen inte finns?** | `Document.Save` kommer att kasta `DirectoryNotFoundException`. Skapa mappen först eller använd `Directory.CreateDirectory`. | +| **Finns det ett sätt att bädda in de saknade teckensnitten i PDF‑filen?** | Aspose.Words kan automatiskt bädda in teckensnitt om de finns på maskinen; sätt `PdfSaveOptions.EmbedFullFonts = true`. | + +## Slutsats + +Du har nu ett robust, produktionsklart mönster för att **spara Word som PDF** samtidigt som du **detekterar saknade teckensnitt** och hanterar **Aspose.Words teckensnittssubstitution**‑scenarier. Genom att fästa en varnings‑callback, anpassa teckensnittsmappar och eventuellt justera `PdfSaveOptions` kan du på ett pålitligt sätt **konvertera docx till pdf** och hålla dina användare informerade om eventuella teckensnittsproblem som kan påverka layoutens noggrannhet. + +Redo för nästa steg? Försök att generera PDF‑filer från flera dokument parallellt, eller utforska att lägga till vattenstämplar och digitala signaturer—båda är enkla utökningar av koden du just behärskar. Lycka till med kodandet, och må dina PDF‑filer alltid se exakt ut som avsett! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-loadoptions/_index.md b/words/swedish/net/programming-with-loadoptions/_index.md index 7398ff854d..37e5b501e3 100644 --- a/words/swedish/net/programming-with-loadoptions/_index.md +++ b/words/swedish/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ I dessa handledningar lär du dig hur du använder LoadOptions för att läsa in | [så här återställer du docx – ställ in återställningsläge & öppna korrupta Word-filer](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Lär dig hur du sätter återställningsläge och öppnar skadade Word-filer med Aspose.Words för .NET. | | [Så här använder du LoadOptions i Aspose.Words – Komplett guide](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Lär dig steg för steg hur du använder LoadOptions för att anpassa inläsning av Word-dokument med Aspose.Words för .NET. | | [Återställ skadat dokument i C# – Ställ in återställningsläge och fråga användaren](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Lär dig hur du återställer korrupta dokument i C# med återställningsläge och visar en prompt till användaren. | +| [Återställ korrupt docx – Fullständig guide för att ladda skadade Word-filer i C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Lär dig hur du laddar och reparerar korrupta docx-filer i C# med Aspose.Words för .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/swedish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..a049ca5283 --- /dev/null +++ b/words/swedish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Återställ korrupta docx-filer snabbt med Aspose.Words. Lär dig hur du + ställer in återställningsläge, laddar docx säkert och läser skadade Word-filer på + bara några steg. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: sv +og_description: Återställ korrupta docx-filer i C#. Ställ in återställningsläge, ladda + docx säkert och läs skadade Word-filer med Aspose.Words. +og_title: Återställ korrupt docx – Snabb C#-guide +tags: +- Aspose.Words +- C# +- Document Recovery +title: Återställ korrupt docx – Fullständig guide för att ladda skadade Word-filer + i C# +url: /sv/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Återställ korrupt docx – Snabb C#-guide + +Har du någonsin försökt öppna en Word‑fil som bara vägrade laddas och undrat om innehållet var förlorat för alltid? I många verkliga projekt kommer du att **recover corrupted docx** filer utan att be användaren att skicka om bilagan. Den goda nyheten är att Aspose.Words gör det till en barnlek: du sätter helt enkelt återställningsläget och låter biblioteket göra det tunga arbetet. + +I den här handledningen går vi igenom de exakta stegen för att **recover corrupted docx** filer, förklarar varför alternativet `RecoveryMode.AutoRecover` är det säkraste valet, och visar dig hur du **how to load docx** filer som kan vara delvis skadade. I slutet kommer du att kunna läsa en skadad Word‑fil, extrahera den text som överlevt och till och med logga det ursprungliga formatet för framtida granskningar. Inga externa verktyg, bara ren C#‑kod. + +## Vad du behöver + +- **Aspose.Words for .NET** (valfri ny version; API‑et vi använder fungerar med 23.5 och senare). +- En .NET‑utvecklingsmiljö (Visual Studio, VS Code eller Rider). +- Den korrupta eller delvis skadade `.docx` du vill rädda. + +Inga speciella behörigheter, ingen COM‑interop och inget behov av att installera Microsoft Office på servern. Enkelt, eller? + +## Steg 1: Ställ in återställningsläge till Auto‑Recover + +När en Word‑fil är trasig kastar standardladdningsbeteendet ett undantag och avbryter. Genom att konfigurera ett `LoadOptions`‑objekt talar du om för Aspose.Words att **set recovery mode** till `AutoRecover`, vilket skannar zip‑paketet, hoppar över oläsbara delar och returnerar allt den kan sätta ihop. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Varför AutoRecover?** +> Den försöker läsa så mycket som möjligt samtidigt som dokumentobjektet förblir användbart. Om du väljer `RecoveryMode.NoRecovery` kommer laddningen att misslyckas vid den första korruptionen, vilket undergräver syftet med **recover corrupted docx**‑scenarier. + +## Steg 2: Ladda dokumentet med de konfigurerade alternativen + +Nu när återställningsläget är satt kan du säkert försöka öppna filen. Ersätt `"YOUR_DIRECTORY/input.docx"` med den faktiska sökvägen till din skadade fil. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Om filen bara är delvis korrupt kommer `Document`‑instansen fortfarande att skapas. Du kan senare kontrollera `document.IsStructureValid` om du behöver extra validering. + +## Steg 3: Verifiera det upptäckta formatet + +Aspose.Words upptäcker automatiskt det ursprungliga formatet (DOC, DOCX, ODT, etc.). Att skriva ut detta värde hjälper dig bekräfta att biblioteket korrekt identifierade filen, vilket är en snabb kontroll efter en **recover corrupted docx**‑operation. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Typisk utskrift: + +``` +Loaded with Docx format. +``` + +Även om vissa delar saknades lyckas formatdetektionen fortfarande—en annan vinst för **recover corrupted docx**‑arbetsflöden. + +## Steg 4: Extrahera det du kan + +När dokumentet är laddat kan du behandla det som vilken hälsosam Word‑fil som helst. Nedan är ett kompakt exempel som extraherar ren text och skriver den till konsolen. Detta visar att du kan **read damaged word file** innehåll utan krascher. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Om den ursprungliga filen hade tabeller eller bilder som var korrupta kommer de helt enkelt att utelämnas från textutdata. Resten av dokumentet förblir intakt. + +## Steg 5: Spara en ren kopia (valfritt) + +Ofta vill du ge användaren en ny, ren version av filen efter återställning. Att spara med samma format säkerställer kompatibilitet med eventuella efterföljande processer. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Nu har du en **recover damaged docx** fil som du säkert kan bifoga i ett e‑postmeddelande eller skicka till en annan tjänst. + +## Fullständigt fungerande exempel + +Sätter vi ihop allt, här är det kompletta, färdiga programmet. Klistra in det i ett nytt konsolprojekt, justera filsökvägarna och tryck F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Förväntad utskrift** (förutsatt att filen innehåller ett enda stycke “Hello world!” och någon korrupt XML): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Observera hur programmet aldrig kraschar—trots att källfilen var delvis trasig. Det är kärnan i **recover corrupted docx** med Aspose.Words. + +## Vanliga frågor & specialfall + +### Vad händer om filen är helt oläsbar? + +Även `AutoRecover` har sina gränser. Om zip‑behållaren själv är så korrupt att den inte kan repareras, kommer Aspose.Words att kasta ett `CorruptedFileException`. I så fall kan du behöva ett tredjeparts‑verktyg för zip‑reparation innan du försöker **recover corrupted docx** igen. + +### Kan jag återställa andra format (t.ex. `.doc`, `.odt`)? + +Absolut. samma `LoadOptions` fungerar för alla format som Aspose.Words stödjer. Byt bara filändelsen så kommer biblioteket automatiskt att upptäcka det ursprungliga formatet. Det betyder att du också kan **recover damaged docx**‑liknande filer som `.doc` eller `.rtf` med identisk kod. + +### Hur hanterar jag stora dokument utan att ladda allt i minnet? + +För filer i gigabyte‑storlek kan du aktivera **load options** som `LoadOptions.LoadFormat` eller strömma dokumentet sida‑för‑sida. Återställningsalgoritmen måste dock fortfarande läsa hela paketet, så förvänta dig högre minnesanvändning för mycket stora korrupta filer. + +### Finns det ett sätt att veta vilka delar som gick förlorade? + +Efter laddning kan du inspektera `document.GetChildNodes(NodeType.Any, true)` och jämföra antalet med en förväntad baslinje. Saknade tabeller, bilder eller sidhuvuden kommer helt enkelt att saknas i nodsamlingen. Detta låter dig logga exakt vad som var **recover damaged docx** och informera användaren. + +## Pro‑tips för pålitlig återställning + +- **Validate the input file size** innan laddning; en noll‑byte fil kommer alltid att misslyckas. +- **Log the `RecoveryMode` result** genom att fånga `DocumentLoadingException` och lagra undantagsmeddelandet; det innehåller ofta ledtrådar om vilka delar som hoppades över. +- **Run the recovery on a background thread** om du bearbetar uppladdningar i en webbtjänst—detta håller förfrågan responsiv. +- **Combine with a checksum** (t.ex. MD5) för att upptäcka om den återställda filen skiljer sig från originalet; du kan då avgöra om du ska behålla båda versionerna. + +## Slutsats + +Vi har precis visat hur man **recover corrupted docx** filer i C# genom att **set recovery mode** till `AutoRecover`, ladda dokumentet säkert, extrahera den text som överlever och eventuellt spara en ren kopia. Detta tillvägagångssätt låter dig **how to load docx** filer som annars skulle kasta undantag, och ger dig ett pålitligt sätt att **read damaged word file** innehåll utan externa verktyg. + +Nästa steg? Prova att byta ut `RecoveryMode.AutoRecover` mot `RecoveryMode.NoRecovery` för att se skillnaden, eller experimentera med `LoadOptions`‑egenskaperna som styr lösenordshantering och teckensnittssubstitution. Du kan också integrera återställningsrutinen i ett ASP.NET Core‑API som accepterar uppladdningar och returnerar en reparerad fil—perfekt för företagsdokument‑hanteringspipelines. + +Har du fler frågor om återställning av Word‑dokument, eller vill du se hur man **recover damaged docx** filer med anpassade återanrop? Lämna en kommentar nedan, och lycka till med kodandet! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-markdownsaveoptions/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/_index.md index 57a9d3bdab..4bc068291c 100644 --- a/words/swedish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/swedish/net/programming-with-markdownsaveoptions/_index.md @@ -75,6 +75,12 @@ Lär dig spara DOCX som Markdown med en komplett C#‑guide som använder Aspose ### [Spara Word-bilder – Konvertera Word till Markdown med Aspose](./save-word-images-convert-word-to-markdown-with-aspose/) Lär dig spara bilder från Word och konvertera dokument till Markdown med Aspose.Words för .NET. +### [Spara docx as markdown – Exportera Word-matematik till LaTeX med Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) +Lär dig exportera matematiska ekvationer från Word till LaTeX när du sparar DOCX som Markdown med Aspose.Words. + +### [Ladda upp bilder till molnet när du konverterar Word till Markdown](./upload-images-to-cloud-when-converting-word-to-markdown/) +Lär dig hur du automatiskt laddar upp bilder till molnlagring under konvertering av Word-dokument till Markdown med Aspose.Words för .NET. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..2c0591ac17 --- /dev/null +++ b/words/swedish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-05-01 +description: spara docx som markdown med Aspose.Words – lär dig konvertera Word till + markdown, exportera ekvationer till LaTeX och ställ in bildupplösning i markdown + i ett smidigt arbetsflöde. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: sv +og_description: spara docx som markdown med Aspose.Words. Den här handledningen visar + hur du konverterar Word till markdown, exporterar ekvationer till LaTeX och ställer + in bildupplösning för markdown. +og_title: spara docx som markdown – fullständig guide för att exportera Word-matematik + som LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Spara docx som markdown – Exportera Word-matematik till LaTeX med Aspose.Words +url: /sv/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# spara docx som markdown – Exportera Word Math till LaTeX med Aspose.Words + +Har du någonsin behövt **save docx as markdown** men fastnat på hur du behåller Office Math‑ekvationerna skarpa? Du är inte ensam. De flesta utvecklare stöter på problem när standardkonverteringen gör om ekvationerna till suddiga bilder, vilket tvingar en manuell omskrivning i LaTeX. + +Bra nyheter: Aspose.Words kan göra det tunga arbetet åt dig. I den här handledningen kommer vi att **convert word to markdown**, be motorn att **export equations to latex**, och även **set markdown image resolution** för resten av dokumentet. I slutet har du ett enda kommando som genererar en ren `.md`‑fil med LaTeX‑klar matematik och högupplösta bilder. + +## Vad du kommer att lära dig + +- Hur du laddar en `.docx` som innehåller Office Math‑objekt. +- Vilka `MarkdownSaveOptions`‑egenskaper som styr **export equations to latex** och **set markdown image resolution**. +- Ett komplett, körbart C#‑exempel som du kan klistra in i vilket .NET‑projekt som helst. +- Tips för felsökning av vanliga fallgropar, som saknade typsnitt eller ej stödda ekvationsfunktioner. + +**Prerequisites**: .NET 6+ (eller .NET Framework 4.6+), en licens för Aspose.Words för .NET, och en grundläggande förtrogenhet med C#. Om du är bekväm med att skapa en konsolapp är du redo att köra. + +--- + +## Steg 1 – Save docx as markdown: Ladda din Word‑fil + +Det första vi behöver är ett `Document`‑objekt som pekar på käll‑`.docx`. Tänk på det som att öppna boken innan du börjar kopiera kapitel. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Varför detta är viktigt*: Om dokumentet inte innehåller någon matematik kommer steget **export equations to latex** att vara en ingen‑operation, men resten av konverteringen körs ändå. Kontrolleringen sparar dig från att undra varför ditt utdata‑Markdown saknar LaTeX‑block. + +## Steg 2 – Configure Export Equations to LaTeX + +Aspose.Words låter dig bestämma hur Office Math ska renderas. Som standard omvandlar det dem till PNG‑bilder, vilket är anledningen till att många handledningar slutar med en kornig markdown‑fil. Genom att byta `OfficeMathExportMode` till `LaTeX` får du rena, kopieringsklara ekvationer. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Varför `OfficeMathExportMode.LaTeX`?* LaTeX är det gemensamma språket för vetenskaplig publicering. När du senare renderar markdown med en static‑site‑generator eller en Jupyter‑notebook kommer ekvationerna att vara skarpa oavsett zoomnivå. + +## Steg 3 – Set Markdown Image Resolution (för icke‑matematikinnehåll) + +Även om vi fokuserar på matematik innehåller de flesta Word‑dokument också bilder, diagram eller inbäddade SVG‑filer. `ImageResolution`‑egenskapen styr hur Aspose.Words rasteriserar dessa resurser. Ett värde på **300 DPI** är en bra kompromiss för skärm och utskrift. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: Om ditt markdown bara ska visas på webben kan du sänka detta till 150 DPI för att minska filstorleken. Omvänt, för utskriftsklara PDF‑filer, höj det till 600 DPI. + +## Steg 4 – Run the Conversion – Convert Word Math LaTeX + +Nu när allt är konfigurerat är den faktiska konverteringen en enda rad. Aspose.Words gör det tunga arbetet bakom kulisserna. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: Öppna den genererade `.md`‑filen så bör du se något liknande: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Observera LaTeX‑blocken (`$...$` och `$$...$$`) som ersätter de tidigare PNG‑snuttarna. Bilden längst ner är fortfarande en PNG, renderad med 300 DPI som vi begärde. + +## Steg 5 – Common Edge Cases & How to Handle Them + +| Situation | Vad händer | Hur man fixar | +|-----------|------------|---------------| +| **Missing fonts** (t.ex. Cambria Math inte installerat) | LaTeX‑utdata kan innehålla okända symboler. | Installera det saknade typsnittet på servern eller bädda in det i dokumentet innan konvertering. | +| **Complex equations** (matris med anpassade avgränsare) | Aspose.Words kan falla tillbaka till en bild trots `LaTeX`‑läge. | Uppgradera till den senaste versionen av Aspose.Words; biblioteket förbättrar kontinuerligt ekvationsstöd. | +| **Large documents** ( > 50 MB ) | Minnetrycket kan orsaka `OutOfMemoryException`. | Använd `LoadOptions` med `LoadFormat.Docx` och strömma filen, eller dela upp dokumentet i sektioner innan konvertering. | +| **Image size too big** | Markdown‑filen blir enorm, vilket saktar ner static‑site‑byggen. | Sänk `ImageResolution` till 150 DPI för enbart webbscenarier (se Steg 3). | + +## Steg 6 – Put It All Together: Full Working Example + +Nedan är det *kompletta* konsol‑app‑programmet som du kan kopiera‑klistra in i `Program.cs`. Det innehåller alla delar vi diskuterat, plus lite extra felhantering. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Kör programmet (`dotnet run`) så får du en markdown‑fil som **save docx as markdown** samtidigt som varje ekvation bevaras som LaTeX. Ingen manuell kopiering, inga fula rasterbilder för matematik. + +## Slutsats + +Vi har gått igenom hela processen för **saving docx as markdown** med Aspose.Words, från att ladda Word‑filen till att konfigurera **export equations to latex** och **set markdown image resolution**. Den sista kodsnutten är produktionsklar, och du kan släppa in den i vilket .NET‑projekt som helst som behöver **convert word to markdown** i realtid. + +Vad blir nästa steg? Prova att mata in den genererade `.md`‑filen i en static‑site‑generator som Hugo eller Jekyll och se dina ekvationer renderas vackert. Om du behöver **convert word math latex** till andra format (PDF, HTML), byt bara `MarkdownSaveOptions` mot `PdfSaveOptions` eller `HtmlSaveOptions`—samma `OfficeMathExportMode`‑flagga fungerar för dem. + +Har du en variant i ditt arbetsflöde, som att hämta Word‑filer från Azure Blob‑lagring eller strömma dem från ett API? Samma mönster gäller; byt bara ut filsystem‑`Document`‑konstruktorn mot en ström‑baserad. + +Känn dig fri att experimentera, och låt oss veta i kommentarerna hur detta tillvägagångssätt löste dina konverteringsproblem. Lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..ef8587723f --- /dev/null +++ b/words/swedish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-05-01 +description: Ladda upp bilder till molnet medan du konverterar ett Word‑dokument till + markdown. Lär dig hur du extraherar bilder från docx och lagrar dem i Azure Blob‑lagring. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: sv +og_description: Ladda upp bilder till molnet medan du konverterar ett Word‑dokument + till markdown. Den här guiden visar hur du extraherar bilder från docx och lagrar + dem i Azure Blob Storage. +og_title: Ladda upp bilder till molnet när du konverterar Word till Markdown +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Ladda upp bilder till molnet när du konverterar Word till Markdown +url: /sv/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ladda upp bilder till molnet när du konverterar Word till Markdown + +Har du någonsin behövt **ladda upp bilder till molnet** medan du omvandlar en Word‑fil till markdown? Du är inte ensam – utvecklare jonglerar ständigt med dokumentkonvertering och resurshantering, och att göra båda i ett smidigt flöde kan kännas som att jaga ett rörligt mål. + +Den goda nyheten? Med Aspose.Words kan du extrahera varje bild, diagram eller figur från en .docx, skicka den direkt till Azure Blob Storage och låta den genererade markdown‑filen referera till dessa moln‑URL:er istället för lokala filer. I den här handledningen går vi igenom hela processen, från att läsa in källdokumentet till att få en ren markdown‑fil som pekar på din Azure‑behållare. + +När du är klar med guiden kommer du att kunna **konvertera docx till markdown**, **extrahera bilder från docx** och **lagra bilder i Azure Blob** – allt med bara några rader C#. Inga externa verktyg, ingen manuell kopiering‑och‑klistring och absolut inga trasiga bildlänkar. + +## Vad du behöver + +- **.NET 6.0** eller senare (koden fungerar även på .NET Core och .NET Framework) +- **Aspose.Words for .NET** (NuGet‑paket `Aspose.Words`) +- Ett **Azure Storage‑konto** med en behållare (t.ex. `images`) och en delad åtkomstnyckel – du behöver anslutningssträngen för att ladda upp filer. +- Grundläggande kunskap om C# och async/await (valfritt men hjälpsamt). + +Om du redan har dessa komponenter på plats, toppen – låt oss hoppa rakt in i lösningen. Om inte, pekar avsnittet “Förutsättningar” i slutet dig åt rätt håll för en snabb installation. + +## Steg 1: Skapa en Azure‑Blob‑hjälpare (Varför det är viktigt) + +Innan vi ens rör Word‑dokumentet behöver vi en liten hjälparklass som vet hur man skickar en byte‑array till Azure Blob Storage och returnerar en offentlig URL. Denna abstraktion håller konverteringslogiken ren och gör det enkelt att byta lagringsleverantör senare. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Varför den här hjälparen?** +1. **Separation av ansvar** – markdown‑konverteringskoden fokuserar på dokumenthantering, inte på HTTP‑detaljer. +2. **Återanvändbarhet** – du kan anropa `UploadAsync` var som helst i din app (t.ex. för användaruppladdade bilder). +3. **Framtidssäkerhet** – att byta till Amazon S3 eller Google Cloud Storage kräver bara en ny implementation av samma interface. + +> **Proffstips:** Ställ in behållarens åtkomstnivå till `Blob` (offentlig) endast om du är okej med att vem som helst kan läsa bilderna. För privata scenarier, generera SAS‑token per uppladdning och bädda in de URL‑erna istället. + +## Steg 2: Definiera en Resource‑Saving‑Callback (Kärnan i Upload‑while‑Convert) + +Aspose.Words låter dig fånga varje resurs (bild, diagram osv.) som normalt skulle skrivas till disk när du sparar ett dokument som markdown. Genom att tillhandahålla en `ResourceSavingCallback` kan vi ladda upp varje resurs till Azure Blob och ersätta det lokala filnamnet med moln‑URL:en. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Vad händer här?** + +- **Extrahera** – Aspose.Words ger oss en stream för varje bild. +- **Ladda upp** – Vi överlämnar den streamen till `AzureBlobUploader`. +- **Ersätt** – Markdown‑skrivaren får den offentliga URL:en och skriver in den i markdown‑bildsyntaxen (`![](https://…)`). + +Eftersom vi sätter `args.AlreadyExists = true` blir inga temporära filer kvar på filsystemet – en ren, tillståndslös operation som är perfekt för serverlösa funktioner. + +## Steg 3: Konfigurera Markdown‑Save‑Options (Knyt ihop allt) + +Nu väver vi in callback‑en i Aspose.Words `MarkdownSaveOptions`. De viktiga flaggorna är `ExportImagesAsBase64 = false` (så att vi får externa länkar) och `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Varför vi inaktiverar Base64?** +När `ExportImagesAsBase64` är true bäddar Aspose in varje bild direkt i markdown‑filen som en data‑URI. Det undergräver syftet med **ladda upp bilder till molnet** eftersom markdown‑filen blir onödigt stor och bilderna hålls gömda från CDN. Genom att stänga av det får vi rena, externa länkar som pekar på Azure Blob – exakt vad en modern static‑site‑generator förväntar sig. + +## Steg 4: Sätt ihop allt – En minimal konsolapp + +Nedan följer ett komplett, körklart konsolprogram. Byt ut platshållarna mot din faktiska Azure‑anslutningssträng och behållarnamn. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Förväntad output + +När du kör programmet med `sample.docx` som innehåller två bilder får du: + +- `output.md` som innehåller markdown‑bildsyntax så här: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-pdfsaveoptions/_index.md b/words/swedish/net/programming-with-pdfsaveoptions/_index.md index cd35c14a95..18bbf9eae7 100644 --- a/words/swedish/net/programming-with-pdfsaveoptions/_index.md +++ b/words/swedish/net/programming-with-pdfsaveoptions/_index.md @@ -28,7 +28,7 @@ Oavsett om du vill konvertera Word-dokument till PDF för onlinedistribution, ar | [Varningar för PDF-rendering](./pdf-render-warnings/) | Steg-för-steg-guide för att hantera varningar om PDF-rendering med Aspose.Words för .NET. | | [Lägg till digital signatur till PDF med hjälp av certifikatinnehavaren](./digitally-signed-pdf-using-certificate-holder/) | Säkra dina PDF-filer med en digital signatur med Aspose.Words för .NET. Följ den här steg-för-steg-guiden för att enkelt lägga till en digital signatur till dina PDF-filer. | | [Bädda in teckensnitt i PDF-dokument](./embedded-all-fonts/) | Bädda in teckensnitt i PDF-dokument utan problem med Aspose.Words för .NET med den här detaljerade steg-för-steg-guiden. Säkerställ ett enhetligt utseende på alla enheter. | -| [Bädda in delmängdsteckensnitt i PDF-dokument](./embedded-subset-fonts/) Minska PDF-filstorleken genom att endast bädda in nödvändiga teckensnittsdelmängder med Aspose.Words för .NET. Följ vår steg-för-steg-guide för att optimera dina PDF-filer effektivt. | +| [Bädda in delmängdsteckensnitt i PDF-dokument](./embedded-subset-fonts/) Minska PDF-filstorleken genom att endast bädda in nödvändiga teckensnittdelmängder med Aspose.Words för .NET. Följ vår steg-för-steg-guide för att optimera dina PDF-filer effektivt. | | [Minska PDF-storleken genom att inaktivera inbäddade teckensnitt](./disable-embed-windows-fonts/) | Minska PDF-storleken genom att inaktivera inbäddade teckensnitt med Aspose.Words för .NET. Följ vår steg-för-steg-guide för att optimera dina dokument för effektiv lagring och delning. | | [Optimera PDF-storleken med att hoppa över inbäddade Arial- och Times Roman-teckensnitt](./skip-embedded-arial-and-times-roman-fonts/) | Optimera PDF-storleken genom att hoppa över inbäddade Arial- och Times Roman-teckensnitt med Aspose.Words för .NET. Följ den här steg-för-steg-guiden för att effektivisera dina PDF-filer. | | [Minska PDF-filstorleken genom att inte bädda in kärnteckensnitt](./avoid-embedding-core-fonts/) | Lär dig hur du minskar PDF-filstorleken genom att inte bädda in kärnteckensnitt med Aspose.Words för .NET. Följ vår steg-för-steg-guide för att optimera dina PDF-filer. | @@ -50,6 +50,7 @@ Oavsett om du vill konvertera Word-dokument till PDF för onlinedistribution, ar | [Skapa tillgänglig PDF i C# – PDF-tillgänglighetstutorial](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Lär dig skapa tillgängliga PDF-filer i C# med Aspose.Words och följa WCAG-riktlinjer. | | [Skapa tillgänglig PDF från Word – Komplett guide](./create-accessible-pdf-from-word-complete-guide/) | Lär dig hur du skapar tillgängliga PDF-filer från Word-dokument med Aspose.Words för .NET i en komplett steg-för-steg-guide. | | [Skapa tillgänglig PDF – Steg‑för‑steg guide för PDF/UA‑efterlevnad](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Lär dig hur du skapar PDF-filer som uppfyller PDF/UA‑standarder för tillgänglighet med Aspose.Words för .NET. | +| [Spara dokument som pdf med Aspose.Words – Komplett C#-guide](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Lär dig hur du sparar ett dokument som PDF med Aspose.Words i en komplett C#-guide. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/swedish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..828fb016cc --- /dev/null +++ b/words/swedish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: Lär dig hur du sparar dokument som PDF med Aspose.Words i C#. Handledningen + täcker också hur du konverterar Word till PDF, exporterar matematiska LaTeX och + hanterar saknade teckensnitt. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: sv +og_description: Spara dokument som PDF utan ansträngning med Aspose.Words. Denna guide + visar också hur du konverterar Word till PDF, exporterar matematiska LaTeX och hanterar + saknade teckensnitt. +og_title: Spara dokument som PDF med Aspose.Words – Komplett C#‑guide +tags: +- Aspose.Words +- C# +- PDF generation +title: Spara dokument som PDF med Aspose.Words – Komplett C#‑guide +url: /sv/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Spara dokument som PDF med Aspose.Words – Komplett C#-guide + +Har du någonsin undrat **how to save document as pdf** direkt från en Word-fil utan att förlora tillgänglighetsfunktioner? Du är inte ensam—utvecklare frågar ständigt efter ett pålitligt sätt att konvertera Word till PDF samtidigt som matematiska ekvationer bevaras och saknade teckensnitt hanteras på ett smidigt sätt. + +I den här handledningen går vi igenom en steg‑för‑steg‑lösning som inte bara **save document as pdf** utan också demonstrerar **convert word to pdf**, **export math latex** och **handle missing fonts** med den senaste Aspose.Words för .NET. I slutet har du ett färdigt C#‑program som producerar PDF/UA‑2‑kompatibla filer, perfekta för tillgänglighetsgranskningar. + +## Vad du behöver + +- .NET 6 eller senare (koden fungerar även med .NET Core och .NET Framework) +- Aspose.Words för .NET 25.10 eller nyare – du kan hämta en gratis provversion från Aspose-webbplatsen +- Ett enkelt Word‑dokument (`input.docx`) som innehåller minst en flytande form och en matematisk ekvation (för att se export‑math‑latex‑funktionen i praktiken) +- Visual Studio 2022 (eller någon annan IDE du föredrar) + +> **Proffstips:** Om du använder en CI/CD‑pipeline, lägg till Aspose.Words NuGet‑paketet i din projektfil: + +```xml + +``` + +## Steg 1: Ladda källdokumentet med automatisk återställning + +När du arbetar med verkliga Word‑filer kan du stöta på korrupta sektioner eller saknade resurser. Genom att aktivera automatisk återställning säkerställer du att inläsningsprocessen aldrig kastar ett undantag. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Varför detta är viktigt:** +`RecoveryMode.AutoRecover` skyddar din pipeline från att krascha på felaktig indata, vilket är särskilt praktiskt när du **convert word to pdf** i stora mängder. + +## Steg 2: Konfigurera PDF‑spara‑alternativ för full tillgänglighet + +PDF/UA‑2 är ISO‑standarden för tillgängliga PDF‑filer. Genom att konfigurera några flaggor får vi en fil som skärmläsare kan navigera i, och vi ser också till att matematiska ekvationer exporteras som dold LaTeX. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – säkerställer att den resulterande PDF‑en bevarar den ursprungliga layouten samtidigt som den förblir semantiskt korrekt. +- **OfficeMathExportMode.LaTeX** – uppfyller kravet **export math latex**, vilket låter efterföljande verktyg extrahera ekvationerna vid behov. + +## Steg 3: Fånga varningar (t.ex. saknade teckensnitt) + +Saknade teckensnitt är ett vanligt huvudvärk när man konverterar dokument. Aspose.Words kan rapportera dessa problem via en `WarningCallback`. Vi samlar dem så att du kan logga eller agera på dem senare. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Varför du bryr dig:** +Om källan använder ett teckensnitt som inte är installerat på servern, kommer PDF‑en att falla tillbaka på ett standardteckensnitt, vilket kan förstöra layouten. Genom att **handle missing fonts** kan vi varna användaren eller bädda in ett ersättningsteckensnitt. + +## Steg 4: Spara dokumentet som en tillgänglig PDF + +Nu är det dags för sanningen—att faktiskt utföra konverteringen. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Om allt går smidigt får du en PDF/UA‑2‑fil som innehåller dold LaTeX för varje ekvation och korrekt taggning för flytande former. + +## Steg 5: Granska fångade varningar (valfritt men rekommenderat) + +Efter spara‑operationen kan du iterera över de samlade varningarna och logga dem. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Typical output might look like: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Att se dessa meddelanden tidigt hjälper dig att **handle missing fonts** innan de påverkar slutanvändarna. + +## Fullt fungerande exempel + +När vi sätter ihop allt, här är det kompletta, färdiga programmet. Ersätt platshållar‑sökvägarna med dina egna. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` uppfyller PDF/UA‑2‑kraven. +- Alla flytande former är taggade som inline‑figurer. +- Varje Office Math‑objekt visas som dold LaTeX (synligt när du inspekterar PDF‑ens struktur). +- Alla teckensnittsrelaterade problem skrivs ut till konsolen, vilket ger dig möjlighet att **handle missing fonts** innan filen levereras. + +![Diagram som visar flödet från Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flödesdiagram för att spara dokument som pdf") + +*Bildtext:* **Diagram över hur man sparar dokument som pdf med Aspose.Words** + +## Vanliga frågor & kantfall + +### Vad händer om jag använder en äldre version av Aspose.Words? + +`OfficeMathExportMode.LaTeX`‑flaggan introducerades i 25.10. För äldre versioner kan du fortfarande **convert word to pdf**, men matematiken kommer att rasteriseras istället för att exporteras som LaTeX. Uppgradera för bästa tillgänglighet. + +### Kan jag bädda in egna teckensnitt för att undvika fallback? + +Ja. Ställ in `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` innan du anropar `Save`. Detta hjälper också **handle missing fonts** genom att tvinga PDF‑en att innehålla de nödvändiga glyferna. + +### Hur verifierar jag PDF/UA‑2‑kompatibiliteten? + +Öppna filen i Adobe Acrobat Pro → “Print Production” → “Preflight”. Välj profilen “PDF/A‑2b” eller “PDF/UA‑2”; Acrobat kommer att rapportera eventuella avvikelser. + +### Vad händer med lösenordsskyddade Word‑filer? + +Läs in dokumentet med en `LoadOptions` som innehåller `Password`. Exempel: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Resten av pipeline‑processen förblir oförändrad. + +## Slutsats + +Vi har gått igenom allt du behöver för att **save document as pdf** med Aspose.Words i C#. Handledningen demonstrerade också hur man **convert word to pdf**, **export math latex** och **handle missing fonts**—allt medan du producerar en tillgänglig PDF/UA‑2‑fil. + +Kör koden, experimentera med olika `PdfSaveOptions` (t.ex. bildkomprimering, PDF/A‑2b), och integrera den i din dokument‑bearbetningstjänst. Om du vill gå längre, överväg att utforska Asposes PDF‑specifika bibliotek för efterbearbetning eller digitala signaturer. + +Har du fler scenarier du vill lösa? Känn dig fri att lämna en kommentar eller kolla in våra andra guider om **PDF manipulation**, **image extraction** och **batch conversion**. Lycka till med kodandet! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-shapes/_index.md b/words/swedish/net/programming-with-shapes/_index.md index 10bece39f4..031746299e 100644 --- a/words/swedish/net/programming-with-shapes/_index.md +++ b/words/swedish/net/programming-with-shapes/_index.md @@ -36,8 +36,8 @@ Genom att använda Aspose.Words för .NET och följa dessa handledningar kommer | [Skapa rektangelform i Word med Aspose.Words – Steg‑för‑steg‑guide](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Lär dig hur du skapar en rektangel i Word-dokument med Aspose.Words i en tydlig steg‑för‑steg‑guide. | | [Skapa rektangelform i Word med C# – Steg‑för‑steg‑guide](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Lär dig hur du skapar en rektangel i ett Word‑dokument med Aspose.Words för .NET och C# i denna detaljerade guide. | | [Aspose.Words-formskugga handledning – Lägg till en skugga på Word-form i C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Lär dig hur du lägger till en skugga på former i Word-dokument med Aspose.Words för .NET i C# med denna steg-för-steg-guide. | - | [Skapa tomt Word-dokument med skuggad rektangelform – steg‑för‑steg‑guide](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Lär dig hur du skapar ett tomt Word-dokument och lägger till en rektangelform med skugga med Aspose.Words för .NET. | +| [Hur du flyttar skugga i Aspose.Words – Komplett C#‑guide](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Lär dig hur du flyttar skuggan på former i Word-dokument med Aspose.Words för .NET i en komplett C#‑guide. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/swedish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..70d5ca90a7 --- /dev/null +++ b/words/swedish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Hur man flyttar skuggan på en form i Aspose.Words med C#. Lär dig att + lägga till skugga på en form, ändra oskärpa, ställa in transparens och rotera skuggan + på några minuter. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: sv +og_description: Hur man flyttar skugga på en form i Aspose.Words med C#. Denna handledning + visar hur du lägger till skugga på en form, ändrar oskärpa, ställer in transparens + och roterar skuggan. +og_title: Hur man flyttar skugga i Aspose.Words – Komplett C#-guide +tags: +- Aspose.Words +- C# +- Document Automation +title: Hur man flyttar skugga i Aspose.Words – Komplett C#‑guide +url: /sv/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Så flyttar du skugga i Aspose.Words – Komplett C#-guide + +Har du någonsin undrat **how to move shadow** på en form i ett Word‑dokument utan att öppna Word manuellt? I mitt dagliga arbete har jag ofta behövt justera en formes skugga programatiskt—oavsett om det är för en polerad rapport eller en dynamisk mall. Den goda nyheten? Med Aspose.Words kan du göra det på några få rader, och du kommer också att lära dig **add shadow to shape**, **how to change blur**, **how to set transparency**, och **how to rotate shadow** i samma steg. + +I den här handledningen går vi igenom ett verkligt scenario: att ladda en befintlig DOCX som redan innehåller en form, justera skuggans position, mjukhet, opacitet och riktning, och slutligen spara resultatet. I slutet har du ett återanvändbart kodsnutt som du kan klistra in i vilket .NET‑projekt som helst, och du kommer att förstå varför varje egenskap är viktig. + +## Förutsättningar – Vad du behöver innan du börjar + +- **Aspose.Words for .NET** (version 23.12 eller senare). Du kan hämta det från NuGet med `Install-Package Aspose.Words`. +- En .NET 6+ utvecklingsmiljö (Visual Studio, VS Code, Rider—vad du än föredrar). +- En inmatnings‑Word‑fil (`input.docx`) som redan innehåller minst en form (en rektangel, cirkel eller bild räcker). +- Grundläggande kunskap om C#‑syntax—inget avancerat. + +Om du saknar någon av dessa, pausa en stund och installera biblioteket; resten av guiden förutsätter att paketet redan är refererat. + +## Steg 1: Ladda dokumentet och hämta målformen – **How to Move Shadow** börjar här + +Det första vi gör är att ladda källdokumentet och hitta den form vi vill ändra. Aspose.Words behandlar varje objekt (paragrafer, tabeller, former) som en nod i ett träd, så vi kan fråga den direkt. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Varför detta är viktigt:** Att ladda dokumentet en gång och återanvända samma `Document`‑instans är effektivt. Anropet `GetChild` är säkert eftersom det returnerar `null` om indexet är utanför intervallet, vilket låter oss hantera saknade former på ett smidigt sätt. + +## Steg 2: Justera suddradie – Master **How to Change Blur** + +En mjuk skugga ser professionell ut, medan en hård kant kan kännas billig. Egenskapen `BlurRadius` styr mjukheten i punkter (1 pt ≈ 1/72 tum). Låt oss öka den till 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Proffstips:** Standardvärdet för sudd är 0,5 pt. Allt över 5 pt märks vanligtvis, men var försiktig så att du inte gör den för stor—det kan få formen att se fristående från sidan. + +## Steg 3: Ställ in transparens – Svaret på **How to Set Transparency** + +Transparens bestämmer hur genomskinlig skuggan är. Ett värde på `0` betyder helt ogenomskinlig; `1` betyder helt osynlig. För en subtil effekt använder vi `0.3` (30 % transparent). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Varför du kan bry dig:** Om formen är mörk kan en helt ogenomskinlig skugga dränka den underliggande texten. Genom att justera transparensen behåller du dokumentets läsbarhet samtidigt som du ger djup. + +## Steg 4: Flytta skuggan – Kärnan i **How to Move Shadow** + +`Distance`‑egenskapen definierar hur långt skuggan är förskjuten från formen, mätt i punkter. Ett större avstånd skjuter skuggan längre bort, vilket skapar en mer dramatisk effekt. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Vad om du behöver en liten förskjutning?** Att sätta `Distance` till `0` gör att skuggan sitter direkt bakom formen, vilket kan vara användbart för präglade effekter. + +## Steg 5: Rotera ljuskällan – Lösning på **How to Rotate Shadow** + +Skuggor är inte bara rakt ner; de följer ljuskällans vinkel. Egenskapen `Angle` (i grader) roterar skuggan runt formen. Låt oss luta den 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Snabbt experiment:** Prova `90` för en högerskugga eller `-30` för en vänstersläntrande. Den visuella förändringen är omedelbar. + +## Steg 6: Spara dokumentet – Se resultatet av **Add Shadow to Shape** + +Nu när vi har justerat skuggan skriver vi dokumentet tillbaka till disk. Du kan skriva över originalet eller skapa en ny fil; exemplet använder en ny utdatafil. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Förväntat resultat:** Öppna `output.docx`. Formens skugga kommer att vara mjukare, lätt förskjuten, semi‑transparent och vinklad 45°. Om du jämför sida‑vid‑sida med `input.docx` är skillnaden tydlig. + +### Fullt fungerande exempel (Klar att kopiera och klistra in) + +Nedan är hela programmet i ett block. Klistra in det i ett nytt konsolprojekt, ersätt `YOUR_DIRECTORY` med en faktisk mappväg, och kör. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Vanliga frågor & kantfall + +### Vad händer om dokumentet har flera former? + +Du kan loopa igenom alla former: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Kan jag lägga till en skugga på en form som för närvarande saknar någon? + +Absolut. `ShadowFormat`‑objektet finns alltid; du behöver bara aktivera det: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Fungerar detta med bilder och SmartArt? + +Ja. Alla noder som ärver från `Shape`—inklusive bilder, diagram och SmartArt—exponerar `ShadowFormat`. Samma egenskaper gäller. + +### Hur styr jag skuggans färg? + +Använd egenskapen `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Kompatibilitetsfrågor? + +Aspose.Words 23.12+ stödjer .NET 6, .NET Core 3.1 och .NET Framework 4.6.2+. API‑et som visas är stabilt över dessa versioner. + +## Slutsats + +Vi har just gått igenom **how to move shadow** på en form med Aspose.Words, och på vägen har vi också demonstrerat **add shadow to shape**, **how to change blur**, **how to set transparency** och **how to rotate shadow**. Det kompletta, körbara exemplet låter dig justera vilken form som helsts skugga på några sekunder, vilket ger dina dokument ett polerat, professionellt utseende utan att någonsin öppna Word. + +Redo för nästa steg? Prova att kombinera dessa skuggjusteringar med **conditional formatting**—till exempel, applicera bara en djupare skugga på rubriker eller diagram som överstiger en viss storlek. Eller utforska **gradient fills** för själva formen för att skapa en riktigt iögonfallande design. + +Om du stöter på problem, lämna en kommentar nedan. Lycka till med kodandet, och må dina skuggor alltid falla precis där du vill ha dem! + +![Diagram som visar effekten av att flytta en skugga på en form – exempel på hur man flyttar skugga](https://example.com/images/shadow-demo.png "exempel på hur man flyttar skugga") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/basic-conversions/_index.md b/words/thai/net/basic-conversions/_index.md index 1d9e196b04..3cb1ec2f95 100644 --- a/words/thai/net/basic-conversions/_index.md +++ b/words/thai/net/basic-conversions/_index.md @@ -26,6 +26,7 @@ Basic Conversions จะแนะนำคุณเกี่ยวกับก | [แปลงไฟล์ Word เป็น PDF](./docx-to-pdf/) เรียนรู้วิธีการแปลงไฟล์ Word เป็น PDF ได้อย่างง่ายดายโดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือของเรา เหมาะสำหรับนักพัฒนาที่ต้องการการแปลงเอกสารที่รวดเร็วและเชื่อถือได้ - - [แปลง Word เป็น PDF ใน C# ด้วย Aspose.Words – คู่มือ](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | เรียนรู้วิธีแปลงไฟล์ Word เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - - [บันทึก Word เป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | เรียนรู้วิธีบันทึกไฟล์ Word เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - +- [บันทึก Word เป็น PDF ด้วย Aspose.Words – คู่มือฉบับสมบูรณ์](./save-word-as-pdf-with-aspose-words-complete-guide/) | เรียนรู้วิธีบันทึกไฟล์ Word เป็น PDF ด้วย Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - - [บันทึก Docx เป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | เรียนรู้วิธีบันทึกไฟล์ Docx เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - | [แปลง Docx เป็นไบต์](./docx-to-byte/) | เรียนรู้วิธีการแปลง Docx เป็นอาร์เรย์ไบต์ใน .NET โดยใช้ Aspose.Words เพื่อการประมวลผลเอกสารอย่างมีประสิทธิภาพ มีคู่มือทีละขั้นตอนรวมอยู่ด้วย - | [แปลง Docx เป็น Epub](./docx-to-epub/) | แปลง DOCX เป็น EPUB ได้อย่างง่ายดายด้วย Aspose.Words สำหรับ .NET ทำตามบทช่วยสอนของเราเพื่อบูรณาการกับแอปพลิเคชัน .NET ของคุณได้อย่างราบรื่น - diff --git a/words/thai/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/thai/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index fb3ac1f634..7d2426328d 100644 --- a/words/thai/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/thai/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,25 +1,24 @@ --- category: general -date: 2025-12-29 -description: วิธีส่งออก LaTeX จาก Word ด้วย Aspose.Words – เรียนรู้การแปลง Word เป็น - LaTeX, บันทึกไฟล์ docx เป็น txt, และจัดการสมการในข้อความธรรมดา +date: 2026-05-01 +description: เรียนรู้วิธีส่งออก LaTeX จากไฟล์ Word, แปลง Word เป็น txt, และคงตารางไว้โดยใช้ + Aspose.Words ใน C# draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: th -og_description: วิธีส่งออก LaTeX จาก Word ด้วย Aspose.Words คู่มือนี้จะแสดงวิธีแปลง - Word เป็น LaTeX, บันทึกไฟล์ docx เป็น txt, และคงสมการไว้ครบถ้วน -og_title: วิธีส่งออก LaTeX จาก Word – บทเรียน C# อย่างรวดเร็ว +og_description: ค้นพบวิธีการส่งออก LaTeX จาก Word, แปลง Word เป็นข้อความธรรมดา, และคงรูปแบบตารางไว้โดยใช้ + Aspose.Words. +og_title: วิธีส่งออก LaTeX จาก Word – คอร์สสอน C# อย่างครบถ้วน tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: วิธีส่งออก LaTeX จาก Word – คู่มือขั้นตอนต่อขั้นตอน +title: วิธีส่งออก LaTeX จาก Word – คู่มือแบบทีละขั้นตอน url: /th/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -27,178 +26,213 @@ url: /th/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# วิธีการส่งออก LaTeX จาก Word – คู่มือขั้นตอน +# วิธีส่งออก LaTeX จาก Word – คำแนะนำ C# ฉบับสมบูรณ์ -เคยสงสัย **วิธีการส่งออก LaTeX จาก Word** โดยไม่สูญเสียสมการ Office Math ที่ซับซ้อนบ้างไหม? คุณไม่ได้เป็นคนเดียวที่เจอปัญหา นักพัฒนาหลายคนเจออุปสรรคเมื่อพยายาม *convert Word to LaTeX* สำหรับเอกสารวิชาการ รายงานวิทยาศาสตร์ หรือกระบวนการเผยแพร่อัตโนมัติ +เคยสงสัย **วิธีส่งออก LaTeX** จากเอกสาร Word โดยไม่สูญเสียสมการคณิตศาสตร์หรือไม่? คุณไม่ได้เป็นคนเดียว นักพัฒนาจำนวนมากต้องการแปลงไฟล์ .docx ที่มี Office Math ให้เป็น LaTeX ที่สะอาดพร้อมกับ **convert Word to txt** สำหรับการประมวลผลต่อไป ในคู่มือนี้เราจะพาคุณผ่านโซลูชันที่ใช้งานได้จริงและพร้อมรันที่ **preserves tables**, ให้ไฟล์ plain‑text และคงไว้ซึ่ง markup ของ LaTeX ตรงตามที่คุณต้องการ -ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่าง C# ที่สมบูรณ์และพร้อมใช้งาน ที่แสดง **วิธีการส่งออก LaTeX** ด้วย Aspose.Words, อธิบาย **วิธีการบันทึก txt** พร้อมมาร์กอัป LaTeX, และแม้กระทั่งครอบคลุมรายละเอียดของ **convert word equations latex** เพื่อให้ไม่มีอะไรสูญหายในการแปลง - -> **เคล็ดลับ:** วิธีเดียวกันทำงานกับไฟล์ .docx ใดก็ได้—เพียงแค่ชี้โค้ดไปยังเส้นทางไฟล์อื่น. - ---- +เราจะครอบคลุมทุกอย่างตั้งแต่การโหลดไฟล์ต้นฉบับจนถึงการปรับ `TxtSaveOptions` เพื่อให้ผลลัพธ์อ่านง่ายสำหรับมนุษย์และเป็นมิตรกับเครื่องจักร เมื่อเสร็จสิ้นคุณจะสามารถ **save docx as txt**, **convert Word to plain text**, และรู้ **how to preserve tables** ระหว่างการส่งออก ไม่ต้องใช้สคริปต์ภายนอก ไม่ต้องคัดลอก‑วางด้วยมือ—เพียงโค้ด C# แท้ที่คุณสามารถใส่ลงในโปรเจกต์ .NET ใดก็ได้ ## สิ่งที่คุณต้องการ -ก่อนที่เราจะเริ่มลงลึก โปรดตรวจสอบว่าคุณมีข้อกำหนดต่อไปนี้: - -| ความต้องการ | ทำไมจึงสำคัญ | -|--------------|----------------| -| **.NET 6.0+** (หรือ .NET Framework 4.6+) | Aspose.Words รองรับ .NET runtime รุ่นใหม่ | -| **Aspose NuGet package (`Aspose.Words`) | ไลบรารีนี้ทำหน้าที่หนักในการแยกวิเคราะห์ Word และสร้าง LaTeX | -| **ตัวอย่าง .docx** ที่มีสมการ Office Math อย่างน้อยหนึ่งสมการ | เพื่อดูการแปลง LaTeX ทำงานจริง | -| **Visual Studio 2022** (หรือ IDE ใดก็ได้ที่คุณชอบ) | ทำให้การดีบักและรันตัวอย่างเป็นเรื่องง่าย | - -หากคุณยังไม่ได้ติดตั้ง NuGet package ให้รัน: - -```bash -dotnet add package Aspose.Words -``` +- **Aspose.Words for .NET** (เวอร์ชันล่าสุด, 2024.x หรือใหม่กว่า) แพ็กเกจ NuGet คือ `Aspose.Words`. +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio, VS Code, Rider—ใช้ได้ทุกตัว) +- ไฟล์ Word (`.docx`) ที่มีสมการ Office Math และอย่างน้อยหนึ่งตาราง (เพื่อให้เห็นการรักษาตาราง) -เท่านั้น—ไม่มี DLL เพิ่มเติม, ไม่มี COM interop, เพียงไลบรารีที่จัดการอย่างสะอาด. +เท่านี้แค่นั้นเอง หากคุณมีแล้วให้อ่านต่อ; หากยังไม่มีให้ดาวน์โหลดแพ็กเกจ NuGet และไฟล์ DOCX ตัวอย่างก่อนที่เราจะดำเนินต่อ --- -## วิธีการส่งออก LaTeX จาก Word – ภาพรวม +## วิธีส่งออก LaTeX จากเอกสาร Word -ด้านล่างเป็นภาพรวมของสิ่งที่เราจะทำ: +ด้านล่างเป็นหัวใจของบทแนะนำ—สามขั้นตอนสั้น ๆ ที่ตอบคำถาม **how to export latex** พร้อมกับจัดการเป้าหมายรองของ **convert word to txt**, **convert word to plain text**, **save docx as txt**, และ **how to preserve tables**. -1. **Load** เอกสาร Word ต้นทาง (`.docx`). -2. **Configure** `TxtSaveOptions` เพื่อให้วัตถุ Office Math ทั้งหมดถูกส่งออกเป็นโค้ด LaTeX. -3. **Save** เอกสารเป็นไฟล์ plain‑text (`.txt`) ที่คุณสามารถส่งต่อโดยตรงไปยังคอมไพเลอร์ LaTeX ใดก็ได้. +### ขั้นตอน 1: โหลดไฟล์ DOCX -![ตัวอย่างการส่งออก LaTeX จาก Word](image.png "การส่งออก LaTeX จาก Word") - ---- - -## ขั้นตอนที่ 1: โหลดเอกสาร Word - -เริ่มต้น—เปิดไฟล์ .docx ที่คุณต้องการแปลง `Document` class จะทำการแยก XML พื้นฐานทั้งหมด ให้คุณได้โมเดลอ็อบเจกต์ที่ใช้งานง่าย +แรกเราต้องอ่านเอกสาร Word เข้าไปในอ็อบเจ็กต์ `Aspose.Words.Document` ขั้นตอนนี้เหมือนกันไม่ว่าคุณจะ **convert word to txt** หรือ **save docx as txt** ต่อไป ```csharp using Aspose.Words; using Aspose.Words.Saving; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -// Load the document into memory Document doc = new Document(inputPath); ``` -**ทำไมเรื่องนี้สำคัญ:** -การโหลดไฟล์ตั้งแต่แรกทำให้เราสามารถตรวจสอบเนื้อหา (เช่น จำนวนสมการ) ก่อนตัดสินใจว่าจะทำการซีเรียลไลซ์อย่างไร หากไฟล์เสียหาย `Document` จะโยนข้อยกเว้นที่ชัดเจน ช่วยคุณหลีกเลี่ยงผลลัพธ์ที่ไม่คาดคิดในภายหลัง. +> **ทำไมสิ่งนี้ถึงสำคัญ:** การโหลดไฟล์จะสร้างการแสดงผลในหน่วยความจำของทุกองค์ประกอบของ Word—ย่อหน้า, ตาราง, และอ็อบเจ็กต์ Office Math หากไม่มีอ็อบเจ็กต์นี้คุณจะไม่สามารถจัดการตัวเลือกการส่งออกได้ ---- +### ขั้นตอน 2: ตั้งค่า `TxtSaveOptions` สำหรับ LaTeX และการจัดรูปแบบตาราง -## ขั้นตอนที่ 2: ตั้งค่า TxtSaveOptions สำหรับการส่งออก LaTeX +คลาส `TxtSaveOptions` ให้คุณควบคุมอย่างแม่นยำว่ไฟล์ plain‑text จะถูกสร้างอย่างไร มีสองคุณสมบัติที่สำคัญสำหรับสถานการณ์ของเรา: -ความมหัศจรรย์เกิดขึ้นใน `TxtSaveOptions` โดยการตั้งค่า `OfficeMathExportMode` เป็น `LaTeX` ทุกวัตถุ Office Math จะถูกแปลงเป็นรูปแบบ LaTeX ที่สอดคล้อง +| Property | สิ่งที่ทำ | ทำไมคุณต้องการ | +|----------|-----------|-----------------| +| `OfficeMathExportMode` | กำหนดวิธีการแสดงผล Office Math การตั้งค่าเป็น `LaTeX` จะเปลี่ยนสมการเป็นไวยากรณ์ LaTeX | นี่คือหัวใจของ **how to export latex** | +| `PreserveTableLayout` | เมื่อเป็น `true` Aspose จะเพิ่มช่องว่างเพื่อให้ตารางคงลักษณะเป็นกริด | สิ่งนี้ตอบสนอง **how to preserve tables** ขณะคุณ **convert word to txt** | ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +TxtSaveOptions saveOptions = new TxtSaveOptions { - // Export Office Math equations as LaTeX strings + // Export all Office Math as LaTeX code OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 + + // Keep tables readable in the plain‑text output + PreserveTableLayout = true }; ``` -**ทำไมเราถึงเลือกการตั้งค่าเหล่านี้:** +> **เคล็ดลับ:** หากคุณต้องการเฉพาะ LaTeX ดิบโดยไม่มีการจัดรูปแบบตาราง ให้ตั้งค่า `PreserveTableLayout` เป็น `false` ไฟล์จะเล็กลง แต่คุณจะสูญเสียสัญญาณการแสดงตาราง -- `OfficeMathExportMode.LaTeX` เป็นโหมดเดียวที่รับประกันการแปลคณิตศาสตร์ที่แม่นยำ -- `PreserveTableLayout` ทำให้ตารางคงรูปร่างเหมือนใน Word ซึ่งสะดวกเมื่อคุณฝังผลลัพธ์ในสภาพแวดล้อม LaTeX `tabular` -- UTF‑8 ทำให้ตัวอักษรเช่น “α”, “β”, หรือ “∑” คงอยู่ตลอดการแปลง +### ขั้นตอน 3: บันทึกเอกสารเป็น Plain Text -หากคุณต้องการ **convert word to latex** โดยไม่ใช้ตัวห่อ plain‑text คุณสามารถสลับเป็น `SaveFormat.LaTeX` แทน—เป็นเคล็ดลับสั้น ๆ สำหรับสถานการณ์ขั้นสูง. +ตอนนี้เราจะเขียนเอกสารลงไฟล์ `.txt` โดยใช้ตัวเลือกที่เรากำหนดไว้บรรทัดเดียวนี้ทำให้สำเร็จ **convert word to plain text**, **save docx as txt**, และแน่นอน **how to export latex** พร้อมกัน ---- +```csharp +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; + +doc.Save(outputPath, saveOptions); +``` -## ขั้นตอนที่ 3: บันทึกเอกสารเป็นไฟล์ข้อความ +หลังจากคำสั่งทำงานเสร็จ ให้เปิด `output.txt` คุณจะเห็น: -ตอนนี้เราจะเขียนข้อความที่มี LaTeX ลงดิสก์ ไฟล์ `.txt` ที่ได้สามารถเปลี่ยนชื่อเป็น `.tex` ต่อมา หรือส่งต่อโดยตรงไปยังคอมไพเลอร์ LaTeX +- ชิ้นส่วน LaTeX เช่น `\frac{a}{b}` สำหรับทุกสมการ Office Math +- ตารางที่แสดงด้วยอักขระ `|` และ `-` รักษาการจัดแนวคอลัมน์ +- ย่อหน้าปกติเป็น plain text พร้อมใช้กับตัวแยกวิเคราะห์ต่อไป -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### ตัวอย่างการทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมที่สมบูรณ์แบบซึ่งคุณสามารถคอมไพล์และรันได้ทันที: -// Save using the configured options -doc.Save(outputPath, txtOptions); +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +class ExportLatexDemo +{ + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**สิ่งที่คุณจะเห็นใน `output.txt`:** +**ผลลัพธ์ที่คาดหวัง** (ส่วนย่อย): ``` -\begin{equation} -E = mc^{2} -\end{equation} +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} ``` -ย่อหน้าทั้งหมดอื่น ๆ จะปรากฏเป็นข้อความธรรมดา ในขณะที่สมการ Office Math ใด ๆ จะถูกห่อด้วยสภาพแวดล้อม LaTeX `equation` (หรือ `inline` หากเป็นอินไลน์ใน Word) สิ่งนี้ทำให้ข้อกำหนด **convert word equations latex** สำเร็จอย่างสมบูรณ์. +สังเกตว่าตารางยังคงกริดและสมการปรากฏเป็น LaTeX ที่สะอาด นี่คือจุดที่ลงตัวเมื่อคุณ **convert word to txt** และยังต้องการการแสดงผลที่แม่นยำของโครงสร้างและคณิตศาสตร์ --- -## กรณีขอบและคำถามทั่วไป +## เคล็ดลับสำหรับการแปลง Word เป็น TXT และการรักษาตาราง -| สถานการณ์ | วิธีทำ | -|-----------|------------| -| **ไม่มีสมการในแหล่งข้อมูล** | การแปลงยังคงทำงาน; คุณจะได้ข้อความธรรมดาเท่านั้น ไม่ได้เพิ่มโค้ด LaTeX ใด ๆ | -| **เอกสารขนาดใหญ่มาก (>100 MB)** | พิจารณา stream ผลลัพธ์โดยใช้ `MemoryStream` เพื่อลดการใช้หน่วยความจำสูง | -| **โครงสร้างคณิตศาสตร์ที่ไม่รองรับ** | Aspose.Words ครอบคลุม 99 % ของ Office Math สำหรับกรณีขอบที่หายาก คุณอาจต้อง post‑process LaTeX ด้วยตนเอง | -| **ต้องการไฟล์ .tex แทน .txt** | เปลี่ยน `outputPath` ให้ลงท้ายด้วย `.tex` และอาจตั้งค่า `txtOptions.Encoding` เป็น `Encoding.UTF8` | -| **รันบน Linux/macOS** | โค้ดเดียวกันทำงาน—แค่ตรวจสอบให้แน่ใจว่าเส้นทางไฟล์ใช้เครื่องหมายทับหน้า (`/`) หรือ `Path.Combine` | +แม้ว่าวิธีการสามขั้นตอนจะทำงานได้ในหลายกรณี แต่โครงการจริงมักมีความท้าทาย ด้านล่างเป็นข้อแนะนำเชิงปฏิบัติที่ทำให้กระบวนการ **convert word to plain text** ของคุณแข็งแรง ---- +### ใช้การเข้ารหัสที่สอดคล้องกัน -## วิธีบันทึก TXT พร้อมสมการ LaTeX – สรุปสั้น +`TxtSaveOptions` มีค่าเริ่มต้นเป็น UTF‑8 ซึ่งรองรับอักขระส่วนใหญ่ หากคุณต้องการหน้าโค้ดที่ต่างออกไป (เช่น ระบบเก่าที่คาดหวัง Windows‑1252) ให้ตั้งค่าคุณสมบัติ `Encoding`: -1. **Load** .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` ใน `TxtSaveOptions`. -3. **Save** ไฟล์ (`doc.Save`) ด้วยตัวเลือกเหล่านั้น. +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); +``` -นี่คือขั้นตอนทั้งหมดเพื่อ **how to save txt** ไฟล์ที่มีสมการรูปแบบ LaTeX +### ตัดช่องว่างส่วนเกิน ---- +ตารางที่มีหลายคอลัมน์อาจสร้างบรรทัดยาว หลังจากบันทึกคุณอาจต้องทำการประมวลผลต่อไฟล์เพื่อแปลงหลายช่องว่างเป็นแท็บเดียว: -## โบนัส: การทำอัตโนมัติการแปลงหลายไฟล์ +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); +``` -หากคุณมีโฟลเดอร์ที่เต็มไปด้วยไฟล์ Word ให้ใส่ตรรกะข้างต้นในลูปง่าย ๆ: +### จัดการตารางซ้อนกัน -```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; +หาก DOCX ของคุณมีตารางภายในตาราง `PreserveTableLayout` จะยังคงรักษาโครงสร้างภาพ แต่การเยื้องอาจดูแปลก การแก้ไขอย่างรวดเร็วคือการแทนที่ช่องว่างนำหน้าด้วยเครื่องหมายกำหนดเอง (เช่น `>>`) เพื่อให้ตัวแยกวิเคราะห์ต่อไปสามารถตรวจจับระดับการซ้อนกันได้ -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) -{ - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); +### การประมวลผลหลายไฟล์เป็นชุด + +เมื่อคุณต้องการ **convert word to txt** สำหรับหลายสิบเอกสาร ให้ใส่ตรรกะไว้ในลูป: - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); } ``` -ตอนนี้คุณสามารถ **convert word to latex** เป็นชุดได้—เหมาะสำหรับกลุ่มวิจัยที่ได้รับต้นฉบับหลายสิบฉบับต่อวัน. +ด้วยวิธีนี้คุณสามารถ **save docx as txt** จำนวนมากได้โดยไม่ต้องแทรกแซงด้วยมือ --- +## ข้อผิดพลาดทั่วไปและวิธีหลีกเลี่ยง + +1. **Missing LaTeX Export Mode** – หากคุณลืมตั้งค่า `OfficeMathExportMode = OfficeMathExportMode.LaTeX` สมการจะกลับเป็น plain text (เช่น “Equation 1”) ตรวจสอบตัวเลือกให้สองครั้งเสมอ +2. **Table Layout Gets Lost** – การตั้งค่า `PreserveTableLayout` เป็น `false` เป็นค่าเริ่มต้น หากผลลัพธ์ของคุณดูเหมือนกำแพงของข้อความ คุณอาจไม่ได้เปิดสวิตช์นี้ +3. **File Paths with Spaces** – การใช้ raw strings (`@"C:\My Folder\input.docx"`) จะหลีกเลี่ยงปัญหาการ escape มิฉะนั้นจะเกิด `FileNotFoundException` +4. **Version Mismatch** – เวอร์ชันเก่าของ Aspose.Words (< 21.9) ไม่รองรับ `OfficeMathExportMode` อัปเกรดเป็นแพ็กเกจล่าสุดเพื่อให้ **how to export latex** ทำงาน +5. **Encoding Errors for Non‑ASCII Characters** – หากคุณเห็นสัญลักษณ์ � ให้ตั้งค่า `options.Encoding` เป็น UTF‑8 หรือหน้าโค้ดที่เหมาะสมอย่างชัดเจน + +--- + +## การขยายโซลูชัน: จาก TXT ไปยัง Markdown หรือ HTML + +บางครั้งคุณต้องการมากกว่า plain text—อาจเป็นไฟล์ Markdown ที่ยังคงมีบล็อก LaTeX ตัวเลือก `TxtSaveOptions` เดียวกันสามารถเปลี่ยนเป็น `HtmlSaveOptions` หรือ `MarkdownSaveOptions` ได้: + +```csharp +var mdOptions = new MarkdownSaveOptions +{ + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); +``` + +การเปลี่ยนแปลงเล็ก ๆ นี้ทำให้คุณได้ผลลัพธ์สไตล์ **convert word to txt** พร้อมกับรักษาไวยากรณ์ markdown ที่คุณชอบ + ## สรุป -เราได้อธิบาย **how to export LaTeX from Word** อย่างเป็นขั้นตอน แสดง **how to save txt** ไฟล์ที่คงสมการ Office Mathสมการไว้ครบถ้วน และยังได้แสดงวิธี **convert word equations latex** โดยไม่สูญเสียความแม่นยำ +เราได้อธิบายวิธีที่ครบถ้วนและพร้อมใช้งานในระดับ production เพื่อ **how to export latex** จากเอกสาร Word พร้อมกับแสดงวิธี **convert word to txt**, **convert word to plain text**, **save docx as txt**, และ **how to preserve tables** สิ่งที่ควรจำคือ: + +- โหลดไฟล์ DOCX ด้วย `Aspose.Words.Document`. +- ตั้งค่า `TxtSaveOptions.OfficeMathExportMode = LaTeX` และ `PreserveTableLayout = true`. +- เรียก `doc.Save(outputPath, options)` เพื่อให้ได้ไฟล์ plain‑text ที่เต็มไปด้วย LaTeX อย่างสะอาด -ด้วยเพียงไม่กี่บรรทัดของ C# และไลบรารี Aspose.Words ที่ทรงพลัง คุณสามารถแปลง .docx ใดก็ได้เป็นข้อความพร้อมใช้กับ LaTeX เพื่อใส่ในงานวิจัย หนังสือเรียน หรือกระบวนการเผยแพร่อัตโนมัติ +ลองใช้กับไฟล์ของคุณเอง ทดลองปรับการเข้ารหัส และอย่าลังเลที่จะประมวลผลหลายโฟลเดอร์พร้อมกัน หากคุณเจอกรณีขอบ—ตารางซ้อนกัน, อักขระแปลก, หรือเวอร์ชัน Aspose เก่า—กลับไปดูส่วน “เคล็ดลับ” และ “ข้อผิดพลาดทั่วไป” เพื่อแก้ไขอย่างรวดเร็ว -**ขั้นตอนต่อไป?** ลองส่งไฟล์ `.txt` ที่สร้าง (หรือเปลี่ยนชื่อเป็น `.tex`) ไปยัง `pdflatex` หรือ `xelatex` เพื่อสร้าง PDF หรือสำรวจตัวเลือก `SaveFormat.LaTeX` สำหรับไฟล์ `.tex` โดยตรง หากคุณต้องการ **save docx as txt** พร้อมคงรูปแบบ ลองใช้ `PreserveTableLayout` และการจัดการการตัดบรรทัดแบบกำหนดเอง +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองแปลง DOCX เดียวกันเป็น Markdown หรือป้อน `.txt` ที่สร้างขึ้นไปยัง static‑site generator ที่แสดง LaTeX บนเว็บ ความเป็นไปได้ไม่มีที่สิ้นสุด และตอนนี้คุณมีพื้นฐานที่มั่นคงสำหรับกระบวนการ **convert word to txt** ใด ๆ -มีคำถามเกี่ยวกับกรณีขอบ, การให้สิทธิ์, หรือการปรับประสิทธิภาพ? แสดงความคิดเห็นด้านล่าง—ขอให้เขียนโค้ดอย่างสนุก! +ขอให้เขียนโค้ดอย่างสนุกสนาน และขอให้ LaTeX ของคุณคอมไพล์ได้สำเร็จตั้งแต่ครั้งแรก! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/thai/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/thai/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..d85dcc70ba --- /dev/null +++ b/words/thai/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,258 @@ +--- +category: general +date: 2026-05-01 +description: บันทึกไฟล์ Word เป็น PDF ด้วย Aspose.Words ใน C#. เรียนรู้การแปลงไฟล์ + docx เป็น PDF, ตรวจจับฟอนต์ที่หายไปและจัดการคำเตือนการแทนที่ฟอนต์อย่างมีประสิทธิภาพ. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: th +og_description: บันทึกไฟล์ Word เป็น PDF ด้วย Aspose.Words. บทแนะนำแบบทีละขั้นตอนนี้แสดงวิธีแปลงไฟล์ + docx เป็น pdf และตรวจจับฟอนต์ที่หายไป. +og_title: บันทึก Word เป็น PDF ด้วย Aspose.Words – คู่มือฉบับสมบูรณ์ +tags: +- Aspose.Words +- C# +- PDF conversion +title: บันทึกไฟล์ Word เป็น PDF ด้วย Aspose.Words – คู่มือฉบับสมบูรณ์ +url: /th/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# บันทึก Word เป็น PDF ด้วย Aspose.Words – คู่มือฉบับสมบูรณ์ + +เคยต้องการ **บันทึก Word เป็น PDF** อย่างรวดเร็วและสงสัยว่าคุณอาจพลาดฟอนต์บางตัวระหว่างทางหรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนาต่างเผชิญกับปัญหาฟอนต์หายเมื่อแปลงเอกสารอยู่เสมอ ในคู่มือนี้เราจะพาคุณผ่านโซลูชันแบบทำมือที่ไม่เพียง **แปลง docx เป็น pdf** แต่ยัง **ตรวจจับฟอนต์ที่หายไป** ด้วยคำเตือนการแทนที่ฟอนต์ของ Aspose.Words + +เราจะครอบคลุมทุกอย่างตั้งแต่การตั้งค่า warning collector ไปจนถึงการตีความผลลัพธ์ ดังนั้นเมื่อจบคุณจะรู้วิธี **บันทึก Word เป็น PDF** อย่างแม่นยำโดยไม่มีเซอร์ไพรส์ ไม่มีเครื่องมือภายนอก ไม่มีการตั้งค่าที่ซับซ้อน—เพียงโค้ด C# สะอาดที่คุณสามารถใส่ลงในโปรเจกต์ .NET ใดก็ได้ + +## สิ่งที่คุณต้องการ + +- **Aspose.Words for .NET** (เวอร์ชันล่าสุด เช่น 24.10) – คุณสามารถดาวน์โหลดได้ผ่าน NuGet (`Install-Package Aspose.Words`). +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio, Rider หรือ VS Code ใช้งานได้ดี). +- ไฟล์ DOCX ตัวอย่างที่อาจมีฟอนต์ที่ไม่ได้ติดตั้งบนเครื่องเป้าหมาย. +เท่านี้เอง หากคุณมีพื้นฐานเหล่านี้ เราพร้อมจะเริ่มลงมือ. + +## บันทึก Word เป็น PDF – ภาพรวมขั้นตอนโดยขั้นตอน + +ด้านล่างเป็นโปรแกรมเต็มที่สามารถรันได้ คุณสามารถคัดลอกและวางลงในโปรเจกต์แอปคอนโซลและกด **F5** ได้เลย. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **เคล็ดลับระดับมืออาชีพ:** แทนที่ `YOUR_DIRECTORY` ด้วยพาธแบบเต็มหรือใช้ `Path.Combine(Environment.CurrentDirectory, "input.docx")` สำหรับพาธแบบสัมพันธ์ที่ปลอดภัยกว่า. + +### ทำไมเราจึงใช้ Warning Callback + +Aspose.Words จะทำการแทนที่ฟอนต์ที่หายไปโดยอัตโนมัติด้วยฟอนต์สำรอง (โดยทั่วไปคือ Arial) หากไม่มี callback คุณจะไม่รู้ว่าการแทนที่เกิดขึ้น ซึ่งอาจทำให้เกิดข้อบกพร่องของเลย์เอาต์ใน PDF ที่ได้ โดยการเชื่อมต่อ `IWarningCallback` เราจะได้รายการที่ชัดเจนและเป็นโปรแกรมของเหตุการณ์ฟอนต์ที่หายไปทุกครั้ง—เหมาะสำหรับการบันทึกหรือแจ้งผู้ใช้ปลายทาง + +### ตรวจจับฟอนต์ที่หายไป – สิ่งที่ควรสังเกต + +เมื่อคุณรันโปรแกรม ฟอนต์ที่หายไปใด ๆ จะสร้างบรรทัดในคอนโซลที่คล้ายกับ: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +หากรายการว่างเปล่า ยินดีด้วย—การ **บันทึก word เป็น pdf** สำเร็จโดยฟอนต์เดิมทั้งหมดยังคงอยู่. + +## แปลง Docx เป็น PDF – ปรับแต่งผลลัพธ์ + +บางครั้งคุณต้องการเวอร์ชัน PDF เฉพาะ, คุณภาพภาพ, หรือระดับการปฏิบัติตามมาตรฐาน Aspose.Words ให้คุณปรับ `PdfSaveOptions` ก่อนเรียก `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **ทำไมเรื่องนี้สำคัญ:** หากคุณกำลังสร้าง PDF สำหรับคลังเอกสารทางกฎหมาย การตั้งค่า `PdfA1b` จะทำให้ไฟล์ตรงตามมาตรฐานที่เข้มงวด การแปลงเดียวกันนี้ยังคงเคารพ warning callback ของเรา ดังนั้นคุณยังคง **ตรวจจับฟอนต์ที่หายไป**. + +## การแทนที่ฟอนต์ของ Aspose Words – การจัดการกรณีขอบ + +### สถานการณ์ 1: ฟอนต์ที่หายหลายตัว + +หากเอกสารต้นฉบับของคุณใช้ฟอนต์แบบกำหนดเองหลายตัว ตัวเก็บ warning จะมีรายการหนึ่งรายการต่อฟอนต์ คุณสามารถรวมกันได้: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### สถานการณ์ 2: การระบุโฟลเดอร์ฟอนต์สำรอง + +Aspose.Words สามารถค้นหาโฟลเดอร์เพิ่มเติมสำหรับฟอนต์ได้ ตั้งค่า property `FontsFolder` บน `FontSettings` ก่อนโหลดเอกสาร: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +ตอนนี้ไลบรารีจะลองโฟลเดอร์ที่คุณกำหนดก่อน ลดความเป็นไปได้ของการแทนที่ที่ไม่ต้องการ. + +### สถานการณ์ 3: การละเว้นการแทนที่ + +หากคุณต้องการให้การแปลงล้มเหลวเมื่อฟอนต์หาย (แทนที่จะทำการแทนที่โดยเงียบ) ให้โยนข้อยกเว้นภายใน callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +สิ่งนี้บังคับให้คุณจัดการฟอนต์ที่หายก่อนดำเนินการต่อ—มีประโยชน์ใน pipeline CI ที่ไม่ยอมรับความล้มเหลวแบบเงียบ. + +## ตัวอย่างเต็มแบบ End‑to‑End + +เมื่อรวมทุกอย่างเข้าด้วยกัน นี่คือเวอร์ชันกระชับที่แสดง **วิธีแปลง Word เป็น PDF**, ตั้งค่าตัวเลือก PDF แบบกำหนดเอง, และบันทึกปัญหาฟอนต์ใด ๆ: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**ผลลัพธ์คอนโซลที่คาดหวัง** (หาก Calibri หาย): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +หากไม่มีคำเตือนปรากฏ การดำเนินการ **บันทึก word เป็น pdf** ของคุณใช้ฟอนต์เดียวกับ DOCX ต้นฉบับอย่างตรงกัน. + +## สรุปภาพรวม + +![แผนภาพการทำงานบันทึก Word เป็น PDF](https://example.com/diagram.png "การทำงานบันทึก Word เป็น PDF") + +*ข้อความแทนภาพ:* **save word as pdf** workflow แสดงการโหลด, การเก็บ warning, และการสร้าง PDF. + +## คำถามที่พบบ่อย & คำตอบ + +| คำถาม | คำตอบ | +|----------|--------| +| **ฉันต้องการไลเซนส์สำหรับ Aspose.Words หรือไม่?** | ไลเซนส์ทดลองฟรีใช้งานได้สำหรับการทดสอบ แต่การใช้งานในสภาพแวดล้อมจริงต้องมีไลเซนส์แบบชำระเงินเพื่อเอาน้ำลายน้ำการทดลองออก. | +| **วิธีนี้จะทำงานบน .NET Core / .NET 6+ หรือไม่?** | แน่นอน—Aspose.Words รองรับ .NET Standard 2.0 ดังนั้นรันไทม์ .NET ใด ๆ ที่ใหม่ก็เข้ากันได้. | +| **ฉันสามารถแปลงไฟล์ DOCX หลายไฟล์ในลูปได้หรือไม่?** | ได้ เพียงสร้าง `Document` ใหม่สำหรับแต่ละไฟล์และใช้ `WarningInfoCollector` เดียวกันหากต้องการผลรวม. | +| **ถ้าโฟลเดอร์ปลายทางไม่มีอยู่จะทำอย่างไร?** | `Document.Save` จะโยน `DirectoryNotFoundException`. สร้างโฟลเดอร์ก่อนหรือใช้ `Directory.CreateDirectory`. | +| **มีวิธีใดที่จะฝังฟอนต์ที่หายไปลงใน PDF หรือไม่?** | Aspose.Words สามารถฝังฟอนต์โดยอัตโนมัติหากฟอนต์นั้นมีบนเครื่อง; ตั้งค่า `PdfSaveOptions.EmbedFullFonts = true`. | + +## สรุป + +ตอนนี้คุณมีรูปแบบที่มั่นคงและพร้อมใช้งานในสภาพแวดล้อมการผลิตเพื่อ **บันทึก Word เป็น PDF** พร้อมกับ **ตรวจจับฟอนต์ที่หายไป** และจัดการกับสถานการณ์ **การแทนที่ฟอนต์ของ Aspose.Words** ด้วยการเชื่อมต่อ warning callback, ปรับโฟลเดอร์ฟอนต์, และปรับ `PdfSaveOptions` ตามต้องการ คุณสามารถ **แปลง docx เป็น pdf** อย่างเชื่อถือได้และแจ้งผู้ใช้เกี่ยวกับปัญหาฟอนต์ใด ๆ ที่อาจส่งผลต่อความแม่นยำของเลย์เอาต์. + +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองสร้าง PDF จากหลายเอกสารพร้อมกัน, หรือสำรวจการเพิ่มลายน้ำและลายเซ็นดิจิทัล—ทั้งสองเป็นส่วนขยายที่ง่ายของโค้ดที่คุณเพิ่งเรียนรู้ ขอให้เขียนโค้ดอย่างสนุกสนานและ PDF ของคุณดูตรงตามที่ต้องการเสมอ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-loadoptions/_index.md b/words/thai/net/programming-with-loadoptions/_index.md index 383ec123c1..afb3c337ca 100644 --- a/words/thai/net/programming-with-loadoptions/_index.md +++ b/words/thai/net/programming-with-loadoptions/_index.md @@ -39,6 +39,7 @@ | [วิธีกู้คืนไฟล์ DOCX – ตั้งค่าโหมดการกู้คืนและเปิดไฟล์ Word ที่เสียหาย](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | เรียนรู้วิธีตั้งค่าโหมดการกู้คืนและเปิดไฟล์ Word ที่เสียหายด้วย Aspose.Words สำหรับ .NET | | [วิธีใช้ LoadOptions ใน Aspose.Words – คู่มือฉบับสมบูรณ์](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | เรียนรู้วิธีใช้ LoadOptions อย่างเต็มที่ใน Aspose.Words สำหรับ .NET ด้วยคู่มือที่ครอบคลุมขั้นตอนและตัวอย่างโค้ด | | [กู้คืนเอกสารเสียหายใน C# – ตั้งค่าโหมดการกู้คืนและแจ้งผู้ใช้](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | เรียนรู้วิธีกู้คืนเอกสาร Word ที่เสียหายใน C# ด้วยการตั้งค่าโหมดการกู้คืนและแจ้งผู้ใช้ | +| [กู้ไฟล์ docx ที่เสีย – คู่มือเต็มสำหรับการโหลดไฟล์ Word ที่เสียใน C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | เรียนรู้วิธีกู้ไฟล์ docx ที่เสียและโหลดไฟล์ Word ที่เสียใน C# ด้วย Aspose.Words อย่างละเอียด | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/thai/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..9af160f17f --- /dev/null +++ b/words/thai/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-01 +description: กู้คืนไฟล์ docx ที่เสียหายอย่างรวดเร็วด้วย Aspose.Words เรียนรู้วิธีตั้งค่าโหมดการกู้คืน + โหลดไฟล์ docx อย่างปลอดภัย และอ่านไฟล์ Word ที่เสียหายในไม่กี่ขั้นตอน +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: th +og_description: กู้ไฟล์ docx ที่เสียหายใน C# ตั้งค่าโหมดการกู้คืน โหลด docx อย่างปลอดภัย + และอ่านไฟล์ Word ที่เสียหายด้วย Aspose.Words. +og_title: กู้ไฟล์ docx ที่เสียหาย – คู่มือ C# อย่างรวดเร็ว +tags: +- Aspose.Words +- C# +- Document Recovery +title: กู้คืนไฟล์ docx ที่เสียหาย – คู่มือเต็มสำหรับการโหลดไฟล์ Word ที่เสียใน C# +url: /th/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# กู้ไฟล์ docx ที่เสีย – คู่มือสั้น C# + +เคยลองเปิดไฟล์ Word ที่ไม่โหลดเลยและสงสัยว่าข้อมูลสูญหายไปตลอดหรือไม่? ในหลายโครงการจริง ๆ คุณจะ **recover corrupted docx** ไฟล์โดยไม่ต้องขอให้ผู้ใช้ส่งไฟล์แนบใหม่ ข่าวดีคือ Aspose.Words ทำให้เรื่องนี้ง่ายมาก: เพียงตั้งค่า recovery mode แล้วให้ไลบรารีทำงานที่เหลือ + +ในบทแนะนำนี้เราจะอธิบายขั้นตอนที่แน่นอนเพื่อ **recover corrupted docx** ไฟล์, อธิบายว่าทำไมตัวเลือก `RecoveryMode.AutoRecover` จึงเป็นตัวเลือกที่ปลอดภัยที่สุด, และแสดงวิธี **how to load docx** ไฟล์ที่อาจเสียบางส่วน. เมื่อเสร็จคุณจะสามารถอ่านไฟล์ Word ที่เสีย, ดึงข้อความที่เหลืออยู่, และบันทึกรูปแบบเดิมเพื่อการตรวจสอบในอนาคต. ไม่ต้องใช้เครื่องมือภายนอก, เพียงโค้ด C# ที่สะอาด + +## สิ่งที่คุณต้องเตรียม + +- **Aspose.Words for .NET** (เวอร์ชันล่าสุดใดก็ได้; API ที่เราใช้ทำงานกับ 23.5 ขึ้นไป). +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio, VS Code, หรือ Rider). +- ไฟล์ `.docx` ที่เสียหรือเสียบางส่วนที่คุณต้องการกู้คืน. + +ไม่ต้องการสิทธิพิเศษ, ไม่ต้องใช้ COM interop, และไม่ต้องติดตั้ง Microsoft Office บนเซิร์ฟเวอร์. ง่ายใช่ไหม? + +## ขั้นตอนที่ 1: ตั้งค่า Recovery Mode เป็น Auto‑Recover + +เมื่อไฟล์ Word มีปัญหา, พฤติกรรมการโหลดเริ่มต้นจะโยนข้อยกเว้นและหยุดทำงาน. โดยการกำหนดวัตถุ `LoadOptions` คุณบอก Aspose.Words ให้ **set recovery mode** เป็น `AutoRecover`, ซึ่งจะสแกนแพคเกจ zip, ข้ามส่วนที่อ่านไม่ออก, และคืนค่าที่สามารถประกอบได้. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **ทำไมต้อง AutoRecover?** +> มันพยายามอ่านให้ได้มากที่สุดขณะยังคงทำให้วัตถุเอกสารใช้งานได้. หากคุณเลือก `RecoveryMode.NoRecovery`, การโหลดจะล้มเหลวที่ความเสียหายแรก, ซึ่งทำให้วัตถุประสงค์ของสถานการณ์ **recover corrupted docx** ไม่สำเร็จ. + +## ขั้นตอนที่ 2: โหลดเอกสารด้วยตัวเลือกที่กำหนด + +เมื่อตั้งค่า recovery mode แล้ว, คุณสามารถพยายามเปิดไฟล์ได้อย่างปลอดภัย. แทนที่ `"YOUR_DIRECTORY/input.docx"` ด้วยเส้นทางจริงของไฟล์ที่เสียของคุณ. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +หากไฟล์เสียเพียงบางส่วน, อินสแตนซ์ `Document` ยังจะถูกสร้างขึ้น. คุณสามารถตรวจสอบ `document.IsStructureValid` ต่อมาได้หากต้องการการตรวจสอบเพิ่มเติม. + +## ขั้นตอนที่ 3: ตรวจสอบรูปแบบที่ตรวจพบ + +Aspose.Words จะตรวจจับรูปแบบเดิมโดยอัตโนมัติ (DOC, DOCX, ODT, ฯลฯ). การพิมพ์ค่าตัวนี้ช่วยให้คุณยืนยันว่าไลบรารีรู้จักไฟล์อย่างถูกต้อง, ซึ่งเป็นการตรวจสอบอย่างรวดเร็วหลังจากการทำงาน **recover corrupted docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +ผลลัพธ์ทั่วไป: + +``` +Loaded with Docx format. +``` + +แม้ว่าบางส่วนจะหายไป, การตรวจจับรูปแบบยังคงสำเร็จ—เป็นอีกหนึ่งความสำเร็จสำหรับเวิร์กโฟลว์ **recover corrupted docx**. + +## ขั้นตอนที่ 4: ดึงข้อมูลที่สามารถได้ + +เมื่อเอกสารถูกโหลดแล้ว, คุณสามารถจัดการมันเหมือนไฟล์ Word ปกติ. ด้านล่างเป็นตัวอย่างสั้นที่ดึงข้อความธรรมดาและเขียนลงคอนโซล. สิ่งนี้แสดงให้เห็นว่าคุณสามารถ **read damaged word file** เนื้อหาโดยไม่มีการล่ม. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +หากไฟล์ต้นฉบับมีตารางหรือรูปภาพที่เสีย, พวกมันจะถูกละเว้นจากผลลัพธ์ข้อความ. ส่วนที่เหลือของเอกสารยังคงอยู่ครบถ้วน. + +## ขั้นตอนที่ 5: บันทึกสำเนาที่สะอาด (ทางเลือก) + +บ่อยครั้งคุณอาจต้องการให้ผู้ใช้ไฟล์เวอร์ชันใหม่ที่สะอาดหลังการกู้คืน. การบันทึกด้วยรูปแบบเดียวกันทำให้แน่ใจว่าระบบต่อไปจะเข้ากันได้. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +ตอนนี้คุณมีไฟล์ **recover damaged docx** ที่สามารถแนบไปในอีเมลหรือส่งต่อให้บริการอื่นได้อย่างปลอดภัย. + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน, นี่คือโปรแกรมที่สมบูรณ์พร้อมรัน. วางลงในโปรเจกต์คอนโซลใหม่, ปรับเส้นทางไฟล์, แล้วกด F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง** (สมมติว่าไฟล์มีย่อหน้าเดียว “Hello world!” และ XML ที่เสียบางส่วน): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +สังเกตว่าโปรแกรมไม่เคยล่ม—แม้ไฟล์ต้นฉบับจะเสียบางส่วน. นั่นคือสาระสำคัญของการ **recover corrupted docx** ด้วย Aspose.Words. + +## คำถามทั่วไป & กรณีขอบ + +### ถ้าไฟล์อ่านไม่ได้เลย? + +แม้ `AutoRecover` จะมีขีดจำกัด. หากคอนเทนเนอร์ zip เองเสียจนไม่สามารถซ่อมได้, Aspose.Words จะโยน `CorruptedFileException`. ในกรณีนั้นคุณอาจต้องใช้เครื่องมือซ่อม zip ของบุคคลที่สามก่อนลอง **recover corrupted docx** อีกครั้ง. + +### ฉันสามารถกู้ฟอร์แมตอื่นได้หรือไม่ (เช่น `.doc`, `.odt`)? + +แน่นอน. `LoadOptions` เดียวกันทำงานกับฟอร์แมตใดก็ได้ที่ Aspose.Words รองรับ. เพียงเปลี่ยนนามสกุลไฟล์และไลบรารีจะตรวจจับรูปแบบเดิมโดยอัตโนมัติ. นั่นหมายความว่าคุณยังสามารถ **recover damaged docx**‑ลักษณะไฟล์เช่น `.doc` หรือ `.rtf` ด้วยโค้ดเดียวกัน. + +### จะจัดการเอกสารขนาดใหญ่โดยไม่โหลดทั้งหมดเข้าสู่หน่วยความจำอย่างไร? + +สำหรับไฟล์ขนาดกิกะไบต์คุณสามารถเปิด **load options** เช่น `LoadOptions.LoadFormat` หรือสตรีมเอกสารทีละหน้า. อย่างไรก็ตามอัลกอริทึมการกู้คืนยังต้องอ่านแพคเกจทั้งหมด, ดังนั้นคาดว่าจะใช้หน่วยความจำมากขึ้นสำหรับไฟล์เสียขนาดใหญ่มาก. + +### มีวิธีทราบว่ามีส่วนใดหายไปบ้างหรือไม่? + +หลังจากโหลด, คุณสามารถตรวจสอบ `document.GetChildNodes(NodeType.Any, true)` และเปรียบเทียบจำนวนกับค่ามาตรฐานที่คาดหวัง. ตาราง, รูปภาพ, หรือหัวเรื่องที่หายไปจะไม่มีในคอลเลกชันโนด. สิ่งนี้ทำให้คุณบันทึกได้อย่างแม่นยำว่าอะไรที่ **recover damaged docx** และแจ้งผู้ใช้. + +## เคล็ดลับมืออาชีพสำหรับการกู้คืนที่เชื่อถือได้ + +- **Validate the input file size** ก่อนโหลด; ไฟล์ขนาดศูนย์ไบต์จะล้มเหลวเสมอ. +- **Log the `RecoveryMode` result** โดยจับ `DocumentLoadingException` และบันทึกข้อความข้อยกเว้น; มักมีเบาะแสเกี่ยวกับส่วนที่ถูกข้าม. +- **Run the recovery on a background thread** หากคุณกำลังประมวลผลการอัปโหลดในเว็บเซอร์วิส—จะทำให้คำขอตอบสนองได้. +- **Combine with a checksum** (เช่น MD5) เพื่อตรวจสอบว่าไฟล์ที่กู้คืนแตกต่างจากต้นฉบับหรือไม่; จากนั้นคุณสามารถตัดสินใจว่าจะเก็บทั้งสองเวอร์ชันหรือไม่. + +## สรุป + +เราได้แสดงวิธี **recover corrupted docx** ไฟล์ใน C# โดย **setting recovery mode** เป็น `AutoRecover`, โหลดเอกสารอย่างปลอดภัย, ดึงข้อความที่เหลืออยู่, และบันทึกสำเนาที่สะอาดเป็นทางเลือก. วิธีนี้ทำให้คุณ **how to load docx** ไฟล์ที่โดยปกติจะโยนข้อยกเว้น, และให้วิธีที่เชื่อถือได้ในการ **read damaged word file** เนื้อหาโดยไม่ต้องใช้เครื่องมือภายนอก. + +ขั้นตอนต่อไป? ลองสลับ `RecoveryMode.AutoRecover` กับ `RecoveryMode.NoRecovery` เพื่อดูความแตกต่าง, หรือทดลองคุณสมบัติ `LoadOptions` ที่ควบคุมการจัดการรหัสผ่านและการแทนที่ฟอนต์. คุณยังสามารถรวมขั้นตอนการกู้คืนเข้าใน ASP.NET Core API ที่รับอัปโหลดและคืนไฟล์ที่ซ่อมแล้ว—เหมาะสำหรับสายงานการจัดการเอกสารระดับองค์กร. + +มีคำถามเพิ่มเติมเกี่ยวกับการกู้คืนเอกสาร Word, หรืออยากดูวิธี **recover damaged docx** ไฟล์ด้วยคอลแบ็กแบบกำหนดเอง? แสดงความคิดเห็นด้านล่าง, และขอให้เขียนโค้ดอย่างสนุก! + +![ภาพประกอบของเอกสารที่กู้คืน – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-markdownsaveoptions/_index.md b/words/thai/net/programming-with-markdownsaveoptions/_index.md index 729f669cef..66eefec392 100644 --- a/words/thai/net/programming-with-markdownsaveoptions/_index.md +++ b/words/thai/net/programming-with-markdownsaveoptions/_index.md @@ -65,6 +65,9 @@ ### [แปลง Word เป็น Markdown ใน C# – คู่มือเต็มพร้อมการสกัดรูปภาพ](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) +### [บันทึก docx เป็น markdown – ส่งออกสมการ Word ไปเป็น LaTeX ด้วย Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) +เรียนรู้วิธีส่งออกสมการจากไฟล์ Word ไปเป็น LaTeX ระหว่างการแปลงเป็น Markdown ด้วย Aspose.Words + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/thai/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..6063ad1816 --- /dev/null +++ b/words/thai/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-05-01 +description: บันทึกไฟล์ docx เป็น markdown ด้วย Aspose.Words – เรียนรู้การแปลง Word + เป็น markdown, ส่งออกสมการเป็น LaTeX, และตั้งค่าความละเอียดของรูปภาพใน markdown + ในกระบวนการทำงานที่ราบรื่นหนึ่งเดียว. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: th +og_description: บันทึกไฟล์ docx เป็น markdown ด้วย Aspose.Words. บทเรียนนี้แสดงวิธีแปลง + Word เป็น markdown, ส่งออกสมการเป็น LaTeX, และตั้งค่าความละเอียดของรูปภาพใน markdown. +og_title: บันทึก docx เป็น markdown – คู่มือเต็มสำหรับการส่งออก Math ของ Word เป็น + LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: บันทึก docx เป็น markdown – ส่งออกสูตร Word เป็น LaTeX ด้วย Aspose.Words +url: /th/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# บันทึก docx เป็น markdown – ส่งออก Word Math เป็น LaTeX ด้วย Aspose.Words + +เคยต้อง **บันทึก docx เป็น markdown** แล้วเจอปัญหาเรื่องสมการ Office Math ไม่คมชัดหรือเปล่า? คุณไม่ได้เป็นคนเดียวที่เจอเรื่องนี้ นักพัฒนาส่วนใหญ่มักเจออุปสรรคเมื่อการแปลงค่าเริ่มต้นทำให้สมการกลายเป็นภาพเบลอ ทำให้ต้องเขียนใหม่ด้วย LaTeX ด้วยตนเอง + +ข่าวดี: Aspose.Words สามารถทำงานหนักให้คุณได้ ในบทเรียนนี้เราจะ **แปลง word เป็น markdown**, บอกให้เครื่องมือ **ส่งออกสมการเป็น latex**, และแม้กระทั่ง **ตั้งค่าความละเอียดภาพ markdown** สำหรับส่วนที่เหลือของเอกสาร เมื่อเสร็จคุณจะได้คำสั่งเดียวที่สร้างไฟล์ `.md` ที่มีสมการพร้อม LaTeX และภาพความละเอียดสูง + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีโหลดไฟล์ `.docx` ที่มีวัตถุ Office Math +- คุณสมบัติของ `MarkdownSaveOptions` ที่ควบคุม **ส่งออกสมการเป็น latex** และ **ตั้งค่าความละเอียดภาพ markdown** +- ตัวอย่างโค้ด C# ที่สมบูรณ์และสามารถรันได้ ซึ่งคุณสามารถคัดลอกไปใส่ในโปรเจกต์ .NET ใดก็ได้ +- เคล็ดลับการแก้ปัญหาข้อผิดพลาดทั่วไป เช่น ฟอนต์หายหรือสมการที่ไม่รองรับ + +**ข้อกำหนดเบื้องต้น**: .NET 6+ (หรือ .NET Framework 4.6+), ไลเซนส์ Aspose.Words for .NET, และความคุ้นเคยพื้นฐานกับ C# หากคุณสร้างแอปคอนโซลได้แล้ว คุณก็พร้อมเริ่มแล้ว + +--- + +## ขั้นตอนที่ 1 – บันทึก docx เป็น markdown: โหลดไฟล์ Word ของคุณ + +สิ่งแรกที่เราต้องมีคืออ็อบเจ็กต์ `Document` ที่ชี้ไปยังไฟล์ `.docx` ต้นฉบับ คิดว่าเป็นการเปิดหนังสือก่อนเริ่มคัดลอกบท + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*ทำไมเรื่องนี้ถึงสำคัญ*: หากเอกสารไม่มีสมการเลย ขั้นตอน **ส่งออกสมการเป็น latex** จะไม่มีผลอะไร แต่การแปลงส่วนอื่นยังคงทำงานอยู่ การตรวจสอบนี้ช่วยให้คุณไม่ต้องสงสัยว่าทำไม Markdown ที่ได้ไม่มีบล็อก LaTeX + +--- + +## ขั้นตอนที่ 2 – ตั้งค่าการส่งออกสมการเป็น LaTeX + +Aspose.Words ให้คุณกำหนดวิธีการแสดง Office Math โดยค่าเริ่มต้นจะเปลี่ยนเป็นภาพ PNG ซึ่งเป็นสาเหตุที่หลายบทเรียนออกมาเป็นไฟล์ markdown ที่มีภาพหยาบ ๆ การเปลี่ยน `OfficeMathExportMode` เป็น `LaTeX` จะทำให้ได้สมการที่สะอาดและพร้อมคัดลอก‑วาง + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*ทำไมต้องใช้ `OfficeMathExportMode.LaTeX`?* LaTeX เป็นภาษากลางของการตีพิมพ์วิชาการ เมื่อคุณแสดง markdown ด้วย static‑site generator หรือ Jupyter notebook สมการจะคมชัดที่ระดับการซูมใด ๆ ก็ตาม + +--- + +## ขั้นตอนที่ 3 – ตั้งค่าความละเอียดภาพ Markdown (สำหรับเนื้อหาไม่ใช่ Math) + +แม้ว่าเราจะเน้นที่สมการ แต่เอกสาร Word ส่วนใหญ่ก็มีรูปภาพ, แผนภูมิ หรือ SVG ฝังอยู่ คุณสมบัติ `ImageResolution` ควบคุมวิธีที่ Aspose.Words แปลงทรัพยากรเหล่านั้นเป็น raster ค่า **300 DPI** เป็นค่าที่เหมาะสมสำหรับการแสดงบนหน้าจอและการพิมพ์ + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*เคล็ดลับ*: หาก markdown ของคุณจะถูกแสดงบนเว็บเท่านั้น คุณอาจลดลงเป็น 150 DPI เพื่อลดขนาดไฟล์ ในทางกลับกัน หากต้องการ PDF ที่พร้อมพิมพ์ ให้เพิ่มเป็น 600 DPI + +--- + +## ขั้นตอนที่ 4 – รันการแปลง – แปลง Word Math เป็น LaTeX + +เมื่อทุกอย่างตั้งค่าเรียบร้อย การแปลงจริงก็เป็นเพียงบรรทัดเดียว Aspose.Words จะทำงานหนักให้คุณโดยอัตโนมัติ + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**ผลลัพธ์ที่คาดหวัง**: เปิดไฟล์ `.md` ที่สร้างขึ้น คุณจะเห็นอย่างนี้ + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +สังเกตบล็อก LaTeX (`$...$` และ `$$...$$`) ที่แทนที่ภาพ PNG ก่อนหน้า ส่วนภาพที่ด้านล่างยังคงเป็น PNG ที่แสดงด้วยความละเอียด 300 DPI ตามที่เราตั้งค่า + +--- + +## ขั้นตอนที่ 5 – กรณีขอบเขตทั่วไป & วิธีจัดการ + +| สถานการณ์ | สิ่งที่เกิดขึ้น | วิธีแก้ | +|-----------|----------------|----------| +| **ฟอนต์หาย** (เช่น Cambria Math ไม่ได้ติดตั้ง) | ผลลัพธ์ LaTeX อาจมีสัญลักษณ์ที่ไม่รู้จัก | ติดตั้งฟอนต์ที่หายบนเซิร์ฟเวอร์หรือฝังฟอนต์ในเอกสารก่อนแปลง | +| **สมการซับซ้อน** (เมทริกซ์ที่มีตัวคั่นกำหนดเอง) | Aspose.Words อาจกลับไปใช้ภาพแม้ในโหมด `LaTeX` | อัปเกรดเป็นเวอร์ชันล่าสุดของ Aspose.Words; ไลบรารีมีการปรับปรุงการรองรับสมการอย่างต่อเนื่อง | +| **เอกสารขนาดใหญ่** ( > 50 MB ) | ความกดดันของหน่วยความจำอาจทำให้เกิด `OutOfMemoryException` | ใช้ `LoadOptions` พร้อม `LoadFormat.Docx` และสตรีมไฟล์, หรือแบ่งเอกสารเป็นส่วนก่อนแปลง | +| **ขนาดภาพใหญ่เกินไป** | ไฟล์ Markdown จะใหญ่เกินไป ทำให้การสร้าง static‑site ช้า | ลด `ImageResolution` ลงเป็น 150 DPI สำหรับกรณีเว็บ‑only (ดูขั้นตอน 3) | + +--- + +## ขั้นตอนที่ 6 – รวมทั้งหมดเข้าด้วยกัน: ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรมคอนโซล *เต็มรูปแบบ* ที่คุณสามารถคัดลอก‑วางลงใน `Program.cs` ได้ รวมทุกส่วนที่กล่าวถึงและเพิ่มการจัดการข้อผิดพลาดเล็กน้อย + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +รันโปรแกรม (`dotnet run`) แล้วคุณจะได้ไฟล์ markdown ที่ **บันทึก docx เป็น markdown** พร้อมรักษาสมการทุกสมการเป็น LaTeX ไม่ต้องคัดลอก‑วางด้วยมือ ไม่ต้องใช้ภาพ raster ที่ดูแย่สำหรับสมการ + +--- + +## สรุป + +เราได้เดินผ่านกระบวนการทั้งหมดของการ **บันทึก docx เป็น markdown** ด้วย Aspose.Words ตั้งแต่การโหลดไฟล์ Word ไปจนถึงการตั้งค่า **ส่งออกสมการเป็น latex** และ **ตั้งค่าความละเอียดภาพ markdown** โค้ดสุดท้ายพร้อมใช้งานในสภาพการผลิต และคุณสามารถนำไปใส่ในโปรเจกต์ .NET ใดก็ได้ที่ต้องการ **แปลง word เป็น markdown** แบบเรียลไทม์ + +ต่อไปคุณอาจลองนำไฟล์ `.md` ที่ได้ไปใช้กับ static‑site generator อย่าง Hugo หรือ Jekyll เพื่อให้สมการแสดงผลอย่างสวยงาม หากต้องการ **แปลง word math latex** ไปเป็นรูปแบบอื่น (PDF, HTML) เพียงเปลี่ยน `MarkdownSaveOptions` เป็น `PdfSaveOptions` หรือ `HtmlSaveOptions` — ธง `OfficeMathExportMode` ทำงานได้กับทุกแบบ + +มีขั้นตอนพิเศษในเวิร์กโฟลว์ของคุณ เช่น ดึงไฟล์ Word จาก Azure Blob storage หรือสตรีมจาก API? แค่เปลี่ยนคอนสตรัคเตอร์ `Document` ที่ใช้ไฟล์ระบบเป็นคอนสตรัคเตอร์ที่รับสตรีมก็ได้ + +ทดลองเล่นได้เลย และบอกเราผ่านคอมเมนต์ว่าแนวทางนี้ช่วยแก้ปัญหาการแปลงของคุณอย่างไร ขอให้สนุกกับการเขียนโค้ด! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-pdfsaveoptions/_index.md b/words/thai/net/programming-with-pdfsaveoptions/_index.md index b8cd30e76e..e18d7d016e 100644 --- a/words/thai/net/programming-with-pdfsaveoptions/_index.md +++ b/words/thai/net/programming-with-pdfsaveoptions/_index.md @@ -46,6 +46,7 @@ - [เรนเดอร์ 3D DML 3DEffects ในเอกสาร PDF](./dml-3deffects-rendering/) | เรียนรู้วิธีการเรนเดอร์เอฟเฟ็กต์ DML สามมิติอันน่าทึ่งในเอกสาร PDF โดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือทีละขั้นตอนที่ครอบคลุมนี้ - [การแทรกภาพในเอกสาร PDF](./interpolate-images/) | เรียนรู้วิธีการแทรกรูปภาพในเอกสาร PDF โดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือทีละขั้นตอนของเรา ปรับปรุงคุณภาพรูปภาพใน PDF ของคุณได้อย่างง่ายดาย - [บันทึก docx เป็น pdf ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | เรียนรู้วิธีบันทึกไฟล์ docx เป็น PDF อย่างครบถ้วนด้วย Aspose.Words ใน C# ผ่านขั้นตอนละเอียด +- [บันทึกเอกสารเป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | เรียนรู้วิธีบันทึกเอกสารเป็น PDF อย่างครบถ้วนด้วย Aspose.Words ใน C# ผ่านขั้นตอนละเอียด - [สร้าง PDF ที่เข้าถึงได้จาก Word ด้วย C# – คู่มือขั้นตอนโดยขั้นตอน](./create-accessible-pdf-from-word-with-c-step-by-step-guide/) | เรียนรู้วิธีสร้าง PDF ที่เข้าถึงได้จากไฟล์ Word ด้วย C# ผ่านขั้นตอนละเอียด - [สร้าง PDF ที่เข้าถึงได้ใน C# – บทเรียนการทำ PDF ให้เข้าถึงได้](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | เรียนรู้วิธีสร้าง PDF ที่เข้าถึงได้ตามมาตรฐาน WCAG ด้วย Aspose.Words สำหรับ .NET ใน C# - [สร้าง PDF ที่เข้าถึงได้จาก Word – คู่มือฉบับสมบูรณ์](./create-accessible-pdf-from-word-complete-guide/) | เรียนรู้วิธีสร้าง PDF ที่เข้าถึงได้จากไฟล์ Word ด้วย Aspose.Words สำหรับ .NET ผ่านขั้นตอนครบถ้วน diff --git a/words/thai/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/thai/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..c669568511 --- /dev/null +++ b/words/thai/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,254 @@ +--- +category: general +date: 2026-05-01 +description: เรียนรู้วิธีบันทึกเอกสารเป็น PDF ด้วย Aspose.Words ใน C# บทเรียนนี้ยังครอบคลุมการแปลง + Word เป็น PDF, การส่งออก Math LaTeX, และการจัดการฟอนต์ที่หายไป. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: th +og_description: บันทึกเอกสารเป็น PDF อย่างง่ายดายด้วย Aspose.Words คู่มือนี้ยังแสดงวิธีแปลง + Word เป็น PDF, ส่งออก Math LaTeX, และจัดการกับฟอนต์ที่หายไป. +og_title: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ +tags: +- Aspose.Words +- C# +- PDF generation +title: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ +url: /th/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# บันทึกเอกสารเป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับเต็ม + +เคยสงสัย **วิธีบันทึกเอกสารเป็น pdf** โดยตรงจากไฟล์ Word โดยไม่สูญเสียคุณลักษณะการเข้าถึงหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนามักถามหาแนวทางที่เชื่อถือได้ในการแปลง Word เป็น PDF พร้อมคงสมการคณิตศาสตร์และจัดการฟอนต์ที่หายไปอย่างราบรื่น + +ในบทเรียนนี้เราจะพาคุณผ่านโซลูชันแบบขั้นตอนต่อขั้นตอนที่ไม่เพียงแต่ **บันทึกเอกสารเป็น pdf** แต่ยังแสดง **แปลง word เป็น pdf**, **ส่งออก math latex**, และ **จัดการฟอนต์ที่หายไป** ด้วย Aspose.Words for .NET รุ่นล่าสุด เมื่อเสร็จสิ้นคุณจะมีโปรแกรม C# ที่พร้อมรันซึ่งสร้างไฟล์ PDF/UA‑2 ที่เป็นไปตามมาตรฐานการเข้าถึงได้อย่างสมบูรณ์ + +## สิ่งที่คุณต้องการ + +- .NET 6 หรือใหม่กว่า (โค้ดทำงานได้กับ .NET Core และ .NET Framework ด้วย) +- Aspose.Words for .NET 25.10 หรือใหม่กว่า – คุณสามารถดาวน์โหลดเวอร์ชันทดลองฟรีจากเว็บไซต์ Aspose +- เอกสาร Word ขนาดเล็ก (`input.docx`) ที่มีอย่างน้อยหนึ่งรูปทรงลอยและสมการคณิตศาสตร์ (เพื่อดูฟีเจอร์ export‑math‑latex ทำงาน) +- Visual Studio 2022 (หรือ IDE ใดก็ได้ที่คุณชอบ) + +> **เคล็ดลับระดับมืออาชีพ:** หากคุณอยู่ใน pipeline CI/CD ให้เพิ่มแพ็กเกจ NuGet ของ Aspose.Words ไปยังไฟล์โครงการของคุณ: + +```xml + +``` + +ตอนนี้มาดูโค้ดกัน + +## ขั้นตอนที่ 1: โหลดเอกสารต้นฉบับด้วยการกู้คืนอัตโนมัติ + +เมื่อทำงานกับไฟล์ Word ในโลกจริงคุณอาจเจอส่วนที่เสียหายหรือทรัพยากรที่หายไป การเปิดใช้งานการกู้คืนอัตโนมัติทำให้กระบวนการโหลดไม่เคยโยนข้อยกเว้น + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**ทำไมเรื่องนี้ถึงสำคัญ:** +`RecoveryMode.AutoRecover` ปกป้อง pipeline ของคุณจากการหยุดทำงานเมื่อรับอินพุตที่ผิดรูปแบบ ซึ่งเป็นประโยชน์อย่างยิ่งเมื่อคุณ **แปลง word เป็น pdf** เป็นจำนวนมาก + +## ขั้นตอนที่ 2: ตั้งค่า PDF Save Options สำหรับการเข้าถึงเต็มรูปแบบ + +PDF/UA‑2 คือมาตรฐาน ISO สำหรับ PDF ที่เข้าถึงได้ โดยการกำหนดค่าตัวเลือกไม่กี่อย่างเราจะได้ไฟล์ที่เครื่องอ่านหน้าจอสามารถนำทางได้ และเรายังทำให้สมการคณิตศาสตร์ถูกส่งออกเป็น LaTeX ที่ซ่อนอยู่ + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**จุดสำคัญ:** + +- **ExportFloatingShapesAsInlineTag** – ทำให้ PDF ที่ได้รักษาเลย์เอาต์เดิมไว้ขณะยังคงมีความหมายเชิงโครงสร้างที่ถูกต้อง +- **OfficeMathExportMode.LaTeX** – ตอบสนองความต้องการ **export math latex** ให้เครื่องมือภายหลังสามารถดึงสมการออกมาได้หากต้องการ + +## ขั้นตอนที่ 3: เก็บคำเตือน (เช่น ฟอนต์ที่หายไป) + +ฟอนต์ที่หายไปเป็นปัญหาที่พบบ่อยเมื่อแปลงเอกสาร Aspose.Words สามารถรายงานปัญหาเหล่านี้ผ่าน `WarningCallback` เราจะเก็บคำเตือนเหล่านี้เพื่อให้คุณบันทึกหรือดำเนินการต่อในภายหลัง + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**ทำไมคุณต้องสนใจ:** +หากแหล่งที่มามีฟอนต์ที่ไม่ได้ติดตั้งบนเซิร์ฟเวอร์ PDF จะใช้ฟอนต์เริ่มต้นแทน ซึ่งอาจทำให้เลย์เอาต์เสียหาย โดยการ **จัดการฟอนต์ที่หายไป** เราสามารถแจ้งผู้ใช้หรือฝังฟอนต์สำรองได้ + +## ขั้นตอนที่ 4: บันทึกเอกสารเป็น PDF ที่เข้าถึงได้ + +นี่คือช่วงเวลาที่สำคัญ—ทำการแปลงจริง + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +หากทุกอย่างดำเนินไปอย่างราบรื่น คุณจะได้ไฟล์ PDF/UA‑2 ที่มี LaTeX ที่ซ่อนอยู่สำหรับแต่ละสมการและการแท็กที่เหมาะสมสำหรับรูปทรงลอย + +## ขั้นตอนที่ 5: ตรวจสอบคำเตือนที่เก็บไว้ (ไม่บังคับแต่แนะนำ) + +หลังจากการบันทึก คุณสามารถวนลูปผ่านคำเตือนที่เก็บไว้และบันทึกลงล็อก + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +ผลลัพธ์ที่เป็นแบบทั่วไปอาจมีลักษณะดังนี้: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +การเห็นข้อความเหล่านี้ตั้งแต่เนิ่นๆ ช่วยให้คุณ **จัดการฟอนต์ที่หายไป** ก่อนที่มันจะส่งผลต่อผู้ใช้ปลายทาง + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมที่พร้อมรันทั้งหมด แทนที่เส้นทางตัวอย่างด้วยของคุณเอง + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง:** +- `output.pdf` สอดคล้องกับ PDF/UA‑2. +- รูปทรงลอยทั้งหมดถูกแท็กเป็นรูปภาพแบบอินไลน์. +- วัตถุ Office Math ทุกตัวปรากฏเป็น LaTeX ที่ซ่อนอยู่ (มองเห็นได้เมื่อคุณตรวจสอบโครงสร้างของ PDF). +- ปัญหาเกี่ยวกับฟอนต์ใด ๆ จะถูกพิมพ์ออกที่คอนโซล ให้คุณมีโอกาส **จัดการฟอนต์ที่หายไป** ก่อนส่งไฟล์. + +![Diagram showing the flow from Word → Aspose.Words → Accessible PDF (save document as pdf)](conversion-diagram.png "Flow diagram for saving document as pdf") + +*Image alt text:* **Diagram of how to save document as pdf using Aspose.Words** → *ภาพแผนภาพแสดงการไหลจาก Word → Aspose.Words → PDF ที่เข้าถึงได้ (บันทึกเอกสารเป็น pdf)* + +## คำถามทั่วไปและกรณีขอบ + +### ถ้าฉันใช้ Aspose.Words เวอร์ชันเก่า? + +ฟลัก `OfficeMathExportMode.LaTeX` ถูกเพิ่มในเวอร์ชัน 25.10 สำหรับรุ่นเก่าคุณยังสามารถ **แปลง word เป็น pdf** ได้ แต่สมการจะถูกแรสเตอร์ไลซ์แทนการส่งออกเป็น LaTeX ควรอัปเกรดเพื่อการเข้าถึงที่ดีที่สุด + +### ฉันสามารถฝังฟอนต์ที่กำหนดเองเพื่อหลีกเลี่ยงการ fallback ได้หรือไม่? + +ได้. ตั้งค่า `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` ก่อนเรียก `Save` สิ่งนี้ยังช่วย **จัดการฟอนต์ที่หายไป** โดยบังคับให้ PDF มี glyph ที่จำเป็นทั้งหมด + +### ฉันจะตรวจสอบความสอดคล้องกับ PDF/UA‑2 อย่างไร? + +เปิดไฟล์ใน Adobe Acrobat Pro → “Print Production” → “Preflight”. เลือกโปรไฟล์ “PDF/A‑2b” หรือ “PDF/UA‑2”; Acrobat จะรายงานการละเมิดใด ๆ + +### จะทำอย่างไรกับไฟล์ Word ที่มีรหัสผ่าน? + +โหลดเอกสารด้วย `LoadOptions` ที่รวม `Password`. ตัวอย่าง: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +ส่วนที่เหลือของ pipeline ไม่เปลี่ยนแปลง + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **บันทึกเอกสารเป็น pdf** ด้วย Aspose.Words ใน C# บทเรียนยังแสดงวิธี **แปลง word เป็น pdf**, **ส่งออก math latex**, และ **จัดการฟอนต์ที่หายไป** — ทั้งหมดนี้พร้อมผลิตไฟล์ PDF/UA‑2 ที่เข้าถึงได้ + +ลองรันโค้ด, ทดลองกับ `PdfSaveOptions` ต่าง ๆ (เช่น การบีบอัดภาพ, PDF/A‑2b) และผสานเข้ากับบริการประมวลผลเอกสารของคุณ หากต้องการขยายต่อไป ให้สำรวจไลบรารี PDF‑specific ของ Aspose สำหรับการประมวลผลหลังการแปลงหรือการลงลายเซ็นดิจิทัล + +มีสถานการณ์อื่นที่อยากลองแก้ไขหรือไม่? อย่าลังเลที่จะคอมเมนต์หรือดูคู่มืออื่น ๆ ของเราเกี่ยวกับ **PDF manipulation**, **image extraction**, และ **batch conversion**. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-shapes/_index.md b/words/thai/net/programming-with-shapes/_index.md index 28d793471a..7484124d19 100644 --- a/words/thai/net/programming-with-shapes/_index.md +++ b/words/thai/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ | [อัพเดท Smart Art Drawing](./update-smart-art-drawing/) | เรียนรู้วิธีอัปเดตภาพวาด Smart Art ในเอกสาร Word โดยใช้ Aspose.Words สำหรับ .NET ด้วยคำแนะนำทีละขั้นตอนนี้ รับรองว่าภาพของคุณจะถูกต้องเสมอ | - [สร้างรูปสี่เหลี่ยมผืนผ้าใน Word ด้วย C# – คู่มือทีละขั้นตอน](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | เรียนรู้วิธีสร้างรูปสี่เหลี่ยมผืนผ้าในเอกสาร Word ด้วย C# โดยใช้ Aspose.Words สำหรับ .NET ผ่านขั้นตอนง่ายๆ | [บทแนะนำเงารูปร่าง Aspose.Words – เพิ่มเงาให้รูปทรงใน Word ด้วย C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | เรียนรู้วิธีเพิ่มเงาให้รูปทรงในเอกสาร Word ด้วย Aspose.Words for .NET และ C# ผ่านบทแนะนำขั้นตอนง่าย | +| [วิธีย้ายเงาใน Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | เรียนรู้วิธีย้ายเงาของรูปทรงในเอกสาร Word ด้วย Aspose.Words for .NET ผ่านคู่มือ C# ฉบับเต็ม | - [สร้างเอกสาร Word ว่างพร้อมรูปสี่เหลี่ยมเงา – คู่มือทีละขั้นตอน](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | เรียนรู้วิธีสร้างเอกสาร Word ว่างและเพิ่มรูปสี่เหลี่ยมที่มีเงาโดยใช้ Aspose.Words สำหรับ .NET ด้วยขั้นตอนง่ายๆ {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/thai/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..c8061373d9 --- /dev/null +++ b/words/thai/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-01 +description: วิธีย้ายเงาบนรูปร่างใน Aspose.Words ด้วย C#. เรียนรู้การเพิ่มเงาให้กับรูปร่าง, + ปรับความเบลอ, ตั้งค่าความโปร่งใส, และหมุนเงาในเวลาไม่กี่นาที. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: th +og_description: วิธีย้ายเงาบนรูปร่างใน Aspose.Words ด้วย C# บทเรียนนี้จะแสดงวิธีเพิ่มเงาให้กับรูปร่าง + ปรับความเบลอ ตั้งค่าความโปร่งใส และหมุนเงา +og_title: วิธีย้ายเงาใน Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ +tags: +- Aspose.Words +- C# +- Document Automation +title: วิธีย้ายเงาใน Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ +url: /th/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีย้ายเงาใน Aspose.Words – คู่มือ C# ฉบับสมบูรณ์ + +เคยสงสัย **วิธีย้ายเงา** บนรูปทรงในเอกสาร Word โดยไม่ต้องเปิด Word ด้วยตนเองไหม? ในงานประจำวันของผม ผมมักต้องปรับเงาของรูปทรงโดยโปรแกรม—ไม่ว่าจะเป็นเพื่อรายงานที่ดูเป็นมืออาชีพหรือเทมเพลตแบบไดนามิก ข่าวดีคือ? ด้วย Aspose.Words คุณสามารถทำได้ในไม่กี่บรรทัด และคุณยังจะได้เรียนรู้ **add shadow to shape**, **how to change blur**, **how to set transparency**, และ **how to rotate shadow** ในขั้นตอนเดียว + +ในบทแนะนำนี้ เราจะเดินผ่านสถานการณ์จริง: โหลดไฟล์ DOCX ที่มีรูปทรงอยู่แล้ว, ปรับตำแหน่งเงา, ความนุ่ม, ความทึบแสง, และทิศทางของเงา, แล้วบันทึกผลลัพธ์. เมื่อจบคุณจะได้โค้ดสั้นที่นำกลับไปใช้ใหม่ได้ในโปรเจกต์ .NET ใดก็ได้ และคุณจะเข้าใจว่าทำไมแต่ละคุณสมบัติจึงสำคัญ + +## ข้อกำหนดเบื้องต้น – สิ่งที่คุณต้องมีก่อนเริ่ม + +- **Aspose.Words for .NET** (เวอร์ชัน 23.12 หรือใหม่กว่า) คุณสามารถดาวน์โหลดได้จาก NuGet ด้วยคำสั่ง `Install-Package Aspose.Words`. +- สภาพแวดล้อมการพัฒนา .NET 6+ (Visual Studio, VS Code, Rider—ตามที่คุณชอบ). +- ไฟล์ Word เข้า (`input.docx`) ที่มีอย่างน้อยหนึ่งรูปทรงอยู่แล้ว (เช่น สี่เหลี่ยม, วงกลม, หรือรูปภาพก็ได้). +- ความคุ้นเคยพื้นฐานกับไวยากรณ์ C#—ไม่ต้องลึกซึ้ง. + +หากคุณขาดสิ่งใดสิ่งหนึ่งจากรายการนี้ ให้หยุดพักแล้วติดตั้งไลบรารี; ส่วนที่เหลือของคู่มือถือว่ามีการอ้างอิงแพคเกจแล้ว. + +## ขั้นตอนที่ 1: โหลดเอกสารและดึงรูปทรงเป้าหมาย – **How to Move Shadow** เริ่มต้นที่นี่ + +สิ่งแรกที่เราทำคือโหลดเอกสารต้นฉบับและค้นหารูปทรงที่ต้องการแก้ไข. Aspose.Words ถือว่าวัตถุทุกอย่าง (ย่อหน้า, ตาราง, รูปทรง) เป็นโหนดในโครงสร้างต้นไม้, ดังนั้นเราสามารถสอบถามได้โดยตรง. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การโหลดเอกสารเพียงครั้งเดียวและใช้อินสแตนซ์ `Document` เดียวกันซ้ำเป็นการทำงานที่มีประสิทธิภาพ. การเรียก `GetChild` ปลอดภัยเพราะจะคืนค่า `null` หากดัชนีอยู่นอกช่วง, ทำให้เราจัดการกับรูปทรงที่หายไปได้อย่างราบรื่น. + +## ขั้นตอนที่ 2: ปรับค่า Blur Radius – Master **How to Change Blur** + +เงานุ่มให้ความรู้สึกเป็นมืออาชีพ, ในขณะที่ขอบแข็งอาจดูราคาถูก. คุณสมบัติ `BlurRadius` ควบคุมความนุ่มในหน่วยจุด (1 pt ≈ 1/72 inch). เรามาเพิ่มเป็น 8 pt กัน. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **เคล็ดลับ:** ค่าเบลอเริ่มต้นคือ 0.5 pt. ค่าที่มากกว่า 5 pt มักจะสังเกตได้ชัดเจน, แต่ระวังไม่ให้ใหญ่เกินไป—อาจทำให้รูปทรงดูแยกจากหน้า. + +## ขั้นตอนที่ 3: ตั้งค่า Transparency – คำตอบสำหรับ **How to Set Transparency** + +Transparency กำหนดว่ามองผ่านเงาได้แค่ไหน. ค่า `0` หมายถึงทึบเต็มที่; `1` หมายถึงโปร่งใสทั้งหมด. เพื่อเอฟเฟกต์ที่ละเอียดอ่อน เราจะใช้ค่า `0.3` (โปร่งใส 30 %). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **ทำไมคุณอาจสนใจ:** หากรูปทรงสีเข้ม, เงาทึบเต็มที่อาจทำให้ข้อความด้านล่างหายไป. การปรับ Transparency ทำให้เอกสารอ่านง่ายขึ้นพร้อมยังคงให้ความลึก. + +## ขั้นตอนที่ 4: ย้ายเงา – แกนหลักของ **How to Move Shadow** + +คุณสมบัติ `Distance` กำหนดระยะห่างของเงาจากรูปทรง, วัดเป็นจุด. ระยะห่างที่ใหญ่ขึ้นทำให้เงาอยู่ไกลออกไป, สร้างเอฟเฟกต์ที่โดดเด่นยิ่งขึ้น. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **ถ้าต้องการระยะเล็กน้อย?** การตั้งค่า `Distance` เป็น `0` จะทำให้เงาอยู่ตรงหลังรูปทรง, ซึ่งอาจเป็นประโยชน์สำหรับเอฟเฟกต์การอัดลาย. + +## ขั้นตอนที่ 5: หมุนแหล่งแสง – แก้ไข **How to Rotate Shadow** + +เงาไม่ได้อยู่แค่ลงตรงลงล่าง; มันตามมุมของแหล่งแสง. คุณสมบัติ `Angle` (เป็นองศา) หมุนเงารอบรูปทรง. เรามาเอียงที่ 45° กัน. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **ทดลองเร็ว:** ลองค่า `90` เพื่อให้เงาอยู่ด้านขวา หรือ `-30` เพื่อให้เงาเอียงซ้าย. การเปลี่ยนแปลงจะเห็นได้ทันที. + +## ขั้นตอนที่ 6: บันทึกเอกสาร – ดูผลลัพธ์ของ **Add Shadow to Shape** + +ตอนนี้เราได้ปรับเงาแล้ว, เราจะเขียนเอกสารกลับไปยังดิสก์. คุณสามารถเขียนทับไฟล์เดิมหรือสร้างไฟล์ใหม่; ตัวอย่างใช้ไฟล์ผลลัพธ์ใหม่. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **ผลลัพธ์ที่คาดหวัง:** เปิด `output.docx`. เงาของรูปทรงจะดูนุ่มขึ้น, เลื่อนตำแหน่งเล็กน้อย, กึ่ง‑โปร่งใส, และเอียงที่ 45°. หากเปรียบเทียบข้างกันกับ `input.docx`, ความแตกต่างจะเห็นได้ชัดเจน. + +### ตัวอย่างทำงานเต็ม (พร้อมคัดลอก‑วาง) + +ด้านล่างเป็นโปรแกรมทั้งหมดในบล็อกเดียว. คัดลอกไปยังโปรเจกต์คอนโซลใหม่, แทนที่ `YOUR_DIRECTORY` ด้วยเส้นทางโฟลเดอร์จริง, แล้วรัน. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## คำถามทั่วไป & กรณีขอบ + +### ถ้าเอกสารมีหลายรูปทรงล่ะ? + +คุณสามารถวนลูปผ่านรูปทรงทั้งหมดได้: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### ฉันสามารถเพิ่มเงาให้รูปทรงที่ยังไม่มีเงาได้ไหม? + +แน่นอน. วัตถุ `ShadowFormat` มีอยู่เสมอ; คุณแค่ต้องเปิดใช้งานมัน: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### วิธีนี้ทำงานกับรูปภาพและ SmartArt หรือไม่? + +ใช่. โหนดใด ๆ ที่สืบทอดจาก `Shape`—รวมถึงรูปภาพ, แผนภูมิ, และ SmartArt—มี `ShadowFormat`. คุณสมบัติเหมือนกันใช้ได้. + +### ฉันจะควบคุมสีของเงาอย่างไร? + +ใช้คุณสมบัติ `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### ความกังวลเรื่องความเข้ากันได้? + +Aspose.Words 23.12+ รองรับ .NET 6, .NET Core 3.1, และ .NET Framework 4.6.2+. API ที่แสดงนี้คงที่ในเวอร์ชันเหล่านี้. + +## สรุป + +เราได้อธิบาย **วิธีย้ายเงา** บนรูปทรงโดยใช้ Aspose.Words, และในระหว่างนั้นยังได้สาธิต **add shadow to shape**, **how to change blur**, **how to set transparency**, และ **how to rotate shadow**. ตัวอย่างที่สมบูรณ์และสามารถรันได้ทำให้คุณปรับเงาของรูปทรงใดก็ได้ในไม่กี่วินาที, ทำให้เอกสารของคุณดูเรียบหรูและเป็นมืออาชีพโดยไม่ต้องเปิด Word. + +พร้อมสำหรับขั้นตอนต่อไปหรือยัง? ลองผสานการปรับเงานี้กับ **conditional formatting**—เช่น ใช้เงาที่ลึกกว่าเฉพาะหัวข้อหรือแผนภูมิที่ใหญ่เกินขนาดที่กำหนด. หรือสำรวจ **gradient fills** สำหรับรูปทรงเองเพื่อสร้างการออกแบบที่ดึงดูดสายตาอย่างแท้จริง. + +หากคุณเจออุปสรรคใด ๆ, ฝากคอมเมนต์ด้านล่างได้เลย. ขอให้เขียนโค้ดอย่างสนุกสนาน, และขอให้เงาของคุณตกลงในตำแหน่งที่คุณต้องการเสมอ! + +![Diagram showing the effect of moving a shadow on a shape – how to move shadow example](https://example.com/images/shadow-demo.png "how to move shadow example") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/basic-conversions/_index.md b/words/turkish/net/basic-conversions/_index.md index ee818f76f2..43df8eaeff 100644 --- a/words/turkish/net/basic-conversions/_index.md +++ b/words/turkish/net/basic-conversions/_index.md @@ -13,7 +13,7 @@ {{< blocks/products/pf/tutorial-page-section >}} -# Temel Dönüşümler +# Temel Dönüşmler Basic Conversions, Aspose.Words for .NET kitaplığını kullanarak temel belge dönüştürmelerinde size yol gösterir. Eğitimler, Word belgelerini PDF, HTML, EPUB, resimler ve daha fazlası gibi farklı biçimlere dönüştürmek için adım adım açıklamalar, ayrıntılı kaynak kodu ve pratik örnekler sunar. Ayrıca dönüştürme seçeneklerini nasıl belirleyeceğinizi, yazı tiplerini, resimleri ve düzenleri nasıl yöneteceğinizi de öğreneceksiniz. Bu kaynak, Aspose.Words for .NET kullanarak belge dönüştürmelerini otomatikleştirmek isteyen geliştiriciler için olmazsa olmazdır ve dönüştürme süreci üzerinde tam esneklik ve kontrol sağlar. @@ -25,6 +25,7 @@ Basic Conversions, Aspose.Words for .NET kitaplığını kullanarak temel belge | [Docx'i Rtf'ye Dönüştür](./docx-to-rtf/) | Aspose.Words for .NET kullanarak DOCX'i RTF'ye nasıl dönüştüreceğinizi adım adım kılavuzumuzla öğrenin. Sorunsuz belge işleme için kolay dönüştürme. | | [Word Dosyasını PDF'ye Dönüştür](./docx-to-pdf/) Aspose.Words for .NET rehberimizle Word dosyalarını PDF'ye nasıl kolayca dönüştürebileceğinizi öğrenin. Hızlı ve güvenilir belge dönüşümü arayan geliştiriciler için mükemmeldir. | | [Word'ü PDF olarak kaydet – Aspose.Words Tam C# Rehberi](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words for .NET kullanarak C# ile Word belgelerini PDF'ye dönüştürmenin adım adım rehberi. | +| [Word'ü PDF olarak kaydet – Aspose.Words Tam Kılavuz](./save-word-as-pdf-with-aspose-words-complete-guide/) | Aspose.Words for .NET kullanarak Word belgelerini PDF'ye dönüştürmenin eksiksiz rehberi. | | [Docx'i PDF olarak kaydet – Aspose.Words Tam C# Rehberi](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words for .NET kullanarak C# ile DOCX dosyalarını PDF'ye dönüştürmenin ayrıntılı rehberi. | | [C# ile Word'ü PDF'ye Dönüştür – Aspose.Words Rehberi](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aspose.Words for .NET ile C# kullanarak Word belgelerini PDF'ye nasıl dönüştüreceğinizi adım adım öğrenin. | | [Docx'i Bayta Dönüştür](./docx-to-byte/) | Verimli belge işleme için Aspose.Words kullanarak .NET'te Docx'i bayt dizisine nasıl dönüştüreceğinizi öğrenin. Adım adım kılavuz dahildir. | @@ -33,7 +34,7 @@ Basic Conversions, Aspose.Words for .NET kitaplığını kullanarak temel belge | [Docx Dosyasını Markdown'a Dönüştür](./docx-to-markdown/) | Aspose.Words for .NET kullanarak DOCX dosyalarını Markdown'a nasıl dönüştüreceğinizi öğrenin. .NET uygulamalarınızda kusursuz entegrasyon için ayrıntılı kılavuzumuzu izleyin. | | [Docx'i Txt'ye Dönüştür](./docx-to-txt/) Aspose.Words for .NET ile DOCX'i TXT'ye adım adım kılavuzumuzla dönüştürün. Belgeleri verimli ve zahmetsizce dönüştürmeyi öğrenin. | | [Metin Dosyasını Word Belgesine Dönüştür](./txt-to-docx/) | Aspose.Words for .NET kullanarak metin dosyalarını Word belgelerine nasıl dönüştüreceğinizi öğrenin. Kapsamlı kılavuzumuzla belge dönüşümlerini verimli bir şekilde yönetin. | -| [PDF'yi Jpeg olarak kaydet](./pdf-to-jpeg/) | Aspose.Words for .NET kullanarak PDF'leri zahmetsizce JPEG'lere dönüştürün. Örnekler ve SSS içeren ayrıntılı kılavuzumuzu takip edin. Geliştiriciler ve meraklılar için mükemmel. | +| [PDF'yi Jpeg olarak kaydet](./pdf-to-jpeg/) | Aspose.Words for .NET kullanarak PDF'leri zahmetsizce JPEG'lere dönüştürün. Örnekler ve SSS içeren ayrıntılı kılavuzumuzu takip edin. Geliştirciler ve meraklılar için mükemmel. | | [PDF'yi Word Formatına (Docx) Kaydet](./pdf-to-docx/) | Bu ayrıntılı, adım adım kılavuzda Aspose.Words for .NET kullanarak bir PDF'yi Word belgesine (Docx) nasıl dönüştüreceğinizi öğrenin. Geliştiriciler için mükemmel. | | [Word'den LaTeX'e Nasıl Dışa Aktarılır – Adım Adım Kılavuz](./how-to-export-latex-from-word-step-by-step-guide/) | Aspose.Words for .NET kullanarak Word belgelerinden LaTeX formatına nasıl dışa aktarım yapacağınızı adım adım öğrenin. | diff --git a/words/turkish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/turkish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index d2c0d5b88c..6add81a409 100644 --- a/words/turkish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/turkish/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,27 +1,24 @@ --- category: general -date: 2025-12-29 -description: Aspose.Words kullanarak Word'den LaTeX nasıl dışa aktarılır – Word'ü - LaTeX'e dönüştürmeyi öğrenin, docx'i txt olarak kaydedin ve düz metinde denklemleri - işleyin. +date: 2026-05-01 +description: Word dosyasından LaTeX dışa aktarmayı, Word'ü txt'ye dönüştürmeyi ve + tabloları Aspose.Words ile C#'ta korumayı öğrenin. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: tr -og_description: Aspose.Words ile Word'ten LaTeX dışa aktarma. Bu kılavuz, Word'ü LaTeX'e - nasıl dönüştüreceğinizi, docx dosyasını txt olarak nasıl kaydedeceğinizi ve denklemleri - bozulmadan nasıl koruyacağınızı gösterir. -og_title: Word'den LaTeX Nasıl Dışa Aktarılır – Hızlı C# Öğretici +og_description: Aspose.Words ile Word'den LaTeX dışa aktarmayı, Word'ü düz metne dönüştürmeyi + ve tablo düzenini bozulmadan korumayı keşfedin. +og_title: Word'den LaTeX Nasıl Dışa Aktarılır – Tam C# Öğreticisi tags: - Aspose.Words - C# -- LaTeX - Document Conversion -title: Word'den LaTeX Nasıl Dışa Aktarılır – Adım Adım Kılavuz +title: Word’ten LaTeX Nasıl Dışa Aktarılır – Adım Adım Kılavuz url: /tr/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ --- @@ -29,178 +26,215 @@ url: /tr/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Word'ten LaTeX Dışa Aktarma – Adım Adım Kılavuz +# Word'den LaTeX Dışa Aktarma – Tam C# Öğreticisi -Hiç **Word'ten LaTeX'i nasıl dışa aktaracağınızı** merak ettiniz mi ve o karmaşık Office Math denklemlerini kaybetmek istemediniz mi? Tek başınıza değilsiniz. Birçok geliştirici, akademik makaleler, bilimsel raporlar veya otomatik yayın akışları için *Word'ten LaTeX'e dönüştürme* yapmaya çalışırken bir duvara çarpıyor. +Hiç **LaTeX'i nasıl dışa aktaracağınızı** bir Word belgesinden, matematik denklemlerini kaybetmeden merak ettiniz mi? Tek başınıza değilsiniz. Birçok geliştirici, Office Math içeren bir .docx dosyasını temiz LaTeX'e dönüştürürken aynı zamanda **Word'ü txt'ye dönüştürmek** istiyor. Bu rehberde, **tabloları koruyan**, düz metin dosyası veren ve LaTeX işaretlemesini tam istediğiniz yerde tutan, pratik ve çalıştırılabilir bir çözümü adım adım inceleyeceğiz. -Bu öğreticide, Aspose.Words kullanarak **LaTeX'i nasıl dışa aktaracağınızı** gösterTeX işaretlemesi içalarını nasıl kaydedeceğinizi** açıklayan ve **convert word equations latex** inceliklerini ele alan, tamamen çalıştırılabilir bir C# örneği üzerinden adım adım ilerleyeceğiz. +Kaynak dosyanın yüklenmesinden `TxtSaveOptions` ayarlarına kadar her şeyi ele alacağız; böylece çıktı hem insan tarafından okunabilir hem de makine dostu olacak. Sonunda **docx'i txt olarak kaydetmeyi**, **Word'ü düz metne dönüştürmeyi** ve **tabloları nasıl koruyacağınızı** öğrenmiş olacaksınız. Harici betikler, manuel kopyala‑yapıştırma yok — sadece herhangi bir .NET projesine ekleyebileceğiniz saf C# kodu. -> **Pro ipucu:** Aynı yaklaşım, sahip olduğunuz herhangi bir .docx dosyası için çalışır—kodun dosya yolunu farklı bir dosyaya yönlendirmeniz yeterli. +## Gereksinimler + +- **Aspose.Words for .NET** (en son sürüm, 2024.x veya daha yeni). NuGet paketi `Aspose.Words`. +- Bir .NET geliştirme ortamı (Visual Studio, VS Code, Rider — herhangi biri yeterli). +- Office Math denklemleri ve en az bir tablo içeren bir Word dosyası (`.docx`) (tabloların korunmasını görebilmek için). + +Hepsi bu. Eğer bunlara sahipseniz okumaya devam edin; aksi takdirde NuGet paketini ve bir örnek DOCX dosyasını edinin, ardından derinlemesine incelemeye başlayalım. --- -## İhtiyacınız Olanlar +## Word Belgesinden LaTeX Nasıl Dışa Aktarılır + +Aşağıdaki bölüm, **LaTeX'i nasıl dışa aktaracağınız** sorusuna yanıt veren üç özlü adımı ve aynı zamanda **Word'ü txt'ye dönüştürme**, **Word'ü düz metne çevirme**, **docx'i txt olarak kaydetme** ve **tabloları nasıl koruyacağınız** hedeflerini kapsar. -İlerlemeye başlamadan önce aşağıdaki önkoşullara sahip olduğunuzdan emin olun: +### Adım 1: DOCX Dosyasını Yükleyin -| Gereklilik | Neden Önemli | -|------------|--------------| -| **.NET 6.0+** (veya .NET Framework 4.6+) | Aspose.Words modern .NET çalışma zamanlarını hedefler. | -| **Aspose.Words for .NET** NuGet paketi (`Aspose.Words`) | Kütüphane, Word dosyasını ayrıştırma ve LaTeX üretme işini üstlenir. | -| **En az bir Office Math denklemi içeren bir .docx örneği** | LaTeX dönüşümünü aksiyon içinde görmek için. | -| **Visual Studio 2022** (veya tercih ettiğiniz herhangi bir IDE) | Örneği hata ayıklamayı ve çalıştırmayı son derece kolaylaştırır. | +İlk olarak Word belgesini bir `Aspose.Words.Document` nesnesine okumamız gerekir. Bu adım, daha sonra **Word'ü txt'ye dönüştürürseniz** ya da **docx'i txt olarak kaydederseniz** aynı kalır. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; -NuGet paketini henüz kurmadıysanız, şu komutu çalıştırın: +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; -```bash -dotnet add package Aspose.Words +Document doc = new Document(inputPath); ``` -Hepsi bu—ekstra DLL'ye, COM interop'a gerek yok, sadece temiz bir yönetilen kütüphane. +> **Neden önemli:** Dosyanın yüklenmesi, tüm Word öğelerinin (paragraflar, tablolar, Office Math nesneleri) bellekte bir temsilini oluşturur. Bu nesne olmadan dışa aktarma seçeneklerini manipüle edemezsiniz. ---- +### Adım 2: LaTeX ve Tablo Düzeni İçin `TxtSaveOptions`'ı Yapılandırın -## Word'ten LaTeX Dışa Aktarma – Genel Bakış +`TxtSaveOptions` sınıfı, düz metin dosyasının nasıl üretileceğini tam kontrol etmenizi sağlar. Senaryomuz için iki özellik kritik: -Aşağıda gerçekleştireceğimiz büyük resim yer alıyor: +| Özellik | Ne yapar | Neden gerekir | +|----------|--------------|-----------------| +| `OfficeMathExportMode` | Office Math'in nasıl render edildiğini belirler. `LaTeX` olarak ayarlandığında denklemler LaTeX sözdizimine dönüştürülür. | Bu, **LaTeX'i nasıl dışa aktaracağınız** sorusunun özüdür. | +| `PreserveTableLayout` | `true` olduğunda, Aspose tabloların ızgara‑benzeri görünümünü koruması için boşluk ekler. | Bu, **tabloları nasıl koruyacağınız** ihtiyacını karşılar ve **Word'ü txt'ye dönüştürür**. | -1. **Kaynak Word belgesini** (`.docx`) **yükleyin**. -2. **TxtSaveOptions**'ı, Office Math nesnelerinin LaTeX kodu olarak dışa aktarılmasını sağlayacak şekilde **yapılandırın**. -3. Belgeyi, doğrudan herhangi bir LaTeX derleyicisine besleyebileceğiniz bir **düz metin** (`.txt`) dosyası olarak **kaydedin**. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Word'ten LaTeX dışa aktarma örneği](image.png "Word'ten LaTeX dışa aktarma") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro ipucu:** Sadece ham LaTeX istiyorsanız ve tablo biçimlendirmesine ihtiyacınız yoksa, `PreserveTableLayout`'u `false` yapın. Dosya daha küçük olur, ancak görsel tablo ipucu kaybolur. -## Adım 1: Word Belgesini Yükleyin +### Adım 3: Belgeyi Düz Metin Olarak Kaydedin -İlk iş olarak, dönüştürmek istediğiniz .docx dosyasını açın. `Document` sınıfı, alttaki tüm XML'i soyutlayarak size dostça bir nesne modeli sunar. +Şimdi, az önce tanımladığımız seçeneklerle belgeyi bir `.txt` dosyasına yazalım. Bu tek satır, **Word'ü düz metne çevirir**, **docx'i txt olarak kaydeder** ve elbette **LaTeX'i nasıl dışa aktaracağınızı** bir arada gerçekleştirir. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; - -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Neden önemli:** -Dosyayı erken yüklemek, içeriğini (örneğin denklemleri saymak) serileştirmeye karar vermeden önce incelemenizi sağlar. Dosya bozuksa, `Document` net bir istisna fırlatır ve daha sonra ortaya çıkabilecek gizemli çıktılardan sizi korur. +Çağrı tamamlandığında `output.txt` dosyasını açın. Şunları göreceksiniz: ---- +- Her Office Math denklemi için `\frac{a}{b}` gibi LaTeX parçacıkları. +- `|` ve `-` karakterleriyle render edilen tablolar, sütun hizalamasını korur. +- Düz metin olarak normal paragraflar, sonraki işlem aşamaları için hazır. -## Adım 2: LaTeX Dışa Aktarma İçin TxtSaveOptions'ı Yapılandırın +### Tam Çalışan Örnek -Sihir, `TxtSaveOptions` içinde gerçekleşir. `OfficeMathExportMode`'u `LaTeX` olarak ayarladığınızda, her Office Math nesnesi karşılık gelen LaTeX temsiline dönüştürülür. +Hepsini bir araya getirdiğimizde, bugün derleyip çalıştırabileceğiniz bağımsız bir program ortaya çıkıyor: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} +``` + +**Beklenen çıktı (alıntı):** + ``` +This is a sample paragraph. -**Bu ayarları neden seçtik:** +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | -- `OfficeMathExportMode.LaTeX`, doğru bir matematiksel çeviriyi garanti eden tek moddur. -- `PreserveTableLayout`, tabloların Word'deki görünümünü korur; bu, çıktıyı daha sonra bir LaTeX `tabular` ortamına gömmek istediğinizde kullanışlıdır. -- UTF‑8, “α”, “β” veya “∑” gibi karakterlerin dönüşüm sırasında kaybolmamasını sağlar. +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Eğer **convert word to latex** işlemini düz metin sarmalayıcısı olmadan yapmak isterseniz, `SaveFormat.LaTeX`'e geçebilirsiniz—gelişmiş senaryolar için hızlı bir ipucu. +Tablonun ızgara yapısını koruduğunu ve denklemin temiz LaTeX olarak göründüğünü fark edin. Bu, **Word'ü txt'ye dönüştürürken** hem yapıyı hem de matematiği doğru bir şekilde temsil etmenin ideal yoludur. --- -## Adım 3: Belgeyi Metin Dosyası Olarak Kaydedin +## Word'ü TXT'ye Dönüştürme ve Tabloları Koruma İpuçları -Şimdi LaTeX zengini metni diske yazıyoruz. Oluşan `.txt` dosyası daha sonra `.tex` olarak yeniden adlandırılabilir veya doğrudan bir LaTeX derleyicisine pipe edilebilir. +Üç adımlı yaklaşım çoğu senaryoda işe yarasa da, gerçek dünyadaki projeler bazen sürprizler çıkarır. Aşağıda **Word'ü düz metne çevirme** hattınızı daha dayanıklı hâle getirecek pratik öneriler bulacaksınız. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Tutarlı Bir Kodlama Kullanın -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` varsayılan olarak UTF‑8'dir ve çoğu karakteri destekler. Farklı bir kod sayfasına (ör. Windows‑1252 gibi eski sistemler) ihtiyacınız varsa, `Encoding` özelliğini ayarlayın: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**`output.txt` içinde görecekleriniz:** +### Fazla Boşlukları Temizleyin -``` -\begin{equation} -E = mc^{2} -\end{equation} +Birçok sütunlu tablolar uzun satırlar üretebilir. Kaydetme sonrası, birden fazla boşluğu tek bir sekmeye dönüştürmek isteyebilirsiniz: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Diğer tüm paragraflar düz metin olarak kalırken, her Office Math denklemi bir LaTeX `equation` ortamı (veya Word'de satır içi ise `inline`) içinde sarılır. Bu, **convert word equations latex** gereksinimini mükemmel şekilde karşılar. +### İç İçe Tabloları İşleyin ---- +DOCX'inizde tablo içinde tablo varsa, `PreserveTableLayout` hâlâ görsel hiyerarşiyi korur, ancak girinti garip görünebilir. Hızlı bir çözüm, baştaki boşlukları özel bir işaretçi (ör. `>>`) ile değiştirmek, böylece sonraki ayrıştırıcılar iç içe geçmiş seviyeleri algılayabilir. -## Kenar Durumları & Sık Sorulan Sorular +### Birden Çok Dosyayı Toplu İşleme -| Durum | Ne Yapmalı | -|-------|------------| -| **Kaynak dosyada denklem yok** | Dönüşüm hâlâ çalışır; sadece düz metin elde edersiniz. Ekstra LaTeX kodu eklenmez. | -| **Çok büyük belgeler (>100 MB)** | Bellek kullanımını azaltmak için çıktıyı `MemoryStream` ile akıtmayı düşünün. | -| **Desteklenmeyen Matematik yapıları** | Aspose.Words %99 Office Math'i kapsar. Nadir bir kenar durumunda LaTeX'i manuel olarak işlemek gerekebilir. | -| **.txt yerine .tex dosyasına ihtiyacınız var** | `outputPath`'i `.tex` ile bitirecek şekilde değiştirin ve isteğe bağlı olarak `txtOptions.Encoding`'i `Encoding.UTF8` olarak ayarlayın. | -| **Linux/macOS üzerinde çalıştırma** | Aynı kod çalışır—dosya yollarının ileri eğik çizgi (`/`) kullandığından veya `Path.Combine` ile oluşturulduğundan emin olun. | +**Word'ü txt'ye dönüştürmek** için onlarca belgeyle uğraşıyorsanız, mantığı bir döngüye alın: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +Bu sayede **docx'i txt olarak kaydedebilir** ve manuel müdahale olmadan toplu iş yapabilirsiniz. -## LaTeX Denklemleri İçeren TXT Kaydetme – Hızlı Özet +--- -1. **.docx'i** (`Document`) **yükleyin**. -2. `TxtSaveOptions` içinde `OfficeMathExportMode = LaTeX` **ayarlayın**. -3. Bu seçeneklerle **dosyayı kaydedin** (`doc.Save`). +## Yaygın Hatalar ve Önleme Yöntemleri -Bu, **how to save txt** dosyalarının LaTeX biçimlendirilmiş denklemler içermesini sağlayan tam iş akışıdır. +1. **LaTeX Dışa Aktarım Modu Eksik** – `OfficeMathExportMode = OfficeMathExportMode.LaTeX` ayarlamayı unutursanız, denklemler düz metin (ör. “Equation 1”) olarak kalır. Her zaman seçenek bloğunu iki kez kontrol edin. +2. **Tablo Düzeni Kaybolur** – `PreserveTableLayout` varsayılan olarak `false`tır. Çıktınız bir duvar metin gibi görünüyorsa, bu bayrağı açmadınız demektir. +3. **Boşluk İçeren Dosya Yolları** – Ham string (`@"C:\My Folder\input.docx"`) kullanmak kaçış sorunlarını önler. Aksi takdirde `FileNotFoundException` alırsınız. +4. **Sürüm Uyumsuzluğu** – Eski Aspose.Words sürümleri (< 21.9) `OfficeMathExportMode`'u desteklemez. **LaTeX'i nasıl dışa aktaracağınız** için en yeni pakete yükseltin. +5. **ASCII Olmayan Karakterlerde Kodlama Hataları** – `�` gibi semboller görürseniz, `options.Encoding`'i açıkça UTF‑8 ya da uygun kod sayfasına ayarlayın. --- -## Bonus: Birden Fazla Dosya İçin Dönüşümü Otomatikleştirme +## Çözümü Genişletmek: TXT'den Markdown veya HTML'ye -Eğer bir klasörde bir sürü Word belgesi varsa, yukarıdaki mantığı basit bir döngüye sarabilirsiniz: +Bazen sadece düz metin yeterli olmayabilir — belki LaTeX blokları içeren bir Markdown dosyasına ihtiyacınız vardır. Aynı `TxtSaveOptions` yerine `HtmlSaveOptions` ya da `MarkdownSaveOptions` kullanabilirsiniz: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Artık **convert word to latex** işlemini toplu olarak yapabilirsiniz—günlük olarak onlarca el yazması alan araştırma grupları için mükemmel. +Bu küçük değişiklik, **Word'ü txt'ye benzer bir çıktı** almanızı sağlarken aynı zamanda sevdiğiniz markdown sözdizimini korur. --- ## Sonuç -**Word'ten LaTeX'i nasıl dışa aktaracağınızı** adım adım ele aldık, **LaTeX içeren txt dosyalarını nasıl kaydedeceğinizi** gösterdik ve **convert word equations latex** işlemini kayıpsız bir şekilde nasıl yapacağınızı sergiledik. +Word belgesinden **LaTeX'i nasıl dışa aktaracağınızı** adım adım, aynı zamanda **Word'ü txt'ye dönüştürme**, **Word'ü düz metne çevirme**, **docx'i txt olarak kaydetme** ve **tabloları nasıl koruyacağınız** konularını kapsayan eksiksiz, üretim‑hazır bir çözüm sunduk. Özetle: + +- DOCX'i `Aspose.Words.Document` ile yükleyin. +- `TxtSaveOptions.OfficeMathExportMode = LaTeX` ve `PreserveTableLayout = true` ayarlarını yapın. +- `doc.Save(outputPath, options)` çağrısıyla temiz, LaTeX‑zengin bir düz metin dosyası elde edin. -Sadece birkaç satır C# ve güçlü Aspose.Words kütüphanesi ile herhangi bir .docx dosyasını LaTeX'e hazır metne dönüştürebilir, bilimsel makaleler, ders kitapları veya otomatik yayın akışları için kullanabilirsiniz. +Kendi dosyalarınızda deneyin, kodlama ayarlarıyla oynayın ve klasörleri toplu işleyin. İç içe tablolar, egzotik karakterler ya da eski Aspose sürümleri gibi kenar durumlarıyla karşılaşırsanız, “İpuçları” ve “Yaygın Hatalar” bölümlerine göz atın. -**Sonraki adım?** Oluşturduğunuz `.txt` dosyasını (veya `.tex` olarak yeniden adlandırın) `pdflatex` veya `xelatex` ile derleyerek PDF elde edin, ya da doğrudan `.tex` dosyası için `SaveFormat.LaTeX` seçeneğini keşfedin. **save docx as txt** yaparken biçimlendirmeyi korumak isterseniz `PreserveTableLayout` ve özel satır sonu işleme ayarlarıyla deneyler yapın. +Bir sonraki adıma hazır mısınız? Aynı DOCX'i Markdown'a dönüştürmeyi deneyin ya da üretilen `.txt` dosyasını LaTeX'i webde render eden bir statik site jeneratörüne besleyin. Olanaklar sınırsız ve artık **Word'ü txt'ye dönüştürme** iş akışınız için sağlam bir temele sahipsiniz. -Kenar durumları, lisanslama veya performans ayarları hakkında sorularınız mı var? Aşağıya yorum bırakın—mutlu kodlamalar! +Kodlamanız keyifli olsun, LaTeX'iniz ilk denemede derlensin! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/turkish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/turkish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..78e3702f91 --- /dev/null +++ b/words/turkish/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words ile C#'ta Word'ü PDF olarak kaydedin. docx'i PDF'ye dönüştürmeyi, + eksik yazı tiplerini tespit etmeyi ve yazı tipi ikame uyarılarını verimli bir şekilde + yönetmeyi öğrenin. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: tr +og_description: Aspose.Words kullanarak Word'ü PDF olarak kaydedin. Bu adım adım öğretici, + docx'i PDF'ye nasıl dönüştüreceğinizi ve eksik yazı tiplerini nasıl tespit edeceğinizi + gösterir. +og_title: Aspose.Words ile Word belgesini PDF olarak kaydetme – Tam Kılavuz +tags: +- Aspose.Words +- C# +- PDF conversion +title: Aspose.Words ile Word'ü PDF olarak kaydetme – Tam Rehber +url: /tr/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words ile Word'ü PDF Olarak Kaydet – Tam Kılavuz + +Hiç **save Word as PDF** yapmanız gerekti ve yol boyunca bir fontun eksik kalıp kalmayacağını merak ettiniz mi? Yalnız değilsiniz—geliştiriciler belge dönüştürürken sürekli eksik‑font sorunlarıyla uğraşıyor. Bu kılavuzda, sadece **convert docx to pdf** yapmakla kalmayıp aynı zamanda Aspose.Words'un font‑substitution uyarılarını kullanarak **detect missing fonts** yapacak bir uygulamalı çözümü adım adım inceleyeceğiz. + +Uyarı toplayıcısını kurmaktan çıktıyı yorumlamaya kadar her şeyi ele alacağız, böylece sonunda **save Word as PDF** işlemini sürpriz olmadan tam olarak nasıl yapacağınızı bileceksiniz. Harici araçlar yok, karmaşık ayarlar yok—herhangi bir .NET projesine ekleyebileceğiniz temiz C# kodu. + +## İhtiyacınız Olanlar + +- **Aspose.Words for .NET** (en son sürüm, ör. 24.10) – NuGet üzerinden alabilirsiniz (`Install-Package Aspose.Words`). +- .NET geliştirme ortamı (Visual Studio, Rider veya VS Code yeterli). +- Hedef makinede yüklü olmayan fontlar içerebilecek bir örnek DOCX dosyası. +Hepsi bu. Bu temellere sahipseniz, derinlemesine incelemeye hazırsınız. + +## Word'ü PDF Olarak Kaydet – Adım Adım Genel Bakış + +Aşağıda tam, çalıştırılabilir program yer alıyor. Bir konsol uygulaması projesine kopyalayıp **F5** tuşuna basabilirsiniz. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Pro tip:** `YOUR_DIRECTORY` ifadesini mutlak bir yol ile değiştirin ya da göreli ve daha güvenli bir yaklaşım için `Path.Combine(Environment.CurrentDirectory, "input.docx")` kullanın. + +### Neden Uyarı Geri Çağrısı Kullanıyoruz + +Aspose.Words eksik fontları sessizce bir yedek fontla (genellikle Arial) değiştirir. Bir geri çağrı olmadan bu değişikliğin gerçekleştiğini asla bilmezsiniz, bu da ortaya çıkan PDF'de düzen bozukluklarına yol açabilir. `IWarningCallback`'i bağlayarak, her eksik‑font olayının net, programatik bir listesini elde ederiz—günlük kaydı tutma veya son kullanıcıları bilgilendirme için mükemmeldir. + +### Eksik Fontları Algılamak – Nelere Bakmalı + +Programı çalıştırdığınızda, eksik bir font aşağıdaki gibi bir konsol satırı üretir: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Liste boşsa, tebrikler—**save word as pdf** işlemi tüm özgün fontlarla sorunsuz gerçekleşti. + +## Docx'i PDF'e Dönüştür – Çıktıyı Özelleştirme + +Bazen belirli bir PDF sürümü, görüntü kalitesi veya uyumluluk seviyesi gerekir. Aspose.Words, `Save` metodunu çağırmadan önce `PdfSaveOptions` nesnesini ayarlamanıza izin verir. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Neden önemli:** Hukuki arşivler için PDF oluşturuyorsanız, `PdfA1b` ayarı dosyanın katı standartlara uymasını sağlar. Aynı dönüşüm uyarı geri çağrımızı da dikkate alır, bu yüzden hâlâ **detect missing fonts** yapabilirsiniz. + +## Aspose Words Font Değiştirme – Kenar Durumlarını Yönetme + +### Senaryo 1: Birden Çok Eksik Font + +Kaynak belgeniz birden fazla özel font kullanıyorsa, uyarı toplayıcısı font başına bir giriş içerir. Bunları birleştirebilirsiniz: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Senaryo 2: Yedek Font Klasörü Sağlama + +Aspose.Words, fontlar için ek klasörler arayabilir. Belgeyi yüklemeden önce `FontSettings` üzerindeki `FontsFolder` özelliğini ayarlayın: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Artık kütüphane önce sizin özel klasörünüzü deneyecek, istenmeyen değişim olasılığını azaltacak. + +### Senaryo 3: Değişimleri Yoksayma + +Bir font eksik olduğunda dönüşümün başarısız olmasını (sessizce değiştirilmesi yerine) tercih ediyorsanız, geri çağrı içinde bir istisna fırlatın: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Bu, ilerlemeden önce eksik fontu ele almanızı zorunlu kılar—sessiz hataların kabul edilemez olduğu CI boru hatları için faydalıdır. + +## Tam Uçtan Uca Örnek + +Her şeyi bir araya getirerek, **Word'ü PDF'e nasıl dönüştüreceğinizi** gösteren, özel PDF seçeneklerini ayarlayan ve font sorunlarını günlüğe kaydeden kompakt bir sürüm burada: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Beklenen konsol çıktısı** (eğer Calibri eksikse): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Uyarı çıkmazsa, **save word as pdf** işleminiz kaynak DOCX ile tam aynı fontları kullandı demektir. + +## Görsel Özet + +![Word'ü PDF Olarak Kaydet iş akışı diyagramı](https://example.com/diagram.png "Word'ü PDF Olarak Kaydet iş akışı") + +*Resim alt metni:* **save word as pdf** iş akışı, yükleme, uyarı toplama ve PDF çıktısını gösterir. + +## Sık Sorulan Sorular & Cevaplar + +| Question | Answer | +|----------|--------| +| **Aspose.Words için bir lisansa ihtiyacım var mı?** | Test için ücretsiz bir değerlendirme lisansı yeterlidir, ancak üretim kullanımında değerlendirme filigranını kaldırmak için ücretli bir lisans gerekir. | +| **Bu .NET Core / .NET 6+ üzerinde çalışır mı?** | Kesinlikle—Aspose.Words .NET Standard 2.0'ı hedefler, bu yüzden herhangi bir yeni .NET çalışma zamanı uyumludur. | +| **Bir döngü içinde birden fazla DOCX dosyasını dönüştürebilir miyim?** | Evet, her dosya için yeni bir `Document` nesnesi oluşturun ve toplu sonuçlar istiyorsanız aynı `WarningInfoCollector`'ı yeniden kullanın. | +| **Çıktı klasörü mevcut değilse ne olur?** | `Document.Save` `DirectoryNotFoundException` hatası fırlatır. Önce klasörü oluşturun ya da `Directory.CreateDirectory` kullanın. | +| **Eksik fontları PDF'e gömmek mümkün mü?** | Aspose.Words, fontlar makinede mevcutsa otomatik olarak gömebilir; `PdfSaveOptions.EmbedFullFonts = true` olarak ayarlayın. | + +## Sonuç + +Artık **save Word as PDF** yaparken **detecting missing fonts** ve **Aspose.Words font substitution** senaryolarını yönetebileceğiniz sağlam, üretim‑hazır bir deseniniz var. Bir uyarı geri çağrısı ekleyerek, font klasörlerini özelleştirerek ve isteğe bağlı olarak `PdfSaveOptions`'ı ayarlayarak güvenilir bir şekilde **convert docx to pdf** yapabilir ve kullanıcılarınızı düzen doğruluğunu etkileyebilecek font sorunları hakkında bilgilendirebilirsiniz. + +Bir sonraki adıma hazır mısınız? Birden çok belgeyi paralel olarak PDF'e dönüştürmeyi deneyin ya da filigran ve dijital imza eklemeyi keşfedin—her ikisi de az önce öğrendiğiniz kodun basit uzantılarıdır. Kodlamanın tadını çıkarın, ve PDF'leriniz her zaman istediğiniz gibi görünsün! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-loadoptions/_index.md b/words/turkish/net/programming-with-loadoptions/_index.md index f645c2214a..33c1bd5d84 100644 --- a/words/turkish/net/programming-with-loadoptions/_index.md +++ b/words/turkish/net/programming-with-loadoptions/_index.md @@ -40,6 +40,7 @@ Bu eğitimlerde, özel ayarlarla Word belgelerini yüklemek için LoadOptions'ı | [docx dosyasını kurtarma – kurtarma modunu ayarla ve bozuk Word dosyalarını aç](./how-to-recover-docx-set-recovery-mode-open-corrupted-word-fi/) | Aspose.Words for .NET ile bozuk bir docx dosyasını kurtarma modunu ayarlayarak nasıl açacağınızı öğrenin. | | [Aspose.Words'te LoadOptions Kullanımı – Tam Kılavuz](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Aspose.Words for .NET ile LoadOptions kullanarak belgeleri nasıl yükleyeceğinizi ve özelleştireceğinizi adım adım öğrenin. | | [C#'ta Bozuk Belgeyi Kurtarma – Kurtarma Modunu Ayarla ve Kullanıcıyı Uyar](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) | Aspose.Words for .NET ile bozuk bir belgeyi kurtarmak, kurtarma modunu ayarlamak ve kullanıcıdan onay istemek için adım adım rehber. | +| [Bozuk docx Dosyasını Kurtarma – C#'ta Hasarlı Word Dosyalarını Yükleme Tam Kılavuzu](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Aspose.Words for .NET ile bozuk docx dosyalarını C# kullanarak nasıl yükleyeceğinizi ve kurtaracağınızı adım adım öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/turkish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..341abfe0a1 --- /dev/null +++ b/words/turkish/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words kullanarak bozuk docx dosyalarını hızlıca kurtarın. Kurtarma + modunu nasıl ayarlayacağınızı, docx dosyasını güvenli bir şekilde nasıl yükleyeceğinizi + ve hasarlı Word dosyalarını sadece birkaç adımda nasıl okuyacağınızı öğrenin. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: tr +og_description: C#'de bozuk docx dosyalarını kurtarın. Kurtarma modunu ayarlayın, + docx'i güvenli bir şekilde yükleyin ve Aspose.Words ile hasarlı Word dosyalarını + okuyun. +og_title: Bozuk docx dosyasını kurtarın – Hızlı C# Kılavuzu +tags: +- Aspose.Words +- C# +- Document Recovery +title: Bozuk docx dosyalarını kurtarın – C#'ta Hasar Görmüş Word Dosyalarını Yükleme + Tam Kılavuzu +url: /tr/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bozuk docx dosyasını kurtarma – Hızlı C# Rehberi + +Hiç bir Word dosyasını açmaya çalıştınız mı ve dosya hiç yüklenmedi, içeriğin sonsuza kadar kaybolduğunu düşündünüz mü? Birçok gerçek dünyadaki projede kullanıcıdan ek'i yeniden göndermesini istemeden **bozuk docx dosyasını kurtarma** dosyalarını **kurtaracaksınız**. İyi haber şu ki Aspose.Words bunu çocuk oyuncağı haline getiriyor: sadece kurtarma modunu ayarlıyorsunuz ve kütüphane geri kalanını hallediyor. + +Bu öğreticide **bozuk docx dosyasını kurtarma** adımlarını adım adım gösterecek, `RecoveryMode.AutoRecover` seçeneğinin neden en güvenli seçim olduğunu açıklayacak ve **docx dosyasını nasıl yükleyeceğinizi** göstereceğiz. Sonunda hasarlı bir Word dosyasını okuyabilecek, hayatta kalan metni çıkarabilecek ve hatta gelecekteki denetimler için orijinal formatı kaydedebileceksiniz. Harici araçlar yok, sadece temiz C# kodu. + +## İhtiyacınız Olanlar + +- **Aspose.Words for .NET** (herhangi bir yeni sürüm; kullandığımız API 23.5 ve üzeriyle çalışır). +- .NET geliştirme ortamı (Visual Studio, VS Code veya Rider). +- Kurtarmak istediğiniz bozuk veya kısmen hasarlı `.docx` dosyası. + +Özel izinler gerekmez, COM interop gerekmez ve sunucuya Microsoft Office kurmanız da gerekmez. Basit, değil mi? + +## Adım 1: Kurtarma Modunu Auto‑Recover Olarak Ayarla + +Bir Word dosyası bozulduğunda, varsayılan yükleme davranışı bir istisna fırlatır ve işlemi durdurur. Bir `LoadOptions` nesnesi yapılandırarak Aspose.Words'e **kurtarma modunu** `AutoRecover` olarak ayarlamasını söylersiniz; bu, zip paketini tarar, okunamayan bölümleri atlar ve bir araya getirebildiği her şeyi döndürür. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Neden AutoRecover?** +> Mümkün olduğunca çok şey okumaya çalışır ve belge nesnesinin kullanılabilir olmasını sağlar. `RecoveryMode.NoRecovery` seçerseniz, yükleme ilk bozulmada başarısız olur ve **bozuk docx dosyasını kurtarma** senaryolarının amacını bozar. + +## Adım 2: Belgeyi Yapılandırılmış Seçeneklerle Yükle + +Kurtarma modu ayarlandığına göre, dosyayı güvenle açmayı deneyebilirsiniz. `"YOUR_DIRECTORY/input.docx"` ifadesini hasarlı dosyanızın gerçek yolu ile değiştirin. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Dosya sadece kısmen bozulmuşsa, `Document` örneği yine de oluşturulacaktır. Ek doğrulama gerekiyorsa daha sonra `document.IsStructureValid` kontrol edebilirsiniz. + +## Adım 3: Algılanan Formatı Doğrula + +Aspose.Words otomatik olarak orijinal formatı (DOC, DOCX, ODT, vb.) algılar. Bu değeri yazdırmak, kütüphanenin dosyayı doğru tanıdığını doğrulamanıza yardımcı olur; bu, bir **bozuk docx dosyasını kurtarma** işleminden sonra hızlı bir mantık kontrolüdür. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Tipik çıktı: + +``` +Loaded with Docx format. +``` + +Bazı bölümler eksik olsa bile, format algılaması yine de başarılı olur—bu da **bozuk docx dosyasını kurtarma** iş akışları için bir başka avantajdır. + +## Adım 4: Alabildiğinizi Çıkarın + +Belge yüklendikten sonra, onu herhangi bir sağlıklı Word dosyası gibi kullanabilirsiniz. Aşağıda düz metni çıkaran ve konsola yazdıran kompakt bir örnek bulunuyor. Bu, **hasarlı word dosyasını okuma** içeriğini çökme olmadan yapabileceğinizi gösterir. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Orijinal dosyada bozulmuş tablolar veya görseller varsa, bunlar metin çıktısından basitçe çıkarılacaktır. Belgenin geri kalanı ise sağlam kalır. + +## Adım 5: Temiz Bir Kopya Kaydedin (İsteğe Bağlı) + +Kurtarma sonrası genellikle kullanıcıya yeni, temiz bir dosya sürümü vermek istersiniz. Aynı formatta kaydetmek, sonraki süreçlerle uyumluluğu sağlar. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Artık bir **hasarlı docx dosyasını kurtarma** dosyanız var; bunu güvenle bir e-postaya ekleyebilir veya başka bir servise aktarabilirsiniz. + +## Tam Çalışan Örnek + +Hepsini bir araya getirerek, işte tam ve çalıştırmaya hazır program. Yeni bir konsol projesine yapıştırın, dosya yollarını ayarlayın ve F5 tuşuna basın. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Beklenen çıktı** (dosyanın tek bir paragraf “Hello world!” ve bazı bozuk XML içerdiğini varsayarsak): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Programın hiç çökmediğine dikkat edin—kaynak dosya kısmen bozuk olsa bile. Bu, Aspose.Words kullanarak **bozuk docx dosyasını kurtarma** özüdür. + +## Yaygın Sorular ve Kenar Durumları + +### Dosya tamamen okunamazsa ne olur? + +`AutoRecover` bile sınırlara sahiptir. Zip konteyneri kendisi tamir edilemeyecek kadar bozulmuşsa, Aspose.Words bir `CorruptedFileException` fırlatır. Bu durumda **bozuk docx dosyasını kurtarma** tekrar denemeden önce üçüncü taraf bir zip onarım aracına ihtiyaç duyabilirsiniz. + +### Diğer formatları (ör. `.doc`, `.odt`) kurtarabilir miyim? + +Kesinlikle. Aynı `LoadOptions` Aspose.Words'ün desteklediği tüm formatlar için çalışır. Sadece dosya uzantısını değiştirin, kütüphane orijinal formatı otomatik olarak algılar. Bu, `.doc` veya `.rtf` gibi **hasarlı docx** benzeri dosyaları da aynı kodla kurtarabileceğiniz anlamına gelir. + +### Büyük belgeleri tümünü belleğe yüklemeden nasıl yönetebilirim? + +Gigabayt boyutundaki dosyalar için `LoadOptions.LoadFormat` gibi **yükleme seçeneklerini** etkinleştirebilir veya belgeyi sayfa sayfa akış olarak işleyebilirsiniz. Ancak, kurtarma algoritması yine de tüm paketi okumak zorunda, bu yüzden çok büyük bozuk dosyalar için daha yüksek bellek kullanımı bekleyin. + +### Hangi bölümlerin kaybolduğunu öğrenmenin bir yolu var mı? + +Yüklemeden sonra `document.GetChildNodes(NodeType.Any, true)` inceleyebilir ve sayıyı beklenen bir temel ile karşılaştırabilirsiniz. Eksik tablolar, görseller veya başlıklar düğüm koleksiyonunda basitçe bulunmaz. Bu, tam olarak neyin **hasarlı docx dosyasını kurtarma** olduğunu kaydetmenizi ve kullanıcıyı bilgilendirmenizi sağlar. + +## Güvenilir Kurtarma İçin Profesyonel İpuçları + +- **Giriş dosyasının boyutunu doğrulayın** yüklemeden önce; sıfır baytlık bir dosya her zaman başarısız olur. +- **`RecoveryMode` sonucunu kaydedin** `DocumentLoadingException` yakalayarak ve istisna mesajını saklayarak; genellikle atlanan bölümler hakkında ipuçları içerir. +- **Kurtarmayı arka plan iş parçacığında çalıştırın** bir web hizmetinde yüklemeleri işliyorsanız—bu, isteğin yanıt vermesini sağlar. +- **Bir checksum ile birleştirin** (ör. MD5) kurtarılan dosyanın orijinalden farklı olup olmadığını tespit etmek için; ardından her iki sürümü de tutup tutmayacağınıza karar verebilirsiniz. + +## Sonuç + +C#'ta **bozuk docx dosyasını kurtarma** işlemini `AutoRecover` olarak **kurtarma modunu ayarlayarak**, belgeyi güvenli bir şekilde yükleyerek, hayatta kalan metni çıkararak ve isteğe bağlı olarak temiz bir kopya kaydederek nasıl yapacağımızı gösterdik. Bu yaklaşım, istisna fırlatacak **docx dosyasını nasıl yükleyeceğinizi** sağlar ve harici araçlar olmadan **hasarlı word dosyasını okuma** içeriği için güvenilir bir yol sunar. + +Sonraki adımlar? Farkı görmek için `RecoveryMode.AutoRecover` yerine `RecoveryMode.NoRecovery` deneyin veya şifre yönetimi ve font ikamesini kontrol eden `LoadOptions` özellikleriyle deneyler yapın. Ayrıca kurtarma rutinini, yüklemeleri kabul edip onarılmış bir dosya döndüren bir ASP.NET Core API'sine entegre edebilirsiniz—kurumsal belge yönetim hatları için mükemmel. + +Word belge kurtarması hakkında daha fazla sorunuz mu var, ya da özel geri aramalarla **hasarlı docx dosyasını kurtarma** nasıl yapılır görmek ister misiniz? Aşağıya bir yorum bırakın, iyi kodlamalar! + +![Kurtarılmış bir belgenin illüstrasyonu – bozuk docx dosyasını kurtarma](https://example.com/images/recover-corrupted-docx.png "bozuk docx dosyasını kurtarma") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-markdownsaveoptions/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/_index.md index 4ad3c251c7..9e82f8a578 100644 --- a/words/turkish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/turkish/net/programming-with-markdownsaveoptions/_index.md @@ -41,6 +41,8 @@ Words Processing with MarkdownSaveOptions, .NET için Aspose.Words kütüphanesi | [Aspose.Words ile docx'i markdown olarak kaydet – Tam C# Rehberi](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Aspose.Words kullanarak docx dosyasını markdown formatına tam C# rehberiyle dönüştürün. | | [Word Görüntülerini Kaydet – Aspose ile Word'u Markdown'a Dönüştür](./save-word-images-convert-word-to-markdown-with-aspose/) | Aspose.Words for .NET kullanarak Word belgelerindeki görüntüleri kaydedin ve Word'u Markdown'a dönüştürün. | | [Word'ü C# ile Markdown'a Dönüştür – Görüntü Çıkarma ile Tam Rehber](./convert-word-to-markdown-in-c-full-guide-with-image-extracti/) | Aspose.Words for .NET kullanarak Word belgelerini markdown formatına dönüştürün ve görüntüleri ayıklayın. Tam C# rehberi. | +| [docx'i markdown olarak kaydet – Word Matematiklerini LaTeX'e Dışa Aktar Aspose.Words ile](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Aspose.Words for .NET kullanarak docx dosyasındaki matematik ifadelerini LaTeX formatına dönüştürerek markdown olarak kaydedin. | +| [Word'ü Markdown'a Dönüştürürken Görüntüleri Buluta Yükle](./upload-images-to-cloud-when-converting-word-to-markdown/) | Aspose.Words for .NET kullanarak Word belgelerini Markdown'a dönüştürürken görüntüleri buluta yüklemeyi öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..e84cd28646 --- /dev/null +++ b/words/turkish/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words kullanarak docx'i markdown olarak kaydedin – kelimeyi markdown'a + dönüştürmeyi öğrenin, denklemleri LaTeX'e dışa aktarın ve tek bir sorunsuz iş akışında + markdown görüntü çözünürlüğünü ayarlayın. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: tr +og_description: Aspose.Words ile docx'i markdown olarak kaydedin. Bu öğreticide, Word'ü + markdown'a nasıl dönüştüreceğiniz, denklemleri LaTeX'e nasıl dışa aktaracağınız + ve markdown görüntü çözünürlüğünü nasıl ayarlayacağınız gösterilmektedir. +og_title: docx'i markdown olarak kaydet – Word Matematiklerini LaTeX olarak dışa aktarma + tam rehberi +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx'i markdown olarak kaydet – Aspose.Words ile Word Matematiğini LaTeX'e + Dışa Aktar +url: /tr/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx'i markdown olarak kaydet – Word Math'i LaTeX'e Aktar Aspose.Words ile + +Hiç **docx'i markdown olarak kaydet**mek istediniz ama Office Math denklemlerinin net kalmasını sağlayamadınız mı? Tek başınıza değilsiniz. Çoğu geliştirici, varsayılan dönüşüm denklemleri bulanık görüntüler olarak kaydettiğinde, LaTeX içinde manuel olarak yeniden yazmak zorunda kalıyor. + +İyi haber: Aspose.Words bu işi sizin için halledebilir. Bu öğreticide **word'u markdown'a dönüştürecek**, motoru **denklemleri LaTeX'e dışa aktaracak** ve belgenin geri kalan kısmı için **markdown görüntü çözünürlüğünü ayarlayacak** bir komut oluşturacağız. Sonunda LaTeX‑hazır matematik ve yüksek çözünürlüklü görüntüler içeren temiz bir `.md` dosyanız olacak. + +## Öğrenecekleriniz + +- Office Math nesneleri içeren bir `.docx` dosyasının nasıl yükleneceği. +- `MarkdownSaveOptions` özelliklerinin **denklemleri LaTeX'e dışa aktar** ve **markdown görüntü çözünürlüğünü ayarla** işlevlerini nasıl kontrol ettiği. +- Herhangi bir .NET projesine yapıştırabileceğiniz tam, çalıştırılabilir bir C# kod parçacığı. +- Eksik fontlar veya desteklenmeyen denklem özellikleri gibi yaygın sorunların nasıl giderileceğine dair ipuçları. + +**Önkoşullar**: .NET 6+ (veya .NET Framework 4.6+), Aspose.Words for .NET lisansı ve C# temellerine aşina olmak. Bir konsol uygulaması oluşturabiliyorsanız, hazırsınız. + +--- + +## Adım 1 – docx'i markdown olarak kaydet: Word Dosyanızı Yükleyin + +İlk olarak, kaynak `.docx` dosyasına işaret eden bir `Document` nesnesine ihtiyacımız var. Bunu, bölümleri kopyalamaya başlamadan önce kitabı açmak gibi düşünün. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Neden önemli*: Belge içinde matematik yoksa, **denklemleri LaTeX'e dışa aktar** adımı bir işlem yapmayacak, ancak dönüşümün geri kalanı yine çalışacak. Bu kontrol, çıktınızda LaTeX bloklarının eksik olmasının nedenini anlamanızı sağlar. + +--- + +## Adım 2 – Denklemleri LaTeX'e Dışa Aktarmayı Yapılandırın + +Aspose.Words, Office Math'in nasıl render edileceğine karar vermenizi sağlar. Varsayılan olarak bunları PNG görüntülerine dönüştürür; bu yüzden birçok öğreticide dosya grenli bir markdown olur. `OfficeMathExportMode` değerini `LaTeX` olarak ayarlamak, temiz ve kopyala‑yapıştır‑hazır denklemler elde etmenizi sağlar. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Neden `OfficeMathExportMode.LaTeX`?* LaTeX, bilimsel yayıncılığın ortak dili. Markdown'ı daha sonra bir static‑site generator veya Jupyter notebook ile render ettiğinizde, denklemler her yakınlaştırma seviyesinde net görünür. + +--- + +## Adım 3 – Markdown Görüntü Çözünürlüğünü Ayarlayın (Matematik Dışı İçerik İçin) + +Matematiğe odaklansak da, çoğu Word belgesi resimler, grafikler veya gömülü SVG'ler içerir. `ImageResolution` özelliği, Aspose.Words'un bu varlıkları rasterleştirme biçimini kontrol eder. **300 DPI** değeri ekran ve baskı için ideal bir denge sunar. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*İpucu*: Markdown sadece webde gösterilecekse, dosya boyutunu düşük tutmak için çözünürlüğü **150 DPI**'ye düşürebilirsiniz. Öte yandan, baskı‑hazır PDF'ler için **600 DPI**'ye çıkarmak daha iyidir. + +--- + +## Adım 4 – Dönüşümü Çalıştırın – Word Math'i LaTeX'e Dönüştürün + +Her şey yapılandırıldıktan sonra, gerçek dönüşüm tek bir satırdır. Aspose.Words arka planda ağır işi yapar. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Beklenen çıktı**: Oluşturulan `.md` dosyasını açtığınızda aşağıdakine benzer bir şey görmelisiniz: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Önceki PNG parçacıklarının yerine LaTeX blokları (`$...$` ve `$$...$$`) yer alıyor. Alt kısımdaki görüntü hâlâ bir PNG ve 300 DPI olarak render edilmiş. + +--- + +## Adım 5 – Yaygın Kenar Durumları ve Çözüm Yöntemleri + +| Durum | Ne Olur | Nasıl Düzeltilir | +|-----------|--------------|------------| +| **Eksik fontlar** (ör. Cambria Math yüklü değil) | LaTeX çıktısı bilinmeyen semboller içerebilir. | Sunucuda eksik fontu kurun veya dönüşümden önce belgeye gömün. | +| **Karmaşık denklemler** (özel sınırlayıcılarla matris) | `LaTeX` moduna rağmen Aspose.Words bir görüntü oluşturabilir. | Aspose.Words'un en yeni sürümüne yükseltin; kütüphane sürekli olarak denklem desteğini artırıyor. | +| **Büyük belgeler** ( > 50 MB ) | Bellek baskısı `OutOfMemoryException` hatasına yol açabilir. | `LoadOptions` ile `LoadFormat.Docx` kullanıp dosyayı stream olarak yükleyin veya belgeyi bölümlere ayırarak dönüştürün. | +| **Görüntü boyutu çok büyük** | Markdown dosyası şişer, static‑site derlemelerini yavaşlatır. | Web‑only senaryolar için `ImageResolution` değerini 150 DPI'ye düşürün (bkz. Adım 3). | + +--- + +## Adım 6 – Hepsini Bir Araya Getirin: Tam Çalışan Örnek + +Aşağıda, `Program.cs` içine kopyalayıp yapıştırabileceğiniz *tam* bir console‑app programı bulunuyor. Konuştuğumuz tüm parçaları ve biraz ekstra hata yönetimini içeriyor. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Programı çalıştırın (`dotnet run`) ve **docx'i markdown olarak kaydet**irken her denklemi LaTeX olarak koruyan bir markdown dosyası elde edeceksiniz. Manuel kopyala‑yapıştır, matematik için çirkin raster görüntüler yok. + +--- + +## Sonuç + +Aspose.Words ile **docx'i markdown olarak kaydet**me sürecini, Word dosyasını yüklemekten **denklemleri LaTeX'e dışa aktar** ve **markdown görüntü çözünürlüğünü ayarla** yapılandırmasına kadar adım adım inceledik. Son kod parçacığı üretim ortamına hazır ve **word'u markdown'a dönüştür**mek isteyen herhangi bir .NET projesine eklenebilir. + +Sırada ne var? Oluşturduğunuz `.md` dosyasını Hugo ya da Jekyll gibi bir static‑site generator'a verin ve denklemlerinizin muhteşem şekilde render edildiğini izleyin. **word math latex**i başka formatlara (PDF, HTML) dönüştürmek isterseniz, sadece `MarkdownSaveOptions` yerine `PdfSaveOptions` ya da `HtmlSaveOptions` kullanın—`OfficeMathExportMode` bayrağı her iki durumda da aynı şekilde çalışır. + +Word dosyalarını Azure Blob depolamadan çekmek ya da bir API üzerinden stream etmek gibi bir akışınız varsa, aynı desen geçerli; sadece dosya‑sistemi `Document` yapıcısını stream‑tabanlı bir versiyonla değiştirin. + +Deneyimlerinizi paylaşın, bu yaklaşımın dönüşüm sorunlarınızı nasıl çözdüğünü yorumlarda bize bildirin. İyi kodlamalar! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md new file mode 100644 index 0000000000..93f3aef171 --- /dev/null +++ b/words/turkish/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/_index.md @@ -0,0 +1,248 @@ +--- +category: general +date: 2026-05-01 +description: Bir Word belgesini markdown’a dönüştürürken görüntüleri buluta yükleyin. + Docx’ten görüntüleri nasıl çıkaracağınızı ve Azure Blob depolama alanına nasıl kaydedeceğinizi + öğrenin. +draft: false +keywords: +- upload images to cloud +- convert word to markdown +- extract images from docx +- convert docx to markdown +- store images azure blob +language: tr +og_description: Bir Word belgesini markdown'a dönüştürürken görüntüleri buluta yükleyin. + Bu kılavuz, docx dosyasından görüntüleri nasıl çıkaracağınızı ve Azure Blob depolama + alanına nasıl kaydedeceğinizi gösterir. +og_title: Word'ü Markdown'a Dönüştürürken Görselleri Buluta Yükle +tags: +- Aspose.Words +- C# +- Azure Blob Storage +title: Word'ü Markdown'a Dönüştürürken Görselleri Buluta Yükle +url: /tr/net/programming-with-markdownsaveoptions/upload-images-to-cloud-when-converting-word-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word'ten Markdown'e Dönüştürürken Görselleri Buluta Yükleme + +Bir Word dosyasını markdown'a çevirirken **görselleri buluta yükleme** ihtiyacı hiç duydunuz mu? Tek başınıza değilsiniz—geliştiriciler sürekli belge dönüşümü ve varlık yönetimini aynı anda halletmeye çalışıyor ve ikisini de sorunsuz bir akışta yapmak, hareketli bir hedefi yakalamaya çalışmak gibi hissettirebiliyor. + +İyi haber? Aspose.Words ile bir .docx dosyasındaki her resim, grafik veya diyagramı çıkarabilir, doğrudan Azure Blob Storage'a itebilir ve oluşturulan markdown'un bu bulut URL'lerine yerel dosyalar yerine referans vermesini sağlayabilirsiniz. Bu öğreticide, kaynak belgeyi yüklemekten temiz bir markdown dosyası elde etmeye kadar tüm süreci adım adım inceleyeceğiz; markdown dosyanız Azure klasörünüze işaret edecek. + +Bu rehberi tamamladığınızda **docx'i markdown'a dönüştürebilecek**, **docx'ten görselleri çıkarabilecek** ve **görselleri Azure Blob'a depolayabilecek** olacaksınız—hepsi sadece birkaç C# satırıyla. Harici araçlar, manuel kopyala‑yapıştırma ve kesinlikle kırık görsel linkleri yok. + +## Gereksinimler + +- **.NET 6.0** veya daha yeni bir sürüm (kod .NET Core ve .NET Framework üzerinde de çalışır) +- **Aspose.Words for .NET** (NuGet paketi `Aspose.Words`) +- Bir **Azure Storage hesabı** ve içinde bir konteyner (ör. `images`) ve paylaşılan erişim anahtarı – dosyaları yüklemek için bağlantı dizesine ihtiyacınız olacak. +- C# ve async/await hakkında temel bilgi (isteğe bağlı ama faydalı). + +Bu bileşenler elinizdeyse harika—doğrudan çözüme geçelim. Yoksa, son bölümdeki “Önkoşullar” kısmı sizi hızlı kurulum adımlarına yönlendirecek. + +## Adım 1: Azure Blob Yardımcısını Kurun (Neden Önemli) + +Word belgesine dokunmadan önce, bir bayt dizisini Azure Blob Storage'a itebilen ve herkese açık bir URL döndüren küçük bir yardımcıya ihtiyacımız var. Bu soyutlama, dönüşüm mantığını temiz tutar ve ileride depolama sağlayıcısını değiştirmeyi kolaylaştırır. + +```csharp +using Azure; +using Azure.Storage.Blobs; +using Azure.Storage.Blobs.Models; + +/// +/// Simple wrapper around Azure Blob Storage for uploading images. +/// +public class AzureBlobUploader +{ + private readonly BlobContainerClient _container; + + public AzureBlobUploader(string connectionString, string containerName) + { + var service = new BlobServiceClient(connectionString); + _container = service.GetBlobContainerClient(containerName); + _container.CreateIfNotExists(PublicAccessType.Blob); + } + + /// + /// Uploads the supplied image bytes and returns a publicly accessible URL. + /// + public async Task UploadAsync(string fileName, byte[] content) + { + // Ensure the file name is safe for URLs. + var safeName = Uri.EscapeDataString(fileName); + var blob = _container.GetBlobClient(safeName); + using var stream = new MemoryStream(content); + await blob.UploadAsync(stream, overwrite: true); + return blob.Uri.ToString(); // This is the URL we’ll embed in markdown. + } +} +``` + +**Bu yardımcı neden?** +1. **Sorumlulukların ayrılması** – markdown dönüşüm kodu belge işleme üzerine odaklanır, HTTP detaylarıyla uğraşmaz. +2. **Yeniden kullanılabilirlik** – `UploadAsync` metodunu uygulamanızın başka yerlerinden (ör. kullanıcı‑yüklediği resimler) çağırabilirsiniz. +3. **Geleceğe hazırlık** – Amazon S3 veya Google Cloud Storage’a geçiş sadece aynı arayüzün yeni bir implementasyonu ile mümkün olur. + +> **İpucu:** Konteynerin erişim seviyesini `Blob` (herkese açık) olarak ayarlayın, ancak bu ayar herkesin görselleri okuyabileceği anlamına gelir. Özel senaryolar için her yükleme başına SAS token üretip bu URL'leri gömmek daha güvenli bir yaklaşımdır. + +## Adım 2: Kaynak‑Kaydetme Geri Çağrısını Tanımlayın (Dönüştürürken Yükleme Çekirdeği) + +Aspose.Words, bir belgeyi markdown olarak kaydettiğinizde normalde diske yazılacak her kaynağı (resim, grafik vb.) yakalamanıza izin verir. Bir `ResourceSavingCallback` sağlayarak, her kaynağı Azure Blob'a yükleyebilir ve yerel dosya adını bulut URL'siyle değiştirebiliriz. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Callback that uploads each extracted image to Azure Blob Storage +/// and tells Aspose.Words to use the resulting URL instead of a file. +/// +public class CloudResourceSaver : IResourceSavingCallback +{ + private readonly AzureBlobUploader _uploader; + + public CloudResourceSaver(AzureBlobUploader uploader) => _uploader = uploader; + + public void ResourceSaving(ResourceSavingArgs args) + { + // args.ResourceFileName contains the default file name (e.g., image001.png) + // args.ResourceStream gives us the raw bytes. + var fileName = args.ResourceFileName; + + // Convert the stream to a byte[] for uploading. + using var ms = new MemoryStream(); + args.ResourceStream.CopyTo(ms); + var bytes = ms.ToArray(); + + // NOTE: Aspose.Words calls this synchronously, so we block on the async upload. + // In a real‑world service you might use .GetAwaiter().GetResult() or redesign. + var uploadTask = _uploader.UploadAsync(fileName, bytes); + var url = uploadTask.GetAwaiter().GetResult(); + + // Tell Aspose.Words to use the cloud URL. + args.ResourceFileName = url; + + // Prevent Aspose.Words from creating a local copy. + args.AlreadyExists = true; + } +} +``` + +**Burada ne oluyor?** + +- **Çıkarma** – Aspose.Words her resim için bir akış (stream) verir. +- **Yükleme** – Bu akışı `AzureBlobUploader`'a göndeririz. +- **Değiştirme** – Markdown yazıcı, gelen herkese açık URL'yi alır ve markdown resim sözdizimine (`![](https://…)`) yazar. + +`args.AlreadyExists = true` ayarladığımız için geçici dosyalar dosya sisteminde birikir; bu, sunucusuz fonksiyonlar için temiz ve durumsuz bir işlemdir. + +## Adım 3: Markdown Kaydetme Seçeneklerini Yapılandırın (Her Şeyi Birleştirin) + +Şimdi geri çağırmayı Aspose.Words `MarkdownSaveOptions` içine ekliyoruz. Önemli bayraklar `ExportImagesAsBase64 = false` (dış linkler alıyoruz) ve `ResourceSavingCallback = new CloudResourceSaver(uploader)`. + +```csharp +using System; +using System.Threading.Tasks; +using Aspose.Words; +using Aspose.Words.Saving; + +public class DocxToMarkdownConverter +{ + private readonly AzureBlobUploader _uploader; + + public DocxToMarkdownConverter(AzureBlobUploader uploader) => _uploader = uploader; + + /// + /// Converts a .docx to markdown and uploads all images to Azure Blob. + /// Returns the path to the generated markdown file. + /// + public async Task ConvertAsync(string inputDocxPath, string outputMarkdownPath) + { + // Load the source document (convert word to markdown step starts here). + var doc = new Document(inputDocxPath); + + // Set up the callback that will upload each image. + var resourceSaver = new CloudResourceSaver(_uploader); + + // Configure markdown options. + var mdOptions = new MarkdownSaveOptions + { + ExportImagesAsBase64 = false, // Keep images as external links. + ResourceSavingCallback = resourceSaver, // Hook that uploads to Azure. + // Optional: you can tweak heading levels, code block fences, etc. + }; + + // Save the markdown file – Aspose.Words will invoke the callback for each image. + doc.Save(outputMarkdownPath, mdOptions); + + // The method is synchronous because Aspose.Words API is sync. + // Wrap in Task.Run if you need true async behavior. + await Task.CompletedTask; + return outputMarkdownPath; + } +} +``` + +**Base64 neden devre dışı bırakılıyor?** +`ExportImagesAsBase64` true olduğunda, Aspose her resmi doğrudan markdown içine bir data URI olarak gömer. Bu, **görselleri buluta yükleme** amacını boşa çıkar; markdown dosyası şişer ve görseller CDN'den ayrılamaz. Devre dışı bırakarak, Azure Blob'a işaret eden temiz dış linkler elde ederiz—modern bir static‑site jeneratörünün tam olarak beklediği şey. + +## Adım 4: Hepsini Bir Araya Getirin – Minimal Bir Konsol Uygulaması + +Aşağıda, çalıştırmaya hazır tam bir konsol programı bulunuyor. Yer tutucuları gerçek Azure bağlantı dizesi ve konteyner adıyla değiştirin. + +```csharp +using System; +using System.Threading.Tasks; + +class Program +{ + // 👉 Replace these with your own Azure storage details. + private const string AzureConnectionString = "DefaultEndpointsProtocol=https;AccountName=YOUR_ACCOUNT;AccountKey=YOUR_KEY;EndpointSuffix=core.windows.net"; + private const string ContainerName = "images"; + + static async Task Main(string[] args) + { + // Simple argument validation. + if (args.Length != 2) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + var inputPath = args[0]; + var outputPath = args[1]; + + // 1️⃣ Initialise the uploader. + var uploader = new AzureBlobUploader(AzureConnectionString, ContainerName); + + // 2️⃣ Create the converter that knows how to upload while converting. + var converter = new DocxToMarkdownConverter(uploader); + + // 3️⃣ Run the conversion. + await converter.ConvertAsync(inputPath, outputPath); + + Console.WriteLine($"✅ Conversion complete! Markdown saved to {outputPath}"); + Console.WriteLine("🖼️ Images have been uploaded to Azure Blob and linked in the markdown."); + } +} +``` + +### Beklenen Çıktı + +`sample.docx` içinde iki resim bulunan bir dosyayla programı çalıştırdığınızda şu çıktı oluşur: + +- `output.md` içinde aşağıdaki gibi markdown resim sözdizimi bulunur: + + ```markdown + ![Image 1](https://myaccount.blob.core.windows.net/images/image001.png) + ![Image 2 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-pdfsaveoptions/_index.md b/words/turkish/net/programming-with-pdfsaveoptions/_index.md index 7a34748fb5..af2ebf9116 100644 --- a/words/turkish/net/programming-with-pdfsaveoptions/_index.md +++ b/words/turkish/net/programming-with-pdfsaveoptions/_index.md @@ -54,6 +54,7 @@ Görüntü kalitesi seçeneklerini ayarlamayı, görüntüler için sıkıştır | [C#'ta Erişilebilir PDF Oluşturma – PDF Erişilebilirlik Eğitimi](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Aspose.Words for .NET kullanarak C# ile erişilebilir PDF dosyaları oluşturmayı adım adım öğrenin. | | [Word'den Erişilebilir PDF Oluşturma – Tam Kılavuz](./create-accessible-pdf-from-word-complete-guide/) | Bu kapsamlı rehberde, Word belgelerinden erişilebilir PDF oluşturmak için gerekli adımları ve ayarları öğrenin. | | [Erişilebilir PDF Oluşturma – PDF/UA Uyumluluğu için Adım‑Adım Kılavuz](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | PDF/UA uyumluluğu için erişilebilir PDF oluşturmayı adım adım öğrenin. | +| [Aspose.Words ile Belgeyi PDF Olarak Kaydet – Tam C# Kılavuzu](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words kullanarak C# ile bir belgeyi PDF formatına dönüştürmenin tüm adımlarını öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/turkish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..5dbba5b79e --- /dev/null +++ b/words/turkish/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Aspose.Words kullanarak C#'te belgeyi PDF olarak kaydetmeyi öğrenin. + Eğitim ayrıca Word'ü PDF'ye dönüştürmeyi, matematik LaTeX'i dışa aktarmayı ve eksik + yazı tiplerini ele almayı kapsar. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: tr +og_description: Aspose.Words ile belgeyi zahmetsizce PDF olarak kaydedin. Bu kılavuz + ayrıca Word'ü PDF'ye dönüştürmeyi, matematik LaTeX'ini dışa aktarmayı ve eksik fontları + yönetmeyi gösterir. +og_title: Aspose.Words ile Belgeyi PDF Olarak Kaydedin – Tam C# Kılavuzu +tags: +- Aspose.Words +- C# +- PDF generation +title: Aspose.Words ile Belgeyi PDF Olarak Kaydet – Tam C# Rehberi +url: /tr/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words ile Belgeyi PDF Olarak Kaydet – Tam C# Rehberi + +Hiç **belgeyi pdf olarak kaydetmenin** doğrudan bir Word dosyasından erişilebilirlik özelliklerini kaybetmeden nasıl yapılacağını merak ettiniz mi? Tek başınıza değilsiniz—geliştiriciler sürekli olarak Word'ü PDF'ye dönüştürürken matematik denklemlerini koruyan ve eksik yazı tiplerini sorunsuz bir şekilde yöneten güvenilir bir yol istiyor. + +Bu öğreticide, yalnızca **belgeyi pdf olarak kaydetmek** değil, aynı zamanda en son Aspose.Words for .NET kullanarak **word'ü pdf'ye dönüştürmek**, **math latex'i dışa aktarmak** ve **eksik yazı tiplerini ele almak** gibi adım adım bir çözümü ele alacağız. Sonunda, erişilebilirlik denetimleri için mükemmel, PDF/UA‑2 uyumlu dosyalar üreten, çalıştırmaya hazır bir C# programına sahip olacaksınız. + +## Gereksinimler + +- .NET 6 veya üzeri (kod .NET Core ve .NET Framework ile de çalışır) +- Aspose.Words for .NET 25.10 veya daha yeni – Aspose web sitesinden ücretsiz deneme sürümünü alabilirsiniz +- En az bir yüzen şekil ve bir matematik denklemi içeren basit bir Word belgesi (`input.docx`) (export‑math‑latex özelliğini görmek için) +- Visual Studio 2022 (veya istediğiniz herhangi bir IDE) + +> **Pro ipucu:** CI/CD hattındaysanız, projenizin dosyasına Aspose.Words NuGet paketini ekleyin: + +```xml + +``` + +Şimdi koda dalalım. + +## Adım 1: Kaynak Belgeyi Otomatik Kurtarma ile Yükleyin + +Gerçek dünya Word dosyalarıyla çalışırken bozuk bölümler veya eksik kaynaklarla karşılaşabilirsiniz. Otomatik kurtarmayı etkinleştirmek, yükleme sürecinin hiçbir zaman istisna fırlatmasını engeller. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Neden önemli:** +`RecoveryMode.AutoRecover`, hatalı girişte hattınızın çökmesini önler; bu, toplu olarak **word'ü pdf'ye dönüştürürken** özellikle kullanışlıdır. + +## Adım 2: Tam Erişilebilirlik İçin PDF Kaydetme Seçeneklerini Ayarlayın + +PDF/UA‑2, erişilebilir PDF'ler için ISO standardıdır. Birkaç bayrağı yapılandırarak ekran okuyucularının gezinebileceği bir dosya elde ederiz ve ayrıca matematik denklemlerinin gizli LaTeX olarak dışa aktarılmasını sağlarız. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Key points:** + +- **ExportFloatingShapesAsInlineTag** – ortaya çıkan PDF'nin orijinal düzeni korumasını ve anlamsal olarak doğru kalmasını sağlar. +- **OfficeMathExportMode.LaTeX** – **export math latex** gereksinimini karşılar, böylece sonraki araçların denklemleri gerektiğinde çıkarmasına izin verir. + +## Adım 3: Uyarıları Yakala (örn., Eksik Yazı Tipleri) + +Eksik yazı tipleri, belgeleri dönüştürürken yaygın bir sorundur. Aspose.Words, bu sorunları bir `WarningCallback` aracılığıyla raporlayabilir. Daha sonra bunları kaydedebilmeniz veya üzerine işlem yapabilmeniz için toplayacağız. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Neden önemlidir:** +Kaynak, sunucuda yüklü olmayan bir yazı tipi kullanıyorsa, PDF varsayılan bir yazı tipine geri döner ve bu da düzeni bozabilir. **eksik yazı tiplerini ele alarak** kullanıcıyı uyarabilir veya bir yedek gömebiliriz. + +## Adım 4: Belgeyi Erişilebilir PDF Olarak Kaydedin + +Şimdi gerçek an—dönüştürmeyi gerçekten gerçekleştirmek. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Her şey sorunsuz giderse, her denklem için gizli LaTeX ve yüzen şekiller için uygun etiketleme içeren bir PDF/UA‑2 dosyasına sahip olacaksınız. + +## Adım 5: Yakalanan Uyarıları Gözden Geçirin (İsteğe Bağlı ama Tavsiye Edilir) + +Kaydetme işleminden sonra, toplanan uyarılar üzerinde döngü kurarak bunları kaydedebilirsiniz. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Tipik çıktı şöyle görünebilir: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Bu mesajları erken görmek, **eksik yazı tiplerini ele almanıza** yardımcı olur ve son kullanıcıları etkilemeden önce önlem almanızı sağlar. + +## Tam Çalışan Örnek + +Her şeyi bir araya getirerek, işte tam, çalıştırmaya hazır program. Yer tutucu yolları kendi yollarınızla değiştirin. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Expected result:** +- `output.pdf` PDF/UA‑2 standardına uygundur. +- Tüm yüzen şekiller satır içi figürler olarak etiketlenir. +- Her Office Math nesnesi gizli LaTeX olarak görünür (PDF yapısını incelediğinizde görülebilir). +- Yazı tipiyle ilgili tüm sorunlar konsola yazdırılır, böylece dosyayı gönderirken **eksik yazı tiplerini ele alabilirsiniz**. + +![Word → Aspose.Words → Erişilebilir PDF (belgeyi pdf olarak kaydet) akışını gösteren diyagram](conversion-diagram.png "Belgeyi pdf olarak kaydetmek için akış diyagramı") + +*Görsel alt metni:* **Aspose.Words kullanarak belgeyi pdf olarak kaydetmenin diyagramı** + +## Yaygın Sorular ve Kenar Durumları + +### Daha eski bir Aspose.Words sürümü kullanıyorsam ne olur? + +`OfficeMathExportMode.LaTeX` bayrağı 25.10'da tanıtıldı. Daha eski sürümler için hâlâ **word'ü pdf'ye dönüştürebilirsiniz**, ancak matematik LaTeX olarak dışa aktarılmak yerine rasterleştirilecektir. En iyi erişilebilirlik için yükseltin. + +### Yedekleme önlemek için özel yazı tipleri gömebilir miyim? + +Evet. `Save` metodunu çağırmadan önce `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` olarak ayarlayın. Bu, PDF'nin gerekli glifleri içermesini zorlayarak **eksik yazı tiplerini ele almanıza** da yardımcı olur. + +### PDF/UA‑2 uyumluluğunu nasıl doğrularım? + +Dosyayı Adobe Acrobat Pro’da açın → “Print Production” → “Preflight”. “PDF/A‑2b” veya “PDF/UA‑2” profilini seçin; Acrobat herhangi bir ihlali raporlayacaktır. + +### Şifre korumalı Word dosyaları nasıl ele alınır? + +Belgeyi `Password` içeren bir `LoadOptions` ile yükleyin. Örnek: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +İşlem hattının geri kalanı değişmeden kalır. + +## Sonuç + +Aspose.Words ile C#'ta **belgeyi pdf olarak kaydetmek** için ihtiyacınız olan her şeyi ele aldık. Öğreticide ayrıca **word'ü pdf'ye dönüştürme**, **math latex'i dışa aktarma** ve **eksik yazı tiplerini ele alma** nasıl yapılır gösterildi—hepsi erişilebilir bir PDF/UA‑2 dosyası üretirken. + +Kodu çalıştırın, farklı `PdfSaveOptions` (ör. görüntü sıkıştırma, PDF/A‑2b) ile deneyler yapın ve belge‑işleme servisinize entegre edin. Daha ileri gitmeniz gerekiyorsa, Aspose’un PDF‑özel kütüphanesini son‑işleme veya dijital imzalar için keşfetmeyi düşünün. + +Ele almak istediğiniz başka senaryolar var mı? Yorum bırakmaktan çekinmeyin veya **PDF manipülasyonu**, **görüntü çıkarma** ve **toplu dönüşüm** üzerine diğer rehberlerimize göz atın. Kodlamanın tadını çıkarın! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-shapes/_index.md b/words/turkish/net/programming-with-shapes/_index.md index 31c7a1c477..8829bb5cf7 100644 --- a/words/turkish/net/programming-with-shapes/_index.md +++ b/words/turkish/net/programming-with-shapes/_index.md @@ -36,7 +36,7 @@ Aspose.Words for .NET'i kullanarak ve bu eğitimleri takip ederek, Word belgeler | [Aspose.Words ile Word'de Dikdörtgen Şekil Oluşturma – Adım Adım Kılavuz](./create-rectangle-shape-in-word-with-aspose-words-step-by-ste/) | Aspose.Words for .NET kullanarak Word belgesine dikdörtgen şekil eklemeyi ve özelliklerini ayarlamayı adım adım öğrenin. | | [C# kullanarak Word'de dikdörtgen şekli oluşturma – Adım adım kılavuz](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Aspose.Words for .NET ile C# kullanarak Word belgesine dikdörtgen şekli eklemeyi ve özelleştirmeyi adım adım öğrenin. | | [Aspose.Words Şekil Gölge Eğitimi – Word Şekline Gölge Ekleme C#'ta](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Aspose.Words for .NET kullanarak C# ile Word şekline gölge eklemeyi adım adım öğrenin. | - +| [Aspose.Words'ta Gölgeyi Taşıma – Tam C# Kılavuzu](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Aspose.Words kullanarak C# ile bir şeklin gölgesini nasıl taşıyacağınızı adım adım öğrenin. | | [Gölgelikli Dikdörtgen Şekilli Boş Word Belgesi Oluşturma – Adım Adım Kılavuz](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Aspose.Words for .NET kullanarak gölgelikli dikdörtgen şekilli boş bir Word belgesi oluşturmayı adım adım öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/turkish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..5c8ecce055 --- /dev/null +++ b/words/turkish/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: C# kullanarak Aspose.Words'ta bir şeklin gölgesini nasıl hareket ettireceğinizi + öğrenin. Şekle gölge eklemeyi, bulanıklığı değiştirmeyi, şeffaflığı ayarlamayı ve + gölgeyi dakikalar içinde döndürmeyi keşfedin. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: tr +og_description: C# kullanarak Aspose.Words'te bir şeklin gölgesini nasıl hareket ettireceğinizi + öğrenin. Bu öğreticide, şekle gölge ekleme, bulanıklığı değiştirme, şeffaflığı ayarlama + ve gölgeyi döndürme konuları gösterilmektedir. +og_title: Aspose.Words'ta Gölgeyi Nasıl Taşırsınız – Tam C# Rehberi +tags: +- Aspose.Words +- C# +- Document Automation +title: Aspose.Words'te Gölgeyi Nasıl Taşırsınız – Tam C# Kılavuzu +url: /tr/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words'ta Gölge Nasıl Taşınır – Tam C# Kılavuzu + +Hiç **gölgeyi nasıl taşıyacağınızı** bir Word belgesindeki şekil üzerinde, Word'ü manuel olarak açmadan merak ettiniz mi? Günlük işimde, şeklin gölgesini programatik olarak ayarlamam gerektiğinde sık sık karşılaştım—ister şık bir rapor, ister dinamik bir şablon olsun. İyi haber? Aspose.Words ile bunu birkaç satırda yapabilirsiniz ve aynı anda **şekle gölge ekleme**, **bulanıklığı nasıl değiştireceğinizi**, **saydamlığı nasıl ayarlayacağınızı** ve **gölgeyi nasıl döndüreceğinizi** de öğreneceksiniz. + +Bu öğreticide gerçek bir senaryoyu adım adım inceleyeceğiz: zaten bir şekil içeren mevcut bir DOCX dosyasını yüklemek, gölgenin konumunu, yumuşaklığını, opaklığını ve yönünü ayarlamak ve sonunda sonucu kaydetmek. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz yeniden kullanılabilir bir kod parçacığına sahip olacaksınız ve her özelliğin neden önemli olduğunu anlayacaksınız. + +## Önkoşullar – Başlamadan Önce Neye İhtiyacınız Var + +- **Aspose.Words for .NET** (sürüm 23.12 veya daha yeni). NuGet üzerinden `Install-Package Aspose.Words` komutuyla edinebilirsiniz. +- .NET 6+ geliştirme ortamı (Visual Studio, VS Code, Rider—ne tercih ederseniz). +- En az bir şekil (dikdörtgen, daire veya resim) içeren bir giriş Word dosyası (`input.docx`). +- C# sözdizimine temel aşinalık—özel bir şey gerekmez. + +Eğer bunlardan birine sahip değilseniz, bir an durup kütüphaneyi kurun; rehberin geri kalanı paketin zaten referans alındığını varsayar. + +## Adım 1: Belgeyi Yükleyin ve Hedef Şekli Alın – **Gölgeyi Nasıl Taşıyacağınız** Burada Başlıyor + +İlk yaptığımız şey, kaynak belgeyi yüklemek ve değiştirmek istediğimiz şekli bulmaktır. Aspose.Words, her nesneyi (paragraflar, tablolar, şekiller) bir ağaçta düğüm olarak ele alır, bu yüzden doğrudan sorgulayabiliriz. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Bu neden önemli:** Belgeyi bir kez yükleyip aynı `Document` örneğini yeniden kullanmak verimlidir. `GetChild` çağrısı, indeks aralık dışındaysa `null` döndürdüğü için eksik şekilleri sorunsuz bir şekilde ele almamıza olanak tanır. + +## Adım 2: Bulanıklık Yarıçapını Ayarlayın – **Bulanıklığı Nasıl Değiştireceğinizi** Öğrenin + +Yumuşak bir gölge profesyonel görünürken, sert bir kenar ucuz durabilir. `BlurRadius` özelliği, yumuşaklığı puan cinsinden kontrol eder (1 pt ≈ 1/72 inç). Hadi bunu 8 pt'ye çıkaralım. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Pro ipucu:** Varsayılan bulanıklık 0.5 pt'dir. 5 pt üzerindeki değerler genellikle fark edilir, ancak çok büyük yapmaktan kaçının—şekil sayfadan kopmuş gibi görünebilir. + +## Adım 3: Saydamlığı Ayarlayın – **Saydamlığı Nasıl Ayarlayacağınız** Sorunun Cevabı + +Saydamlık, gölgenin ne kadar şeffaf olduğunu belirler. `0` değeri tamamen opak, `1` değeri tamamen görünmez demektir. İnce bir etki için `0.3` ( %30 şeffaf) kullanacağız. + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Neden ilgilenebilirsiniz:** Şekil koyuysa, tamamen opak bir gölge alt metni boğabilir. Saydamlığı ayarlamak, belgeyi okunabilir tutarken derinlik kazandırır. + +## Adım 4: Gölgeyi Taşıyın – **Gölgeyi Nasıl Taşıyacağınız**'ın Özeti + +`Distance` özelliği, gölgenin şekilden ne kadar uzakta olduğunu puan cinsinden tanımlar. Daha büyük bir mesafe gölgeyi daha uzağa iter ve daha dramatik bir etki yaratır. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Küçük bir kaydırma gerekirse ne olur?** `Distance` değerini `0` yaparsanız gölge doğrudan şeklin arkasına oturur; bu, kabartma etkileri için faydalı olabilir. + +## Adım 5: Işık Kaynağını Döndürün – **Gölgeyi Nasıl Döndüreceğinizi** Çözmek + +Gölge sadece aşağı doğru düşmez; ışık kaynağının açısına göre yön alır. `Angle` özelliği (derece cinsinden) gölgeyi şeklin etrafında döndürür. Hadi 45° eğelim. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Hızlı deney:** Sağ tarafta bir gölge için `90`, sola eğik bir gölge için `-30` deneyin. Görsel değişim anında görülür. + +## Adım 6: Belgeyi Kaydedin – **Şekle Gölge Ekle** Sonucunu Görmek + +Gölgeyi ayarladığımıza göre belgeyi diske geri yazacağız. Orijinali üzerine yazabilir ya da yeni bir dosya oluşturabilirsiniz; örnek yeni bir çıktı dosyası kullanıyor. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Beklenen çıktı:** `output.docx` dosyasını açın. Şeklin gölgesi daha yumuşak, hafifçe kaydırılmış, yarı‑saydam ve 45° açıyla görünecek. `input.docx` ile yan yana karşılaştırırsanız fark hemen anlaşılır. + +### Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +Aşağıda tüm program tek bir blokta verilmiştir. Yeni bir konsol projesine yapıştırın, `YOUR_DIRECTORY` ifadesini gerçek bir klasör yolu ile değiştirin ve çalıştırın. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Yaygın Sorular ve Kenar Durumları + +### Belge birden fazla şekle sahipse ne olur? + +Tüm şekiller üzerinde döngü kurabilirsiniz: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Şu anda gölgesi olmayan bir şekle gölge ekleyebilir miyim? + +Kesinlikle. `ShadowFormat` nesnesi her zaman mevcuttur; sadece etkinleştirmeniz yeterlidir: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Bu, resimler ve SmartArt ile çalışır mı? + +Evet. `Shape` sınıfından türetilen her düğüm—resimler, grafikler ve SmartArt dahil—`ShadowFormat` özelliğine sahiptir. Aynı özellikler geçerlidir. + +### Gölge rengini nasıl kontrol ederim? + +`Color` özelliğini kullanın: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Uyumluluk Endişeleri? + +Aspose.Words 23.12+ .NET 6, .NET Core 3.1 ve .NET Framework 4.6.2+ sürümlerini destekler. Gösterilen API bu sürümlerde kararlıdır. + +## Sonuç + +**gölgeyi nasıl taşıyacağınızı** bir şekil üzerinde Aspose.Words ile nasıl yapacağınızı yeni öğrendik ve aynı zamanda **şekle gölge ekleme**, **bulanıklığı nasıl değiştireceğinizi**, **saydamlığı nasıl ayarlayacağınızı** ve **gölgeyi nasıl döndüreceğinizi** de gösterdik. Tam, çalıştırılabilir örnek, herhangi bir şeklin gölgesini saniyeler içinde ayarlamanıza olanak tanır, belgelerinize Word'ü hiç açmadan şık ve profesyonel bir görünüm kazandırır. + +Bir sonraki adıma hazır mısınız? Bu gölge ayarlarını **koşullu biçimlendirme** ile birleştirin—örneğin, yalnızca başlıklara veya belirli bir boyutu aşan grafiklere daha derin bir gölge uygulayın. Ya da şeklin kendisi için **gradient doldurmalar** keşfederek gerçekten göz alıcı bir tasarım yaratın. + +Herhangi bir sorunla karşılaşırsanız, aşağıya yorum bırakın. İyi kodlamalar ve gölgeleriniz her zaman istediğiniz yerde kalsın! + +![Bir şekil üzerindeki gölgenin hareket ettirilmesinin etkisini gösteren diyagram – gölgeyi nasıl taşıma örneği](https://example.com/images/shadow-demo.png "gölgeyi nasıl taşıma örneği") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/basic-conversions/_index.md b/words/vietnamese/net/basic-conversions/_index.md index 0cb9d585c5..04bc00c5fd 100644 --- a/words/vietnamese/net/basic-conversions/_index.md +++ b/words/vietnamese/net/basic-conversions/_index.md @@ -26,6 +26,7 @@ Basic Conversions hướng dẫn bạn cách chuyển đổi tài liệu cơ b | [Chuyển đổi tệp Word sang PDF](./docx-to-pdf/) Tìm hiểu cách dễ dàng chuyển đổi tệp Word sang PDF bằng Aspose.Words cho .NET với hướng dẫn của chúng tôi. Hoàn hảo cho các nhà phát triển đang tìm kiếm chuyển đổi tài liệu nhanh chóng và đáng tin cậy. | | [Chuyển đổi Word sang PDF trong C# bằng Aspose.Words – Hướng dẫn](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Hướng dẫn chi tiết cách chuyển đổi tài liệu Word sang PDF trong C# sử dụng Aspose.Words, kèm ví dụ mã nguồn. | | [Lưu Word thành PDF với Aspose.Words – Hướng dẫn C# đầy đủ](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Hướng dẫn chi tiết cách lưu tài liệu Word thành PDF bằng Aspose.Words trong C#, kèm ví dụ mã nguồn. | +| [Lưu Word thành PDF với Aspose.Words – Hướng dẫn đầy đủ](./save-word-as-pdf-with-aspose-words-complete-guide/) | Hướng dẫn chi tiết cách lưu tài liệu Word thành PDF bằng Aspose.Words, kèm ví dụ mã nguồn và các tùy chọn chuyển đổi. | | [Lưu docx thành PDF với Aspose.Words – Hướng dẫn C# đầy đủ](./save-docx-as-pdf-with-aspose-words-complete-c-guide/) | Hướng dẫn chi tiết cách lưu tài liệu docx thành PDF bằng Aspose.Words trong C#, kèm ví dụ mã nguồn. | | [Chuyển đổi Docx sang Byte](./docx-to-byte/) | Tìm hiểu cách chuyển đổi Docx sang mảng byte trong .NET bằng Aspose.Words để xử lý tài liệu hiệu quả. Có kèm hướng dẫn từng bước. | | [Chuyển đổi Docx sang Epub](./docx-to-epub/) | Chuyển đổi DOCX sang EPUB dễ dàng với Aspose.Words cho .NET. Làm theo hướng dẫn của chúng tôi để tích hợp liền mạch vào các ứng dụng .NET của bạn. | diff --git a/words/vietnamese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md b/words/vietnamese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md index cf32cbda3a..2c6ce81451 100644 --- a/words/vietnamese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md +++ b/words/vietnamese/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/_index.md @@ -1,24 +1,22 @@ --- category: general -date: 2025-12-29 -description: Cách xuất LaTeX từ Word bằng Aspose.Words – học cách chuyển Word sang - LaTeX, lưu file docx dưới dạng txt và xử lý các phương trình trong văn bản thuần. +date: 2026-05-01 +description: Tìm hiểu cách xuất LaTeX từ tệp Word, chuyển đổi Word sang txt và giữ + nguyên bảng khi sử dụng Aspose.Words trong C#. draft: false keywords: - how to export latex -- convert word to latex -- how to save txt +- convert word to txt +- convert word to plain text - save docx as txt -- convert word equations latex +- how to preserve tables language: vi -og_description: Cách xuất LaTeX từ Word bằng Aspose.Words. Hướng dẫn này chỉ cho bạn - cách chuyển Word sang LaTeX, lưu file docx dưới dạng txt và giữ nguyên các công - thức. -og_title: Cách xuất LaTeX từ Word – Hướng dẫn nhanh C# +og_description: Khám phá cách xuất LaTeX từ Word, chuyển Word sang văn bản thuần và + giữ nguyên bố cục bảng với Aspose.Words. +og_title: Cách xuất LaTeX từ Word – Hướng dẫn C# đầy đủ tags: - Aspose.Words - C# -- LaTeX - Document Conversion title: Cách xuất LaTeX từ Word – Hướng dẫn từng bước url: /vi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ @@ -28,178 +26,215 @@ url: /vi/net/basic-conversions/how-to-export-latex-from-word-step-by-step-guide/ {{< blocks/products/pf/main-container >}} {{< blocks/products/pf/tutorial-page-section >}} -# Cách xuất LaTeX từ Word – Hướng dẫn từng bước +# Cách xuất LaTeX từ Word – Hướng dẫn C# đầy đủ -Bạn đã bao giờ tự hỏi **cách xuất LaTeX từ Word** mà không mất bất kỳ công thức Office Math khó xử nào chưa? 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 họ cố gắng *convert Word to LaTeX* cho các bài báo học thuật, báo cáo khoa học, hoặc các pipeline xuất bản tự động. +Bạn đã bao giờ tự hỏi **cách xuất LaTeX** từ một tài liệu Word mà không mất bất kỳ công thức toán học nào chưa? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần chuyển một tệp .docx chứa Office Math thành LaTeX sạch sẽ đồng thời **convert Word to txt** cho quá trình xử lý tiếp theo. Trong hướng dẫn này, chúng tôi sẽ trình bày một giải pháp thực tế, sẵn sàng chạy mà **giữ lại bảng**, cung cấp cho bạn một tệp văn bản thuần và giữ nguyên đánh dấu LaTeX ở đúng nơi bạn cần. -Trong hướng dẫn này, chúng tôi sẽ đi qua một ví dụ C# hoàn chỉnh, sẵn sàng chạy, cho thấy **cách xuất LaTeX** bằng cách sử dụng Aspose.Words, giải thích **cách lưu txt** với đánh dấu LaTeX, và thậm chí đề cập đến các chi tiết tinh tế của **convert word equations latex** để không có gì bị mất trong quá trình chuyển đổi. +Chúng tôi sẽ bao phủ mọi thứ từ việc tải tệp nguồn đến việc tinh chỉnh `TxtSaveOptions` để đầu ra vừa dễ đọc cho con người vừa thân thiện với máy. Khi kết thúc, bạn sẽ có thể **save docx as txt**, **convert Word to plain text**, và biết **how to preserve tables** trong quá trình xuất. Không có script bên ngoài, không sao chép‑dán thủ công—chỉ có mã C# thuần mà bạn có thể chèn vào bất kỳ dự án .NET nào. -> **Mẹo:** Cách tiếp cận này cũng hoạt động cho bất kỳ tệp .docx nào bạn có—chỉ cần chỉ đường dẫn tệp khác cho mã. +## Những gì bạn cần + +- **Aspose.Words for .NET** (phiên bản mới nhất, 2024.x hoặc mới hơn). Gói NuGet là `Aspose.Words`. +- Môi trường phát triển .NET (Visual Studio, VS Code, Rider—bất kỳ cái nào cũng được). +- Tệp Word (`.docx`) chứa các phương trình Office Math và ít nhất một bảng (để chúng ta có thể thấy phép màu giữ bảng). + +Chỉ vậy thôi. Nếu bạn đã có những thứ này, hãy tiếp tục đọc; nếu không, hãy tải gói NuGet và một mẫu DOCX trước khi chúng ta đi sâu hơn. --- -## Những gì bạn cần +## Cách xuất LaTeX từ tài liệu Word -Trước khi bắt đầu, hãy chắc chắn rằng bạn đã chuẩn bị đầy đủ các yêu cầu sau: +Dưới đây là phần cốt lõi của hướng dẫn—ba bước ngắn gọn trả lời câu hỏi **how to export latex** đồng thời xử lý các mục tiêu phụ là **convert word to txt**, **convert word to plain text**, **save docx as txt**, và **how to preserve tables**. -| Yêu cầu | Lý do quan trọng | -|--------------|----------------| -| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.Words hỗ trợ các runtime .NET hiện đại. | -| **Aspose.Words for .NET** NuGet package (`Aspose.Words`) | Thư viện thực hiện công việc nặng nề của việc phân tích Word và xuất LaTeX. | -| **A sample .docx** containing at least one Office Math equation | Một tệp .docx mẫu chứa ít nhất một công thức Office Math để xem quá trình chuyển đổi LaTeX hoạt động. | -| **Visual Studio 2022** (or any IDE you like) | Giúp việc gỡ lỗi và chạy mẫu trở nên đơn giản. | +### Bước 1: Tải tệp DOCX -Nếu bạn chưa cài đặt gói NuGet, chạy: +Đầu tiên chúng ta cần đọc tài liệu Word vào một đối tượng `Aspose.Words.Document`. Bước này giống nhau dù bạn sau này **convert word to txt** hay **save docx as txt**. -```bash -dotnet add package Aspose.Words +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Replace with the path to your source file +string inputPath = @"C:\Samples\input.docx"; + +Document doc = new Document(inputPath); ``` -Xong rồi—không cần DLL bổ sung, không cần COM interop, chỉ một thư viện quản lý sạch sẽ. +> **Why this matters:** Việc tải tệp tạo ra một biểu diễn trong bộ nhớ của tất cả các thành phần Word—đoạn văn, bảng và các đối tượng Office Math. Nếu không có đối tượng này, bạn không thể thao tác các tùy chọn xuất. ---- +### Bước 2: Cấu hình `TxtSaveOptions` cho LaTeX và Bố cục Bảng -## Cách xuất LaTeX từ Word – Tổng quan +Lớp `TxtSaveOptions` cho phép bạn kiểm soát chính xác cách tệp văn bản thuần được tạo ra. Hai thuộc tính là chìa khóa cho kịch bản của chúng ta: -Dưới đây là bức tranh tổng thể những gì chúng ta sẽ thực hiện: +| Thuộc tính | Chức năng | Lý do cần | +|------------|-----------|-----------| +| `OfficeMathExportMode` | Xác định cách Office Math được hiển thị. Đặt nó thành `LaTeX` sẽ chuyển các phương trình sang cú pháp LaTeX. | Đây là cốt lõi của **how to export latex**. | +| `PreserveTableLayout` | Khi `true`, Aspose thêm khoảng trắng để các bảng giữ dạng lưới. | Điều này đáp ứng **how to preserve tables** trong khi bạn **convert word to txt**. | -1. **Load** tài liệu Word nguồn (`.docx`). -2. **Configure** `TxtSaveOptions` để mọi đối tượng Office Math được xuất dưới dạng mã LaTeX. -3. **Save** tài liệu dưới dạng tệp plain‑text (`.txt`) mà bạn có thể đưa trực tiếp vào bất kỳ trình biên dịch LaTeX nào. +```csharp +TxtSaveOptions saveOptions = new TxtSaveOptions +{ + // Export all Office Math as LaTeX code + OfficeMathExportMode = OfficeMathExportMode.LaTeX, -![Cách xuất LaTeX từ Word ví dụ](image.png "Cách xuất LaTeX từ Word") + // Keep tables readable in the plain‑text output + PreserveTableLayout = true +}; +``` ---- +> **Pro tip:** Nếu bạn chỉ cần LaTeX thô mà không có bất kỳ định dạng bảng nào, đặt `PreserveTableLayout` thành `false`. Tệp sẽ nhỏ hơn, nhưng bạn sẽ mất dấu hiệu bảng trực quan. -## Bước 1: Tải tài liệu Word +### Bước 3: Lưu tài liệu dưới dạng Văn bản Thuần -Đầu tiên—mở tệp .docx bạn muốn chuyển đổi. Lớp `Document` trừu tượng hoá mọi XML bên dưới, cung cấp cho bạn một mô hình đối tượng thân thiện. +Bây giờ chúng ta ghi tài liệu ra tệp `.txt` bằng các tùy chọn vừa định nghĩa. Dòng lệnh duy nhất này thực hiện **convert word to plain text**, **save docx as txt**, và dĩ nhiên, **how to export latex** đồng thời. ```csharp -using Aspose.Words; -using Aspose.Words.Saving; +// Output path – change as needed +string outputPath = @"C:\Samples\output.txt"; -// Replace with the actual path to your .docx file -string inputPath = @"C:\MyProjects\WordSamples\input.docx"; - -// Load the document into memory -Document doc = new Document(inputPath); +doc.Save(outputPath, saveOptions); ``` -**Tại sao điều này quan trọng:** -Việc tải tệp sớm cho phép chúng ta kiểm tra nội dung của nó (ví dụ, đếm số công thức) trước khi quyết định cách tuần tự hoá. Nếu tệp bị hỏng, `Document` sẽ ném ra một ngoại lệ rõ ràng, giúp bạn tránh kết quả đầu ra bí ẩn sau này. +Sau khi lệnh hoàn thành, mở `output.txt`. Bạn sẽ thấy: ---- +- Các đoạn mã LaTeX như `\frac{a}{b}` cho mọi phương trình Office Math. +- Các bảng được hiển thị bằng ký tự `|` và `-`, giữ căn chỉnh cột. +- Các đoạn văn thông thường dưới dạng văn bản thuần, sẵn sàng cho bất kỳ bộ phân tích nào tiếp theo. -## Bước 2: Cấu hình TxtSaveOptions để xuất LaTeX +### Ví dụ Hoạt động Đầy đủ -Phép màu xảy ra trong `TxtSaveOptions`. Bằng cách đặt `OfficeMathExportMode` thành `LaTeX`, mọi đối tượng Office Math sẽ được chuyển đổi thành biểu diễn LaTeX tương ứng. +Kết hợp tất cả lại, đây là một chương trình tự chứa mà bạn có thể biên dịch và chạy ngay hôm nay: ```csharp -// Prepare save options – this is where we tell Aspose to emit LaTeX for equations -TxtSaveOptions txtOptions = new TxtSaveOptions +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class ExportLatexDemo { - // Export Office Math equations as LaTeX strings - OfficeMathExportMode = OfficeMathExportMode.LaTeX, - - // Optional: preserve line breaks exactly as they appear in Word - PreserveTableLayout = true, - - // Optional: specify UTF‑8 encoding (important for special symbols) - Encoding = System.Text.Encoding.UTF8 -}; + static void Main() + { + // 1️⃣ Load the source DOCX + string inputPath = @"C:\Samples\input.docx"; + Document doc = new Document(inputPath); + + // 2️⃣ Configure export options for LaTeX and tables + TxtSaveOptions options = new TxtSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + PreserveTableLayout = true + }; + + // 3️⃣ Save as plain‑text (this is the step that does the conversion) + string outputPath = @"C:\Samples\output.txt"; + doc.Save(outputPath, options); + + Console.WriteLine($"✅ Done! LaTeX exported and tables preserved at: {outputPath}"); + } +} ``` -**Tại sao chúng tôi chọn các thiết lập này:** +**Kết quả mong đợi** (trích đoạn): -- `OfficeMathExportMode.LaTeX` là chế độ duy nhất đảm bảo chuyển đổi toán học trung thực. -- `PreserveTableLayout` giữ bảng trông giống như trong Word, hữu ích khi bạn nhúng đầu ra vào môi trường LaTeX `tabular`. -- UTF‑8 đảm bảo các ký tự như “α”, “β”, hoặc “∑” tồn tại qua quá trình chuyển đổi. +``` +This is a sample paragraph. + +| Column A | Column B | +|----------|----------| +| 1 | 2 | +| 3 | 4 | + +Here is an equation in LaTeX: +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +``` -Nếu bạn cần **convert word to latex** mà không có lớp bao plain‑text, bạn có thể chuyển sang `SaveFormat.LaTeX`—chỉ là một mẹo nhanh cho các kịch bản nâng cao. +Chú ý cách bảng giữ lưới và phương trình xuất hiện dưới dạng LaTeX sạch sẽ. Đó là điểm mạnh khi bạn **convert word to txt** và vẫn cần một biểu diễn trung thực của cả cấu trúc và toán học. --- -## Bước 3: Lưu tài liệu dưới dạng tệp văn bản +## Mẹo khi Chuyển Word sang TXT và Giữ Bảng -Bây giờ chúng ta ghi văn bản chứa LaTeX vào đĩa. Tệp `.txt` kết quả có thể được đổi tên thành `.tex` sau này, hoặc truyền trực tiếp vào trình biên dịch LaTeX. +Mặc dù cách tiếp cận ba bước hoạt động cho hầu hết các trường hợp, các dự án thực tế thường gặp những tình huống bất ngờ. Dưới đây là những gợi ý thực tế giúp quy trình **convert word to plain text** của bạn trở nên vững chắc. -```csharp -// Destination file – you can change the extension to .tex if you prefer -string outputPath = @"C:\MyProjects\WordSamples\output.txt"; +### Sử dụng Mã hóa Nhất quán -// Save using the configured options -doc.Save(outputPath, txtOptions); +`TxtSaveOptions` mặc định là UTF‑8, hỗ trợ hầu hết các ký tự. Nếu bạn cần một trang mã khác (ví dụ, hệ thống cũ yêu cầu Windows‑1252), hãy đặt thuộc tính `Encoding`: -Console.WriteLine($"✅ LaTeX export complete! File saved to: {outputPath}"); +```csharp +options.Encoding = System.Text.Encoding.GetEncoding(1252); ``` -**Bạn sẽ thấy gì trong `output.txt`:** +### Cắt bớt Khoảng trắng Dư thừa -``` -\begin{equation} -E = mc^{2} -\end{equation} +Các bảng có nhiều cột có thể tạo ra các dòng dài. Sau khi lưu, bạn có thể muốn xử lý hậu kỳ tệp để gộp nhiều khoảng trắng thành một tab duy nhất: + +```csharp +string content = System.IO.File.ReadAllText(outputPath); +content = System.Text.RegularExpressions.Regex.Replace(content, @" {2,}", "\t"); +System.IO.File.WriteAllText(outputPath, content); ``` -Tất cả các đoạn văn khác xuất hiện dưới dạng văn bản thuần, trong khi bất kỳ công thức Office Math nào được bao bọc trong môi trường LaTeX `equation` (hoặc `inline` nếu nó là nội tuyến trong Word). Điều này đáp ứng hoàn hảo yêu cầu **convert word equations latex**. +### Xử lý Bảng Lồng nhau ---- +Nếu DOCX của bạn chứa bảng trong bảng, `PreserveTableLayout` vẫn sẽ giữ được thứ tự trực quan, nhưng thụt lề có thể trông lạ. Một cách khắc phục nhanh là thay thế các khoảng trắng đầu dòng bằng một ký hiệu tùy chỉnh (ví dụ, `>>`) để các bộ phân tích tiếp theo có thể phát hiện mức độ lồng nhau. -## Các trường hợp đặc biệt & Câu hỏi thường gặp +### Xử lý Hàng loạt Nhiều Tệp -| Tình huống | Cách xử lý | -|-----------|------------| -| **Không có công thức trong nguồn** | Quá trình chuyển đổi vẫn hoạt động; bạn sẽ chỉ nhận được văn bản thuần. Không có mã LaTeX bổ sung nào được thêm. | -| **Tài liệu rất lớn (>100 MB)** | Xem xét stream đầu ra bằng `MemoryStream` để tránh sử dụng bộ nhớ cao. | -| **Các cấu trúc toán học không được hỗ trợ** | Aspose.Words bao phủ 99 % Office Math. Đối với những trường hợp hiếm, bạn có thể cần xử lý LaTeX thủ công. | -| **Cần tệp .tex thay vì .txt** | Thay đổi `outputPath` để kết thúc bằng `.tex` và tùy chọn đặt `txtOptions.Encoding` thành `Encoding.UTF8`. | -| **Chạy trên Linux/macOS** | Mã giống nhau hoạt động—chỉ cần đảm bảo đường dẫn tệp sử dụng dấu gạch chéo hoặc `Path.Combine`. | +Khi bạn cần **convert word to txt** cho hàng chục tài liệu, hãy bao bọc logic trong một vòng lặp: ---- +```csharp +foreach (var file in Directory.GetFiles(@"C:\Samples", "*.docx")) +{ + Document d = new Document(file); + string outFile = Path.ChangeExtension(file, ".txt"); + d.Save(outFile, options); +} +``` + +Bằng cách đó, bạn có thể **save docx as txt** hàng loạt mà không cần can thiệp thủ công. -## Cách lưu TXT với các công thức LaTeX – Tóm tắt nhanh +--- -1. **Load** tệp .docx (`Document`). -2. **Set** `OfficeMathExportMode = LaTeX` trong `TxtSaveOptions`. -3. **Save** tệp (`doc.Save`) với các tùy chọn đó. +## Những Sai lầm Thường gặp và Cách Tránh -Đó là toàn bộ quy trình để **how to save txt** các tệp chứa công thức được định dạng LaTeX. +1. **Missing LaTeX Export Mode** – Nếu bạn quên đặt `OfficeMathExportMode = OfficeMathExportMode.LaTeX`, các phương trình sẽ quay lại dạng văn bản thuần (ví dụ, “Equation 1”). Luôn kiểm tra lại khối tùy chọn. +2. **Table Layout Gets Lost** – Đặt `PreserveTableLayout` thành `false` là mặc định. Nếu đầu ra của bạn trông như một bức tường văn bản, có thể bạn chưa bật cờ này. +3. **File Paths with Spaces** – Sử dụng chuỗi thô (`@"C:\My Folder\input.docx"`) tránh các vấn đề escape. Nếu không, bạn sẽ gặp `FileNotFoundException`. +4. **Version Mismatch** – Các phiên bản cũ của Aspose.Words (< 21.9) không hỗ trợ `OfficeMathExportMode`. Nâng cấp lên gói mới nhất để đảm bảo **how to export latex** hoạt động. +5. **Encoding Errors for Non‑ASCII Characters** – Nếu bạn thấy ký tự �, hãy đặt rõ ràng `options.Encoding` thành UTF‑8 hoặc trang mã phù hợp. --- -## Bonus: Tự động hoá chuyển đổi cho nhiều tệp +## Mở rộng Giải pháp: Từ TXT sang Markdown hoặc HTML -Nếu bạn có một thư mục chứa nhiều tài liệu Word, hãy bọc logic trên trong một vòng lặp đơn giản: +Đôi khi bạn cần hơn một văn bản thuần—có thể là tệp Markdown vẫn chứa các khối LaTeX. `TxtSaveOptions` tương tự có thể thay bằng `HtmlSaveOptions` hoặc `MarkdownSaveOptions`: ```csharp -string sourceFolder = @"C:\MyProjects\WordSamples\Batch"; -string destFolder = @"C:\MyProjects\WordSamples\BatchOutput"; - -foreach (var file in Directory.GetFiles(sourceFolder, "*.docx")) +var mdOptions = new MarkdownSaveOptions { - Document batchDoc = new Document(file); - string fileName = Path.GetFileNameWithoutExtension(file); - string outPath = Path.Combine(destFolder, $"{fileName}.txt"); - - batchDoc.Save(outPath, txtOptions); - Console.WriteLine($"Converted {fileName}.docx → {fileName}.txt"); -} + ExportDocumentStructure = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +doc.Save("output.md", mdOptions); ``` -Bây giờ bạn có thể **convert word to latex** hàng loạt—hoàn hảo cho các nhóm nghiên cứu nhận hàng chục bản thảo mỗi ngày. +Thay đổi nhỏ đó cho phép bạn **convert word to txt**‑style output trong khi vẫn giữ cú pháp markdown mà bạn yêu thích. --- ## Kết luận -Chúng tôi đã trình bày **cách xuất LaTeX từ Word** từng bước, minh họa **cách lưu txt** các tệp giữ nguyên mọi công thức Office Math, và thậm chí cho bạn thấy cách **convert word equations latex** mà không mất độ chính xác. +Chúng tôi đã trình bày một câu trả lời hoàn chỉnh, sẵn sàng cho sản xuất cho **how to export latex** từ tài liệu Word, đồng thời chỉ cho bạn cách **convert word to txt**, **convert word to plain text**, **save docx as txt**, và **how to preserve tables**. Những điểm chính cần nhớ là: + +- Tải DOCX bằng `Aspose.Words.Document`. +- Đặt `TxtSaveOptions.OfficeMathExportMode = LaTeX` và `PreserveTableLayout = true`. +- Gọi `doc.Save(outputPath, options)` để nhận được tệp văn bản thuần giàu LaTeX sạch sẽ. -Chỉ với vài dòng C# và thư viện mạnh mẽ Aspose.Words, bạn có thể chuyển bất kỳ .docx nào thành văn bản sẵn sàng cho LaTeX, sẵn sàng đưa vào các bài báo khoa học, sách giáo trình, hoặc các pipeline xuất bản tự động. +Hãy thử trên các tệp của bạn, thử nghiệm các điều chỉnh mã hóa, và tự do xử lý hàng loạt các thư mục. Nếu gặp các trường hợp đặc biệt—bảng lồng nhau, ký tự lạ, hoặc phiên bản Aspose cũ—hãy quay lại phần “Mẹo” và “Những Sai lầm Thường gặp” để tìm giải pháp nhanh. -**Bước tiếp theo?** Hãy thử đưa tệp `.txt` đã tạo (hoặc đổi tên thành `.tex`) vào `pdflatex` hoặc `xelatex` để tạo PDF, hoặc khám phá tùy chọn `SaveFormat.LaTeX` để có tệp `.tex` trực tiếp. Nếu bạn cần **save docx as txt** trong khi giữ định dạng, hãy thử nghiệm với `PreserveTableLayout` và xử lý ngắt dòng tùy chỉnh. +Sẵn sàng cho bước tiếp theo? Hãy thử chuyển cùng một DOCX sang Markdown, hoặc đưa `.txt` đã tạo vào một trình tạo trang tĩnh có thể hiển thị LaTeX trên web. Các khả năng là vô hạn, và giờ bạn đã có nền tảng vững chắc cho bất kỳ quy trình **convert word to txt** nào. -Có câu hỏi về các trường hợp đặc biệt, giấy phép, hoặc tinh chỉnh hiệu năng? Để lại bình luận bên dưới—ch! +Chúc lập trình vui vẻ, và hy vọng LaTeX của bạn luôn biên dịch thành công ngay lần đầu! {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/vietnamese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md b/words/vietnamese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md new file mode 100644 index 0000000000..44dbd205aa --- /dev/null +++ b/words/vietnamese/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-01 +description: Lưu Word thành PDF bằng Aspose.Words trong C#. Học cách chuyển đổi docx + sang PDF, phát hiện phông chữ thiếu và xử lý cảnh báo thay thế phông chữ một cách + hiệu quả. +draft: false +keywords: +- save word as pdf +- convert docx to pdf +- how to convert word to pdf +- aspose words font substitution +- detect missing fonts +language: vi +og_description: Lưu Word thành PDF bằng Aspose.Words. Hướng dẫn chi tiết này chỉ cách + chuyển đổi docx sang PDF và phát hiện phông chữ thiếu. +og_title: Lưu Word thành PDF với Aspose.Words – Hướng dẫn đầy đủ +tags: +- Aspose.Words +- C# +- PDF conversion +title: Lưu Word thành PDF với Aspose.Words – Hướng dẫn toàn diện +url: /vi/net/basic-conversions/save-word-as-pdf-with-aspose-words-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lưu Word thành PDF với Aspose.Words – Hướng Dẫn Đầy Đủ + +Bạn đã bao giờ cần **lưu Word thành PDF** ngay lập tức và tự hỏi liệu có bỏ lỡ phông chữ nào không? Bạn không phải là người duy nhất—các nhà phát triển luôn phải đối mặt với các vấn đề phông chữ thiếu khi chuyển đổi tài liệu. Trong hướng dẫn này, chúng ta sẽ đi qua một giải pháp thực tế không chỉ **chuyển đổi docx sang pdf** mà còn **phát hiện phông chữ thiếu** bằng cách sử dụng cảnh báo thay thế phông chữ của Aspose.Words. + +Chúng ta sẽ bao phủ mọi thứ từ việc thiết lập bộ thu thập cảnh báo đến cách giải thích kết quả, vì vậy vào cuối bạn sẽ biết chính xác cách **lưu Word thành PDF** mà không gặp bất ngờ. Không cần công cụ bên ngoài, không cần cài đặt phức tạp—chỉ có mã C# sạch sẽ bạn có thể đưa vào bất kỳ dự án .NET nào. + +## Những Gì Bạn Cần Chuẩn Bị + +- **Aspose.Words for .NET** (phiên bản mới nhất, ví dụ 24.10) – bạn có thể tải qua NuGet (`Install-Package Aspose.Words`). +- Môi trường phát triển .NET (Visual Studio, Rider, hoặc VS Code đều ổn). +- Một tệp DOCX mẫu có thể chứa các phông chữ chưa được cài trên máy đích. +Đó là tất cả. Nếu bạn đã có những yếu tố cơ bản này, chúng ta sẵn sàng bắt đầu. + +## Lưu Word thành PDF – Tổng Quan Các Bước + +Dưới đây là chương trình đầy đủ, có thể chạy ngay. Bạn có thể sao chép‑dán vào một dự án console và nhấn **F5**. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using System; +using System.Collections.Generic; + +namespace WordToPdfDemo +{ + // Helper class that implements IWarningCallback to store warnings. + public class WarningInfoCollector : IWarningCallback + { + // A thread‑safe list that will hold every warning Aspose.Words raises. + public readonly List Warnings = new(); + + // This method is called automatically whenever Aspose.Words generates a warning. + public void Warning(WarningInfo info) => Warnings.Add(info); + } + + class Program + { + static void Main() + { + // 1️⃣ Load the source document – it could be any .docx you have. + Document doc = new Document("YOUR_DIRECTORY/input.docx"); + + // 2️⃣ Attach the warning collector so we can later inspect font‑substitution messages. + doc.WarningCallback = new WarningInfoCollector(); + + // 3️⃣ Perform the conversion that forces Aspose.Words to resolve fonts. + // Saving to PDF is the simplest way to trigger font loading. + doc.Save("YOUR_DIRECTORY/output.pdf"); + + // 4️⃣ Retrieve and display any font‑substitution warnings. + var collector = (WarningInfoCollector)doc.WarningCallback; + foreach (WarningInfo warning in collector.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + { + Console.WriteLine($"Font substitution detected: {warning.Description}"); + } + } + + Console.WriteLine("Conversion finished. Check output.pdf and console for warnings."); + } + } +} +``` + +> **Mẹo chuyên nghiệp:** Thay `YOUR_DIRECTORY` bằng đường dẫn tuyệt đối hoặc dùng `Path.Combine(Environment.CurrentDirectory, "input.docx")` cho cách tiếp cận tương đối, an toàn hơn. + +### Tại Sao Chúng Ta Dùng Callback Cảnh Báo + +Aspose.Words tự động thay thế các phông chữ thiếu bằng một phông dự phòng (thường là Arial). Nếu không có callback, bạn sẽ không bao giờ biết rằng việc thay thế đã xảy ra, điều này có thể gây ra lỗi bố cục trong PDF kết quả. Bằng cách gắn `IWarningCallback`, chúng ta nhận được danh sách rõ ràng, có thể lập trình được của mọi sự kiện phông chữ thiếu—hoàn hảo để ghi log hoặc thông báo cho người dùng cuối. + +### Phát Hiện Phông Chữ Thiếu – Những Điều Cần Kiểm Tra + +Khi bạn chạy chương trình, bất kỳ phông chữ nào thiếu sẽ xuất hiện một dòng console tương tự như: + +``` +Font substitution detected: Font 'Calibri' is not installed. Substituted with 'Arial'. +``` + +Nếu danh sách rỗng, chúc mừng—**lưu word thành pdf** đã thành công với tất cả phông chữ gốc vẫn còn nguyên vẹn. + +## Chuyển Đổi Docx sang PDF – Tùy Chỉnh Đầu Ra + +Đôi khi bạn cần một phiên bản PDF cụ thể, chất lượng hình ảnh, hoặc mức độ tuân thủ. Aspose.Words cho phép bạn điều chỉnh đối tượng `PdfSaveOptions` trước khi gọi `Save`. + +```csharp +PdfSaveOptions options = new PdfSaveOptions +{ + Compliance = PdfCompliance.PdfA1b, // For archival‑friendly PDFs + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 90 // Balance quality vs. size +}; + +doc.Save("YOUR_DIRECTORY/custom_output.pdf", options); +``` + +> **Tại sao điều này quan trọng:** Nếu bạn tạo PDF cho lưu trữ pháp lý, đặt `PdfA1b` sẽ đảm bảo tệp đáp ứng các tiêu chuẩn nghiêm ngặt. Việc chuyển đổi vẫn tuân theo callback cảnh báo của chúng ta, vì vậy bạn vẫn **phát hiện phông chữ thiếu**. + +## Thay Thế Phông Chữ Aspose Words – Xử Lý Các Trường Hợp Cạnh + +### Kịch Bản 1: Nhiều Phông Chữ Thiếu + +Nếu tài liệu nguồn sử dụng nhiều phông chữ tùy chỉnh, bộ thu thập cảnh báo sẽ chứa một mục cho mỗi phông. Bạn có thể tổng hợp chúng: + +```csharp +var missingFonts = new HashSet(); +foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + missingFonts.Add(w.Description); + +if (missingFonts.Count > 0) +{ + Console.WriteLine("The following fonts were substituted:"); + foreach (var f in missingFonts) Console.WriteLine($" • {f}"); +} +``` + +### Kịch Bản 2: Cung Cấp Thư Mục Phông Chữ Dự Phòng + +Aspose.Words có thể tìm kiếm thêm các thư mục chứa phông. Đặt thuộc tính `FontsFolder` trên `FontSettings` trước khi tải tài liệu: + +```csharp +FontSettings fontSettings = new FontSettings(); +fontSettings.SetFontsFolder("YOUR_DIRECTORY/custom_fonts", recursive: true); +doc.FontSettings = fontSettings; +``` + +Bây giờ thư viện sẽ thử thư mục tùy chỉnh của bạn trước, giảm khả năng thay thế không mong muốn. + +### Kịch Bản 3: Bỏ Qua Việc Thay Thế + +Nếu bạn muốn quá trình chuyển đổi thất bại khi gặp phông chữ thiếu (thay vì tự động thay thế), ném một ngoại lệ trong callback: + +```csharp +public void Warning(WarningInfo info) +{ + if (info.Type == WarningType.FontSubstitution) + throw new InvalidOperationException($"Missing font: {info.Description}"); +} +``` + +Điều này buộc bạn phải giải quyết phông chữ thiếu trước khi tiếp tục—rất hữu ích trong các pipeline CI nơi các lỗi im lặng là không chấp nhận được. + +## Ví Dụ Toàn Diện Từ Đầu Đến Cuối + +Kết hợp mọi thứ lại, đây là phiên bản ngắn gọn thể hiện **cách chuyển đổi Word sang PDF**, thiết lập tùy chọn PDF tùy chỉnh, và ghi lại bất kỳ vấn đề phông chữ nào: + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; +using Aspose.Words.Saving; +using System; +using System.Collections.Generic; +using System.IO; + +class FullDemo +{ + static void Main() + { + string inputPath = Path.Combine(Environment.CurrentDirectory, "sample.docx"); + string outputPath = Path.Combine(Environment.CurrentDirectory, "sample.pdf"); + + // Load document + Document doc = new Document(inputPath); + + // Attach warning collector + var collector = new WarningInfoCollector(); + doc.WarningCallback = collector; + + // Optional: add extra font folder + FontSettings fs = new FontSettings(); + fs.SetFontsFolder(@"C:\MyCustomFonts", true); + doc.FontSettings = fs; + + // Define PDF options + PdfSaveOptions pdfOpts = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfA1b, + ImageCompression = PdfImageCompression.Jpeg, + JpegQuality = 80 + }; + + // Save as PDF (triggers font loading) + doc.Save(outputPath, pdfOpts); + + // Report any missing fonts + foreach (var w in collector.Warnings) + if (w.Type == WarningType.FontSubstitution) + Console.WriteLine($"⚠️ Font substitution: {w.Description}"); + + Console.WriteLine($"✅ Done! PDF saved to {outputPath}"); + } +} +``` + +**Kết quả console dự kiến** (nếu Calibri thiếu): + +``` +⚠️ Font substitution: Font 'Calibri' is not installed. Substituted with 'Arial'. +✅ Done! PDF saved to C:\Path\To\sample.pdf +``` + +Nếu không có cảnh báo nào xuất hiện, thao tác **lưu word thành pdf** của bạn đã sử dụng đúng các phông chữ giống như trong DOCX nguồn. + +## Tóm Tắt Hình Ảnh + +![Sơ đồ quy trình lưu Word thành PDF](https://example.com/diagram.png "Sơ đồ quy trình lưu Word thành PDF") + +*Văn bản thay thế ảnh:* **lưu word thành pdf** quy trình hiển thị việc tải, thu thập cảnh báo, và xuất PDF. + +## Câu Hỏi Thường Gặp & Trả Lời + +| Câu hỏi | Trả lời | +|----------|--------| +| **Tôi có cần giấy phép cho Aspose.Words không?** | Giấy phép dùng thử miễn phí đủ cho việc thử nghiệm, nhưng khi triển khai thực tế cần mua giấy phép trả phí để loại bỏ watermark đánh giá. | +| **Điều này có hoạt động trên .NET Core / .NET 6+ không?** | Hoàn toàn có—Aspose.Words nhắm tới .NET Standard 2.0, vì vậy bất kỳ runtime .NET hiện đại nào cũng tương thích. | +| **Tôi có thể chuyển đổi nhiều tệp DOCX trong một vòng lặp không?** | Có, chỉ cần tạo một `Document` mới cho mỗi tệp và có thể tái sử dụng cùng một `WarningInfoCollector` nếu muốn tổng hợp kết quả. | +| **Nếu thư mục đầu ra không tồn tại thì sao?** | `Document.Save` sẽ ném `DirectoryNotFoundException`. Hãy tạo thư mục trước hoặc dùng `Directory.CreateDirectory`. | +| **Có cách nào nhúng các phông chữ thiếu vào PDF không?** | Aspose.Words có thể tự động nhúng phông nếu chúng có sẵn trên máy; đặt `PdfSaveOptions.EmbedFullFonts = true`. | + +## Kết Luận + +Bạn đã có một mẫu mẫu sẵn sàng cho môi trường sản xuất để **lưu Word thành PDF** đồng thời **phát hiện phông chữ thiếu** và xử lý các trường hợp **thay thế phông chữ Aspose.Words**. Bằng cách gắn callback cảnh báo, tùy chỉnh thư mục phông, và tùy chọn `PdfSaveOptions`, bạn có thể chuyển đổi **docx sang pdf** một cách đáng tin cậy và thông báo cho người dùng về bất kỳ vấn đề phông chữ nào có thể ảnh hưởng đến độ chính xác bố cục. + +Sẵn sàng cho bước tiếp theo? Hãy thử tạo PDF từ nhiều tài liệu đồng thời, hoặc khám phá cách thêm watermark và chữ ký số—cả hai đều là những mở rộng đơn giản của đoạn mã bạn vừa học. Chúc lập trình vui vẻ, và hy vọng các PDF của bạn luôn hiển thị đúng như mong muốn! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-loadoptions/_index.md b/words/vietnamese/net/programming-with-loadoptions/_index.md index f129aba6d7..ccc915edbd 100644 --- a/words/vietnamese/net/programming-with-loadoptions/_index.md +++ b/words/vietnamese/net/programming-with-loadoptions/_index.md @@ -41,6 +41,7 @@ Trong các hướng dẫn này, bạn sẽ học cách sử dụng LoadOptions | [Aspose Load Options – Tải DOCX với Cài Đặt Phông Chữ Tùy Chỉnh](./aspose-load-options-load-docx-with-custom-font-settings/) | | [Cách Sử Dụng LoadOptions trong Aspose.Words – Hướng Dẫn Toàn Diện](./how-to-use-loadoptions-in-aspose-words-complete-guide/) | Hướng dẫn chi tiết cách sử dụng LoadOptions trong Aspose.Words để tùy chỉnh việc tải tài liệu Word. | | [Khôi phục tài liệu bị hỏng trong C# – Đặt chế độ khôi phục và nhắc người dùng](./recover-corrupted-document-in-c-set-recovery-mode-prompt-use/) Hướng dẫn khôi phục tài liệu Word bị hỏng bằng Aspose.Words trong C#, thiết lập chế độ khôi phục và hiển thị lời nhắc cho người dùng. | +| [Khôi phục tệp docx bị hỏng – Hướng dẫn đầy đủ để tải các tệp Word bị hỏng trong C#](./recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/) | Hướng dẫn chi tiết cách mở và khôi phục các tệp Word (.docx) bị hỏng bằng Aspose.Words trong C#, bao gồm các bước thiết lập và xử lý lỗi. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md b/words/vietnamese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md new file mode 100644 index 0000000000..203a85e1b6 --- /dev/null +++ b/words/vietnamese/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-01 +description: Khôi phục nhanh các tệp docx bị hỏng bằng Aspose.Words. Tìm hiểu cách + thiết lập chế độ khôi phục, tải docx một cách an toàn và đọc các tệp Word bị hỏng + chỉ trong vài bước. +draft: false +keywords: +- recover corrupted docx +- set recovery mode +- recover damaged docx +- how to load docx +- read damaged word file +language: vi +og_description: Khôi phục các tệp docx bị hỏng trong C#. Đặt chế độ khôi phục, tải + docx một cách an toàn và đọc các tệp Word bị hỏng bằng Aspose.Words. +og_title: Khôi phục docx bị hỏng – Hướng dẫn nhanh C# +tags: +- Aspose.Words +- C# +- Document Recovery +title: Khôi phục file docx bị hỏng – Hướng dẫn đầy đủ về cách tải các tệp Word bị + hỏng trong C# +url: /vi/net/programming-with-loadoptions/recover-corrupted-docx-full-guide-to-loading-damaged-word-fi/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Khôi phục docx bị hỏng – Hướng dẫn nhanh C# + +Bạn đã bao giờ cố gắng mở một tệp Word mà không tải được và tự hỏi liệu nội dung có bị mất vĩnh viễn không? Trong nhiều dự án thực tế, bạn sẽ **recover corrupted docx** các tệp mà không cần yêu cầu người dùng gửi lại tệp đính kèm. Tin tốt là Aspose.Words làm cho việc này trở nên dễ dàng: bạn chỉ cần đặt chế độ khôi phục và để thư viện thực hiện phần còn lại. + +Trong hướng dẫn này, chúng ta sẽ đi qua các bước chính xác để **recover corrupted docx** các tệp, giải thích tại sao tùy chọn `RecoveryMode.AutoRecover` là lựa chọn an toàn nhất, và cho bạn thấy cách **how to load docx** các tệp có thể bị hỏng một phần. Khi kết thúc, bạn sẽ có thể đọc một tệp Word bị hỏng, trích xuất bất kỳ văn bản nào còn lại, và thậm chí ghi lại định dạng gốc để kiểm toán trong tương lai. Không cần công cụ bên ngoài, chỉ cần mã C# sạch sẽ. + +## Những gì bạn cần + +- **Aspose.Words for .NET** (bất kỳ phiên bản mới nào; API chúng tôi sử dụng hoạt động với 23.5 và mới hơn). +- Môi trường phát triển .NET (Visual Studio, VS Code, hoặc Rider). +- Tệp `.docx` bị hỏng hoặc bị hư hỏng một phần mà bạn muốn khôi phục. + +Không cần quyền đặc biệt, không có COM interop, và không cần cài đặt Microsoft Office trên máy chủ. Đơn giản, đúng không? + +## Bước 1: Đặt chế độ khôi phục thành Auto‑Recover + +Khi một tệp Word bị hỏng, hành vi tải mặc định sẽ ném ra ngoại lệ và dừng lại. Bằng cách cấu hình một đối tượng `LoadOptions`, bạn thông báo cho Aspose.Words **set recovery mode** thành `AutoRecover`, nó sẽ quét gói zip, bỏ qua các phần không đọc được, và trả về những gì nó có thể ghép lại. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; + +// Configure loading options – this is where we **set recovery mode**. +LoadOptions loadOptions = new LoadOptions +{ + // AutoRecover tries to salvage every readable piece. + RecoveryMode = RecoveryMode.AutoRecover +}; +``` + +> **Tại sao AutoRecover?** +> Nó cố gắng đọc càng nhiều càng tốt trong khi vẫn giữ đối tượng tài liệu có thể sử dụng được. Nếu bạn chọn `RecoveryMode.NoRecovery`, quá trình tải sẽ thất bại ngay khi gặp lỗi đầu tiên, điều này làm mất mục đích của các kịch bản **recover corrupted docx**. + +## Bước 2: Tải tài liệu với các tùy chọn đã cấu hình + +Bây giờ chế độ khôi phục đã được đặt, bạn có thể an toàn thử mở tệp. Thay thế `"YOUR_DIRECTORY/input.docx"` bằng đường dẫn thực tế tới tệp bị hỏng của bạn. + +```csharp +// Load the possibly damaged document. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +Nếu tệp chỉ bị hỏng một phần, thể hiện `Document` vẫn sẽ được tạo. Bạn có thể kiểm tra `document.IsStructureValid` sau này nếu cần xác thực bổ sung. + +## Bước 3: Xác minh định dạng được phát hiện + +Aspose.Words tự động phát hiện định dạng gốc (DOC, DOCX, ODT, v.v.). In giá trị này giúp bạn xác nhận rằng thư viện đã nhận dạng tệp đúng, đây là một kiểm tra nhanh sau một thao tác **recover corrupted docx**. + +```csharp +Console.WriteLine($"Loaded with {document.OriginalFormat} format."); +``` + +Kết quả thường gặp: + +``` +Loaded with Docx format. +``` + +Ngay cả khi một số phần bị thiếu, việc phát hiện định dạng vẫn thành công—một lợi thế nữa cho quy trình **recover corrupted docx**. + +## Bước 4: Trích xuất những gì bạn có thể + +Khi tài liệu đã được tải, bạn có thể xử lý nó như bất kỳ tệp Word khỏe mạnh nào. Dưới đây là một ví dụ ngắn gọn trích xuất văn bản thuần và ghi ra console. Điều này chứng minh rằng bạn có thể **read damaged word file** nội dung mà không gặp lỗi. + +```csharp +// Extract the plain text of the recovered document. +string plainText = document.GetText(); +Console.WriteLine("--- Extracted Text Start ---"); +Console.WriteLine(plainText); +Console.WriteLine("--- Extracted Text End ---"); +``` + +Nếu tệp gốc có bảng hoặc hình ảnh bị hỏng, chúng sẽ chỉ bị bỏ qua trong đầu ra văn bản. Phần còn lại của tài liệu vẫn nguyên vẹn. + +## Bước 5: Lưu bản sao sạch (Tùy chọn) + +Thường bạn sẽ muốn cung cấp cho người dùng một phiên bản mới, sạch sẽ của tệp sau khi khôi phục. Lưu với cùng định dạng đảm bảo tính tương thích với bất kỳ quy trình nào tiếp theo. + +```csharp +// Save a repaired copy next to the original. +string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; +document.Save(repairedPath, SaveFormat.Docx); +Console.WriteLine($"Repaired file saved to {repairedPath}"); +``` + +Bây giờ bạn có một tệp **recover damaged docx** mà có thể an toàn đính kèm vào email hoặc chuyển cho dịch vụ khác. + +## Ví dụ hoạt động đầy đủ + +Kết hợp tất cả lại, đây là chương trình hoàn chỉnh, sẵn sàng chạy. Dán nó vào một dự án console mới, điều chỉnh đường dẫn tệp, và nhấn F5. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Loading; + +class Program +{ + static void Main() + { + // 1️⃣ Configure loading options – **set recovery mode** to AutoRecover. + LoadOptions loadOptions = new LoadOptions + { + RecoveryMode = RecoveryMode.AutoRecover + }; + + // 2️⃣ Load the possibly corrupted document. + string inputPath = "YOUR_DIRECTORY/input.docx"; + Document document = new Document(inputPath, loadOptions); + + // 3️⃣ Show which format was detected. + Console.WriteLine($"Loaded with {document.OriginalFormat} format."); + + // 4️⃣ Extract and display any readable text. + string text = document.GetText(); + Console.WriteLine("--- Extracted Text Start ---"); + Console.WriteLine(text); + Console.WriteLine("--- Extracted Text End ---"); + + // 5️⃣ (Optional) Save a clean copy. + string repairedPath = "YOUR_DIRECTORY/input_repaired.docx"; + document.Save(repairedPath, SaveFormat.Docx); + Console.WriteLine($"Repaired file saved to {repairedPath}"); + } +} +``` + +**Kết quả mong đợi** (giả sử tệp chứa một đoạn duy nhất “Hello world!” và một số XML bị hỏng): + +``` +Loaded with Docx format. +--- Extracted Text Start --- +Hello world! + +--- Extracted Text End --- +Repaired file saved to YOUR_DIRECTORY/input_repaired.docx +``` + +Chú ý cách chương trình không bao giờ gặp lỗi—mặc dù tệp nguồn bị hỏng một phần. Đó là bản chất của **recover corrupted docx** bằng Aspose.Words. + +## Câu hỏi thường gặp & Trường hợp đặc biệt + +### Nếu tệp hoàn toàn không đọc được thì sao? + +Ngay cả `AutoRecover` cũng có giới hạn. Nếu container zip tự nó bị hỏng quá mức không thể sửa, Aspose.Words sẽ ném ra `CorruptedFileException`. Trong trường hợp đó bạn có thể cần một công cụ sửa zip của bên thứ ba trước khi thử **recover corrupted docx** lại. + +### Tôi có thể khôi phục các định dạng khác (ví dụ, `.doc`, `.odt`) không? + +Chắc chắn. `LoadOptions` giống nhau hoạt động cho bất kỳ định dạng nào mà Aspose.Words hỗ trợ. Chỉ cần thay đổi phần mở rộng tệp và thư viện sẽ tự động phát hiện định dạng gốc. Điều này có nghĩa là bạn cũng có thể **recover damaged docx**‑like các tệp như `.doc` hoặc `.rtf` với cùng một đoạn mã. + +### Làm sao để xử lý tài liệu lớn mà không tải toàn bộ vào bộ nhớ? + +Đối với các tệp có kích thước gigabyte, bạn có thể bật **load options** như `LoadOptions.LoadFormat` hoặc truyền tài liệu từng trang. Tuy nhiên, thuật toán khôi phục vẫn cần đọc toàn bộ gói, vì vậy hãy chuẩn bị tiêu thụ bộ nhớ cao hơn cho các tệp hỏng rất lớn. + +### Có cách nào để biết phần nào đã bị mất không? + +Sau khi tải, bạn có thể kiểm tra `document.GetChildNodes(NodeType.Any, true)` và so sánh số lượng với chuẩn mong đợi. Các bảng, hình ảnh hoặc tiêu đề bị thiếu sẽ đơn giản không có trong bộ sưu tập node. Điều này cho phép bạn ghi lại chính xác những gì đã **recover damaged docx** và thông báo cho người dùng. + +## Mẹo chuyên nghiệp để khôi phục đáng tin cậy + +- **Validate the input file size** trước khi tải; một tệp có kích thước 0 byte sẽ luôn thất bại. +- **Log the `RecoveryMode` result** bằng cách bắt `DocumentLoadingException` và lưu thông báo ngoại lệ; nó thường chứa manh mối về các phần đã bị bỏ qua. +- **Run the recovery on a background thread** nếu bạn đang xử lý tải lên trong một dịch vụ web—điều này giữ cho yêu cầu phản hồi nhanh. +- **Combine with a checksum** (ví dụ, MD5) để phát hiện nếu tệp đã khôi phục khác với bản gốc; bạn có thể quyết định có giữ cả hai phiên bản hay không. + +## Kết luận + +Chúng tôi vừa trình bày cách **recover corrupted docx** các tệp trong C# bằng cách **setting recovery mode** thành `AutoRecover`, tải tài liệu một cách an toàn, trích xuất bất kỳ văn bản nào còn lại, và tùy chọn lưu bản sao sạch. Cách tiếp cận này cho phép bạn **how to load docx** các tệp mà nếu không sẽ ném ngoại lệ, và cung cấp cho bạn một phương pháp đáng tin cậy để **read damaged word file** nội dung mà không cần công cụ bên ngoài. + +Bước tiếp theo? Hãy thử thay `RecoveryMode.AutoRecover` bằng `RecoveryMode.NoRecovery` để xem sự khác biệt, hoặc thử nghiệm các thuộc tính của `LoadOptions` điều khiển xử lý mật khẩu và thay thế phông chữ. Bạn cũng có thể tích hợp quy trình khôi phục vào một API ASP.NET Core nhận tải lên và trả về tệp đã sửa—hoàn hảo cho các quy trình quản lý tài liệu doanh nghiệp. + +Có thêm câu hỏi nào về việc khôi phục tài liệu Word, hoặc muốn xem cách **recover damaged docx** các tệp với các callback tùy chỉnh? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +![Illustration of a recovered document – recover corrupted docx](https://example.com/images/recover-corrupted-docx.png "recover corrupted docx") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md b/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md index 402ae5906c..91a1d08f72 100644 --- a/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md @@ -41,6 +41,7 @@ Words Processing with MarkdownSaveOptions là một nguồn tài nguyên chuyên | [Cách xuất LaTeX: Chuyển DOCX sang Markdown & TXT](./how-to-export-latex-convert-docx-to-markdown-txt/) | Hướng dẫn chi tiết cách xuất nội dung LaTeX từ DOCX sang Markdown và TXT bằng C# và Aspose.Words. | | [Cách đổi tên hình ảnh khi chuyển DOCX sang Markdown](./how-to-rename-images-when-converting-docx-to-markdown/) | Hướng dẫn chi tiết cách đổi tên các hình ảnh trong quá trình chuyển đổi tài liệu DOCX sang định dạng Markdown bằng Aspose.Words cho .NET. | | [Lưu docx thành markdown với Aspose.Words – Hướng dẫn đầy đủ C#](./save-docx-as-markdown-with-aspose-words-full-c-guide/) | Hướng dẫn chi tiết cách lưu file docx thành markdown bằng C# với Aspose.Words, bao gồm các tùy chọn và ví dụ thực tế. | +| [Lưu docx thành markdown – Export Word Math to LaTeX with Aspose.Words](./save-docx-as-markdown-export-word-math-to-latex-with-aspose/) | Hướng dẫn xuất công thức toán học từ tài liệu Word sang LaTeX khi lưu dưới dạng markdown bằng Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md b/words/vietnamese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md new file mode 100644 index 0000000000..156daa9ce4 --- /dev/null +++ b/words/vietnamese/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-01 +description: Lưu file docx thành markdown bằng Aspose.Words – học cách chuyển đổi + Word sang markdown, xuất phương trình sang LaTeX và thiết lập độ phân giải hình + ảnh markdown trong một quy trình liền mạch. +draft: false +keywords: +- save docx as markdown +- convert word to markdown +- export equations to latex +- convert word math latex +- set markdown image resolution +language: vi +og_description: Lưu file docx dưới dạng markdown với Aspose.Words. Hướng dẫn này chỉ + cách chuyển đổi Word sang markdown, xuất phương trình sang LaTeX và thiết lập độ + phân giải hình ảnh trong markdown. +og_title: Lưu docx dưới dạng markdown – Hướng dẫn đầy đủ để xuất công thức Word sang + LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Lưu docx dưới dạng markdown – Xuất công thức Word sang LaTeX với Aspose.Words +url: /vi/net/programming-with-markdownsaveoptions/save-docx-as-markdown-export-word-math-to-latex-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# lưu docx dưới dạng markdown – Xuất công thức Word sang LaTeX với Aspose.Words + +Bạn đã bao giờ cần **save docx as markdown** nhưng gặp khó khăn trong việc giữ các công thức Office Math sắc nét? Bạn không phải là người duy nhất. Hầu hết các nhà phát triển gặp phải vấn đề khi quá trình chuyển đổi mặc định chuyển các công thức thành hình ảnh mờ, buộc phải viết lại thủ công bằng LaTeX. + +Tin tốt: Aspose.Words có thể thực hiện công việc nặng cho bạn. Trong hướng dẫn này, chúng ta sẽ **convert word to markdown**, yêu cầu engine **export equations to latex**, và thậm chí **set markdown image resolution** cho phần còn lại của tài liệu. Khi kết thúc, bạn sẽ có một lệnh duy nhất tạo ra tệp `.md` sạch sẽ với công thức sẵn sàng cho LaTeX và hình ảnh độ phân giải cao. + +## What You’ll Learn + +- Cách tải một tệp `.docx` chứa các đối tượng Office Math. +- Thuộc tính nào của `MarkdownSaveOptions` kiểm soát **export equations to latex** và **set markdown image resolution**. +- Một đoạn mã C# đầy đủ, có thể chạy được mà bạn có thể dán vào bất kỳ dự án .NET nào. +- Mẹo khắc phục các vấn đề thường gặp, như thiếu phông chữ hoặc các tính năng phương trình không được hỗ trợ. + +**Prerequisites**: .NET 6+ (hoặc .NET Framework 4.6+), giấy phép Aspose.Words for .NET, và kiến thức cơ bản về C#. Nếu bạn đã quen với việc tạo một ứng dụng console, bạn đã sẵn sàng. + +--- + +## Step 1 – Save docx as markdown: Load Your Word File + +The first thing we need is a `Document` object that points at the source `.docx`. Think of it as opening the book before you start copying chapters. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Load the .docx that contains Office Math objects. +Document doc = new Document(@"C:\Docs\MathSample.docx"); + +// Quick sanity check – make sure the document actually has math. +if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) +{ + Console.WriteLine("Warning: No Office Math objects found in the source file."); +} +``` + +*Why this matters*: If the document doesn’t contain any math, the **export equations to latex** step will be a no‑op, but the rest of the conversion still runs. The check saves you from wondering why your output Markdown is missing LaTeX blocks. + +--- + +## Step 2 – Configure Export Equations to LaTeX + +Aspose.Words lets you decide how Office Math should be rendered. By default it turns them into PNG images, which is why many tutorials end up with a grainy markdown file. Switching the `OfficeMathExportMode` to `LaTeX` gives you clean, copy‑paste‑ready equations. + +```csharp +// Create Markdown save options. +MarkdownSaveOptions markdownOptions = new MarkdownSaveOptions +{ + // This is the key line: export Office Math as LaTeX. + OfficeMathExportMode = OfficeMathExportMode.LaTeX, + + // Optional: keep non‑math images at a decent DPI. + ImageResolution = 300 +}; +``` + +*Why `OfficeMathExportMode.LaTeX`?* LaTeX is the lingua franca of scientific publishing. When you later render the markdown with a static‑site generator or a Jupyter notebook, the equations will appear crisp at any zoom level. + +--- + +## Step 3 – Set Markdown Image Resolution (for Non‑Math Content) + +Even though we’re focusing on math, most Word documents also contain pictures, charts, or embedded SVGs. The `ImageResolution` property controls how Aspose.Words rasterizes those assets. A value of **300 DPI** is a sweet spot for screen and print. + +```csharp +// Already set in the options above, but you can tweak it per project. +markdownOptions.ImageResolution = 300; // 300 DPI yields high‑quality PNGs. +``` + +*Pro tip*: If your markdown will be displayed on the web only, you might drop this to 150 DPI to keep file size down. Conversely, for print‑ready PDFs, bump it up to 600 DPI. + +--- + +## Step 4 – Run the Conversion – Convert Word Math LaTeX + +Now that everything is configured, the actual conversion is a single line. Aspose.Words does the heavy lifting behind the scenes. + +```csharp +// Save the document as Markdown using the options we defined. +doc.Save(@"C:\Output\MathAsLatex.md", markdownOptions); + +Console.WriteLine("Conversion complete! Check C:\\Output\\MathAsLatex.md"); +``` + +**Expected output**: Open the generated `.md` file and you should see something like: + +```markdown +# Sample Document + +Here is an inline equation $E = mc^2$ that was originally an Office Math object. + +And a displayed equation: + +$$ +\int_{0}^{\infty} e^{-x^2} dx = \frac{\sqrt{\pi}}{2} +$$ + +![SampleImage](SampleImage.png) +``` + +Notice the LaTeX blocks (`$...$` and `$$...$$`) replacing the previous PNG snippets. The image at the bottom is still a PNG, rendered at 300 DPI as we requested. + +--- + +## Step 5 – Common Edge Cases & How to Handle Them + +| Situation | What Happens | How to Fix | +|-----------|--------------|------------| +| **Missing fonts** (e.g., Cambria Math not installed) | LaTeX output may contain unknown symbols. | Install the missing font on the server or embed it in the document before conversion. | +| **Complex equations** (matrix with custom delimiters) | Aspose.Words may fall back to an image despite `LaTeX` mode. | Upgrade to the latest Aspose.Words version; the library continuously improves equation coverage. | +| **Large documents** ( > 50 MB ) | Memory pressure can cause `OutOfMemoryException`. | Use `LoadOptions` with `LoadFormat.Docx` and stream the file, or split the document into sections before conversion. | +| **Image size too big** | Markdown file becomes huge, slowing down static‑site builds. | Reduce `ImageResolution` to 150 DPI for web‑only scenarios (see Step 3). | + +--- + +## Step 6 – Put It All Together: Full Working Example + +Below is the *complete* console‑app program you can copy‑paste into `Program.cs`. It includes all the bits we discussed, plus a little extra error handling. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +namespace WordToMarkdown +{ + class Program + { + static void Main(string[] args) + { + // 1️⃣ Load the source DOCX. + string inputPath = @"C:\Docs\MathSample.docx"; + Document doc; + try + { + doc = new Document(inputPath); + } + catch (Exception ex) + { + Console.WriteLine($"Failed to load document: {ex.Message}"); + return; + } + + // 2️⃣ Verify we have Office Math (optional but helpful). + if (doc.GetChildNodes(NodeType.OfficeMath, true).Count == 0) + Console.WriteLine("Note: No Office Math objects detected."); + + // 3️⃣ Configure Markdown save options. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = OfficeMathExportMode.LaTeX, // export equations to latex + ImageResolution = 300 // set markdown image resolution + }; + + // 4️⃣ Perform the conversion. + string outputPath = @"C:\Output\MathAsLatex.md"; + try + { + doc.Save(outputPath, mdOptions); + Console.WriteLine($"✅ Success! Markdown saved to: {outputPath}"); + } + catch (Exception ex) + { + Console.WriteLine($"Conversion error: {ex.Message}"); + } + } + } +} +``` + +Run the program (`dotnet run`) and you’ll get a markdown file that **save docx as markdown** while preserving every equation as LaTeX. No manual copy‑pasting, no ugly raster images for math. + +--- + +## Conclusion + +We’ve walked through the entire process of **saving docx as markdown** with Aspose.Words, from loading the Word file to configuring **export equations to latex** and **set markdown image resolution**. The final snippet is production‑ready, and you can drop it into any .NET project that needs to **convert word to markdown** on the fly. + +What’s next? Try feeding the generated `.md` into a static‑site generator like Hugo or Jekyll and watch your equations render beautifully. If you need to **convert word math latex** into other formats (PDF, HTML), just swap `MarkdownSaveOptions` for `PdfSaveOptions` or `HtmlSaveOptions`—the same `OfficeMathExportMode` flag works across them. + +Got a twist in your workflow, like pulling Word files from Azure Blob storage or streaming them from an API? The same pattern applies; just replace the file‑system `Document` constructor with a stream‑based one. + +Feel free to experiment, and let us know in the comments how this approach solved your conversion headaches. Happy coding! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-pdfsaveoptions/_index.md b/words/vietnamese/net/programming-with-pdfsaveoptions/_index.md index c8b0721e4d..508636ecf4 100644 --- a/words/vietnamese/net/programming-with-pdfsaveoptions/_index.md +++ b/words/vietnamese/net/programming-with-pdfsaveoptions/_index.md @@ -50,6 +50,7 @@ Cho dù bạn muốn chuyển đổi tài liệu Word sang PDF để phân phố | [Tạo PDF có thể truy cập trong C# – Hướng dẫn truy cập PDF](./create-accessible-pdf-in-c-pdf-accessibility-tutorial/) | Hướng dẫn tạo PDF đáp ứng tiêu chuẩn truy cập, bao gồm thẻ, cấu trúc và nội dung cho người dùng khuyết tật bằng Aspose.Words cho .NET. | | [Tạo PDF có khả năng truy cập từ Word – Hướng dẫn đầy đủ](./create-accessible-pdf-from-word-complete-guide/) | Hướng dẫn chi tiết cách tạo PDF có khả năng truy cập từ tài liệu Word bằng Aspose.Words cho .NET. | | [Tạo PDF có thể truy cập – Hướng dẫn từng bước để tuân thủ PDF/UA](./create-accessible-pdf-step-by-step-guide-for-pdf-ua-complian/) | Hướng dẫn chi tiết cách tạo PDF đáp ứng tiêu chuẩn PDF/UA để đảm bảo khả năng truy cập cho mọi người. | +| [Lưu tài liệu dưới dạng PDF với Aspose.Words – Hướng dẫn C# đầy đủ](./save-document-as-pdf-with-aspose-words-complete-c-guide/) | Hướng dẫn chi tiết cách lưu tài liệu Word thành PDF bằng Aspose.Words trong C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md b/words/vietnamese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..882449911e --- /dev/null +++ b/words/vietnamese/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,256 @@ +--- +category: general +date: 2026-05-01 +description: Học cách lưu tài liệu dưới dạng PDF bằng Aspose.Words trong C#. Bài hướng + dẫn cũng bao gồm chuyển đổi Word sang PDF, xuất LaTeX cho toán học và xử lý các + phông chữ thiếu. +draft: false +keywords: +- save document as pdf +- convert word to pdf +- export math latex +- handle missing fonts +language: vi +og_description: Lưu tài liệu dưới dạng PDF một cách dễ dàng với Aspose.Words. Hướng + dẫn này cũng chỉ cách chuyển đổi Word sang PDF, xuất LaTeX toán học và xử lý các + phông chữ thiếu. +og_title: Lưu tài liệu thành PDF với Aspose.Words – Hướng dẫn C# đầy đủ +tags: +- Aspose.Words +- C# +- PDF generation +title: Lưu tài liệu dưới dạng PDF với Aspose.Words – Hướng dẫn C# toàn diện +url: /vi/net/programming-with-pdfsaveoptions/save-document-as-pdf-with-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lưu Tài Liệu dưới dạng PDF với Aspose.Words – Hướng Dẫn C# Đầy Đủ + +Bạn đã bao giờ tự hỏi **cách lưu tài liệu dưới dạng pdf** trực tiếp từ tệp Word mà không mất các tính năng truy cập? Bạn không phải là người duy nhất—các nhà phát triển luôn hỏi về một cách đáng tin cậy để chuyển đổi Word sang PDF đồng thời bảo tồn các công thức toán học và xử lý các phông chữ thiếu một cách khéo léo. + +Trong tutorial này, chúng ta sẽ đi qua một giải pháp từng bước không chỉ **lưu tài liệu dưới dạng pdf** mà còn minh họa **chuyển đổi word sang pdf**, **xuất math latex**, và **xử lý phông chữ thiếu** bằng Aspose.Words for .NET mới nhất. 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 các tệp PDF/UA‑2 tuân thủ, hoàn hảo cho các cuộc kiểm tra khả năng truy cập. + +## Những Gì Bạn Cần Chuẩn Bị + +- .NET 6 trở lên (mã hoạt động với .NET Core và .NET Framework cũng được) +- Aspose.Words for .NET 25.10 hoặc mới hơn – bạn có thể tải bản dùng thử miễn phí từ trang web Aspose +- Một tệp Word đơn giản (`input.docx`) chứa ít nhất một hình dạng nổi và một công thức toán học (để thấy tính năng export‑math‑latex hoạt động) +- Visual Studio 2022 (hoặc bất kỳ IDE nào bạn thích) + +> **Mẹo chuyên nghiệp:** Nếu bạn đang chạy trên pipeline CI/CD, hãy thêm gói NuGet Aspose.Words vào tệp dự án của bạn: + +```xml + +``` + +Bây giờ, chúng ta cùng khám phá mã nguồn. + +## Bước 1: Tải Tài Liệu Nguồn với Khôi Phục Tự Động + +Khi làm việc với các tệp Word thực tế, bạn có thể gặp các phần bị hỏng hoặc tài nguyên thiếu. Bật chế độ khôi phục tự động đảm bảo quá trình tải không bao giờ ném ra ngoại lệ. + +```csharp +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// LoadOptions tells Aspose how to behave while reading the file. +LoadOptions loadOptions = new LoadOptions +{ + // If the document is partially damaged, Aspose will try to fix it. + RecoveryMode = RecoveryMode.AutoRecover +}; + +// Replace "YOUR_DIRECTORY" with the folder that holds your .docx. +Document document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); +``` + +**Tại sao điều này quan trọng:** +`RecoveryMode.AutoRecover` bảo vệ pipeline của bạn khỏi việc sập khi đầu vào bị sai định dạng, điều này đặc biệt hữu ích khi bạn **chuyển đổi word sang pdf** hàng loạt. + +## Bước 2: Cấu Hình Tùy Chọn Lưu PDF cho Khả Năng Truy Cập Đầy Đủ + +PDF/UA‑2 là tiêu chuẩn ISO cho các PDF có khả năng truy cập. Bằng cách cấu hình một vài cờ, chúng ta nhận được tệp mà các trình đọc màn hình có thể điều hướng, đồng thời đảm bảo các công thức toán học được xuất dưới dạng LaTeX ẩn. + +```csharp +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 compliance. + PdfCompliance = PdfCompliance.PdfUa2, + + // Floating shapes (like text boxes) become
tags – essential for accessibility. + ExportFloatingShapesAsInlineTag = true, + + // Export Office Math as hidden LaTeX (requires Aspose.Words 25.10+). + OfficeMathExportMode = OfficeMathExportMode.LaTeX +}; +``` + +**Các điểm chính:** + +- **ExportFloatingShapesAsInlineTag** – đảm bảo PDF kết quả giữ nguyên bố cục gốc đồng thời vẫn đúng ngữ nghĩa. +- **OfficeMathExportMode.LaTeX** – đáp ứng yêu cầu **export math latex**, cho phép các công cụ downstream trích xuất công thức nếu cần. + +## Bước 3: Thu Thập Cảnh Báo (ví dụ: Phông Chữ Thiếu) + +Phông chữ thiếu là một rắc rối phổ biến khi chuyển đổi tài liệu. Aspose.Words có thể báo cáo các vấn đề này qua một `WarningCallback`. Chúng ta sẽ thu thập chúng để bạn có thể ghi log hoặc xử lý sau này. + +```csharp +// Simple collector that stores all warnings in a list. +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) + { + Warnings.Add(info); + } +} + +// Attach the collector to the document. +document.WarningCallback = new WarningInfoCollector(); +``` + +**Lý do bạn cần quan tâm:** +Nếu nguồn sử dụng một phông chữ không được cài trên máy chủ, PDF sẽ chuyển sang phông mặc định, có thể làm hỏng bố cục. Bằng cách **xử lý phông chữ thiếu** chúng ta có thể cảnh báo người dùng hoặc nhúng phông thay thế. + +## Bước 4: Lưu Tài Liệu dưới dạng PDF Có Khả Năng Truy Cập + +Bây giờ là thời khắc quyết định—thực hiện chuyển đổi. + +```csharp +// Save the PDF to the output folder. +document.Save("YOUR_DIRECTORY/output.pdf", pdfSaveOptions); +``` + +Nếu mọi thứ diễn ra suôn sẻ, bạn sẽ có một tệp PDF/UA‑2 chứa LaTeX ẩn cho mỗi công thức và đánh thẻ đúng cho các hình dạng nổi. + +## Bước 5: Xem Lại Các Cảnh Báo Đã Thu Thập (Tùy Chọn nhưng Được Khuyến Khích) + +Sau khi lưu, bạn có thể duyệt qua các cảnh báo đã thu thập và ghi chúng lại. + +```csharp +var collector = (WarningInfoCollector)document.WarningCallback; + +foreach (var warning in collector.Warnings) +{ + Console.WriteLine($"{warning.Type}: {warning.Description}"); +} +``` + +Kết quả điển hình có thể trông như sau: + +``` +FontSubstitution: Font "Calibri" was not found. Substituted with "Arial". +``` + +Nhìn thấy những thông báo này sớm giúp bạn **xử lý phông chữ thiếu** trước khi chúng ảnh hưởng tới người dùng cuối. + +## Ví Dụ Hoàn Chỉnh + +Kết hợp tất cả lại, đây là chương trình hoàn chỉnh, sẵn sàng chạy. Thay thế các đường dẫn placeholder bằng của bạn. + +```csharp +using System; +using System.Collections.Generic; +using Aspose.Words; +using Aspose.Words.Loading; +using Aspose.Words.Saving; + +// ------------------------------------------------------------ +// Step 0: Helper class for warning collection (handles missing fonts) +// ------------------------------------------------------------ +public class WarningInfoCollector : IWarningCallback +{ + public List Warnings { get; } = new(); + + public void Warning(WarningInfo info) => Warnings.Add(info); +} + +// ------------------------------------------------------------ +// Main conversion routine +// ------------------------------------------------------------ +class Program +{ + static void Main() + { + // 1️⃣ Load the source .docx with auto‑recovery. + var loadOptions = new LoadOptions { RecoveryMode = RecoveryMode.AutoRecover }; + var document = new Document("YOUR_DIRECTORY/input.docx", loadOptions); + + // 2️⃣ Configure PDF/UA‑2 options (export math as LaTeX, handle floating shapes). + var pdfOptions = new PdfSaveOptions + { + PdfCompliance = PdfCompliance.PdfUa2, + ExportFloatingShapesAsInlineTag = true, + OfficeMathExportMode = OfficeMathExportMode.LaTeX + }; + + // 3️⃣ Attach warning collector to capture missing‑font alerts. + document.WarningCallback = new WarningInfoCollector(); + + // 4️⃣ Perform the conversion. + document.Save("YOUR_DIRECTORY/output.pdf", pdfOptions); + + // 5️⃣ (Optional) Print any warnings to the console. + var collector = (WarningInfoCollector)document.WarningCallback; + foreach (var w in collector.Warnings) + { + Console.WriteLine($"{w.Type}: {w.Description}"); + } + + Console.WriteLine("✅ Conversion complete! PDF saved as output.pdf"); + } +} +``` + +**Kết quả mong đợi:** +- `output.pdf` tuân thủ PDF/UA‑2. +- Tất cả các hình dạng nổi được đánh thẻ là hình ảnh nội tuyến. +- Mỗi đối tượng Office Math xuất hiện dưới dạng LaTeX ẩn (có thể thấy khi kiểm tra cấu trúc PDF). +- Bất kỳ vấn đề liên quan đến phông chữ nào đều được in ra console, cho bạn cơ hội **xử lý phông chữ thiếu** trước khi phát hành tệp. + +![Sơ đồ mô tả luồng từ Word → Aspose.Words → PDF có khả năng truy cập (lưu tài liệu dưới dạng pdf)](conversion-diagram.png "Sơ đồ luồng để lưu tài liệu dưới dạng pdf") + +*Văn bản thay thế ảnh:* **Sơ đồ cách lưu tài liệu dưới dạng pdf bằng Aspose.Words** + +## Câu Hỏi Thường Gặp & Các Trường Hợp Cạnh + +### Nếu tôi đang dùng phiên bản Aspose.Words cũ hơn thì sao? + +Cờ `OfficeMathExportMode.LaTeX` được giới thiệu từ 25.10. Đối với các phiên bản cũ hơn, bạn vẫn có thể **chuyển đổi word sang pdf**, nhưng công thức sẽ được raster hoá thay vì xuất dưới dạng LaTeX. Nên nâng cấp để đạt khả năng truy cập tốt nhất. + +### Tôi có thể nhúng phông chữ tùy chỉnh để tránh fallback không? + +Có. Đặt `PdfSaveOptions.FontEmbeddingMode = PdfFontEmbeddingMode.EmbedAll` trước khi gọi `Save`. Điều này cũng giúp **xử lý phông chữ thiếu** bằng cách buộc PDF chứa các glyph cần thiết. + +### Làm sao kiểm tra tính tuân thủ PDF/UA‑2? + +Mở tệp trong Adobe Acrobat Pro → “Print Production” → “Preflight”. Chọn hồ sơ “PDF/A‑2b” hoặc “PDF/UA‑2”; Acrobat sẽ báo cáo bất kỳ vi phạm nào. + +### Còn các tệp Word được bảo vệ bằng mật khẩu thì sao? + +Tải tài liệu bằng một `LoadOptions` bao gồm `Password`. Ví dụ: + +```csharp +var loadOptions = new LoadOptions { Password = "mySecret" }; +var doc = new Document("protected.docx", loadOptions); +``` + +Phần còn lại của pipeline không thay đổi. + +## Kết Luận + +Chúng ta đã bao quát mọi thứ cần thiết để **lưu tài liệu dưới dạng pdf** bằng Aspose.Words trong C#. Tutorial cũng đã minh họa cách **chuyển đổi word sang pdf**, **xuất math latex**, và **xử lý phông chữ thiếu**—tất cả đều tạo ra một tệp PDF/UA‑2 có khả năng truy cập. + +Hãy chạy thử mã, thử nghiệm với các `PdfSaveOptions` khác nhau (ví dụ: nén hình ảnh, PDF/A‑2b), và tích hợp vào dịch vụ xử lý tài liệu của bạn. Nếu muốn đi sâu hơn, hãy khám phá thư viện PDF‑specific của Aspose để xử lý hậu kỳ hoặc ký số kỹ thuật số. + +Bạn có thêm các kịch bản muốn giải quyết? Đừng ngần ngại để lại bình luận hoặc xem các hướng dẫn khác của chúng tôi về **PDF manipulation**, **image extraction**, và **batch conversion**. Chúc bạn lập trình vui vẻ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-shapes/_index.md b/words/vietnamese/net/programming-with-shapes/_index.md index 48570cb285..42af522e7c 100644 --- a/words/vietnamese/net/programming-with-shapes/_index.md +++ b/words/vietnamese/net/programming-with-shapes/_index.md @@ -37,6 +37,7 @@ Bằng cách sử dụng Aspose.Words cho .NET và làm theo các hướng dẫn | [Tạo hình chữ nhật trong Word bằng C# – Hướng dẫn từng bước](./create-rectangle-shape-in-word-using-c-step-by-step-guide/) | Tìm hiểu cách tạo hình chữ nhật trong tài liệu Word bằng Aspose.Words cho .NET với hướng dẫn chi tiết từng bước. | | [Hướng dẫn bóng đổ hình dạng Aspose.Words – Thêm bóng đổ cho hình dạng Word trong C#](./aspose-words-shape-shadow-tutorial-add-a-shadow-to-word-shap/) | Hướng dẫn cách thêm bóng đổ cho hình dạng trong tài liệu Word bằng Aspose.Words cho .NET và C#. | | [Tạo tài liệu Word trống với hình chữ nhật có bóng – Hướng dẫn từng bước](./create-blank-word-document-with-shadowed-rectangle-shape-ste/) | Tìm hiểu cách tạo tài liệu Word trống và chèn hình chữ nhật có bóng bằng Aspose.Words cho .NET qua hướng dẫn chi tiết từng bước. | +| [Cách di chuyển bóng đổ trong Aspose.Words – Hướng dẫn đầy đủ C#](./how-to-move-shadow-in-aspose-words-complete-c-guide/) | Tìm hiểu cách di chuyển bóng đổ cho hình dạng trong tài liệu Word bằng Aspose.Words cho .NET với hướng dẫn chi tiết từng bước. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md b/words/vietnamese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md new file mode 100644 index 0000000000..8bf61270a6 --- /dev/null +++ b/words/vietnamese/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-01 +description: Cách di chuyển bóng trên một hình dạng trong Aspose.Words bằng C#. Học + cách thêm bóng cho hình dạng, thay đổi độ mờ, đặt độ trong suốt và xoay bóng trong + vài phút. +draft: false +keywords: +- how to move shadow +- add shadow to shape +- how to change blur +- how to set transparency +- how to rotate shadow +language: vi +og_description: Cách di chuyển bóng đổ trên một hình dạng trong Aspose.Words bằng + C#. Hướng dẫn này cho bạn biết cách thêm bóng đổ vào hình dạng, thay đổi độ mờ, + đặt độ trong suốt và xoay bóng đổ. +og_title: Cách di chuyển bóng trong Aspose.Words – Hướng dẫn đầy đủ C# +tags: +- Aspose.Words +- C# +- Document Automation +title: Cách di chuyển bóng trong Aspose.Words – Hướng dẫn đầy đủ C# +url: /vi/net/programming-with-shapes/how-to-move-shadow-in-aspose-words-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Di chuyển Bóng trong Aspose.Words – Hướng dẫn C# đầy đủ + +Bạn đã bao giờ tự hỏi **cách di chuyển bóng** trên một hình dạng trong tài liệu Word mà không cần mở Word thủ công chưa? Trong công việc hàng ngày, tôi thường phải chỉnh sửa bóng của hình dạng một cách lập trình—cho dù đó là để tạo báo cáo chuyên nghiệp hay mẫu động. Tin tốt là gì? Với Aspose.Words bạn có thể thực hiện trong vài dòng code, và bạn cũng sẽ học **add shadow to shape**, **how to change blur**, **how to set transparency**, và **how to rotate shadow** trong cùng một lần. + +Trong tutorial này, chúng ta sẽ đi qua một kịch bản thực tế: tải một tệp DOCX hiện có đã có một hình dạng, điều chỉnh vị trí, độ mềm mại, độ mờ và hướng của bóng, và cuối cùng lưu kết quả. Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng để chèn vào bất kỳ dự án .NET nào, và bạn sẽ hiểu tại sao mỗi thuộc tính lại quan trọng. + +## Yêu cầu trước – Những gì bạn cần trước khi bắt đầu + +- **Aspose.Words for .NET** (phiên bản 23.12 trở lên). Bạn có thể tải nó từ NuGet bằng `Install-Package Aspose.Words`. +- Môi trường phát triển .NET 6+ (Visual Studio, VS Code, Rider—bất kỳ công cụ nào bạn thích). +- Tệp Word đầu vào (`input.docx`) đã chứa ít nhất một hình dạng (hình chữ nhật, vòng tròn, hoặc ảnh đều được). +- Kiến thức cơ bản về cú pháp C#—không cần phức tạp. + +Nếu bạn thiếu bất kỳ mục nào ở trên, hãy tạm dừng và cài đặt thư viện; phần còn lại của hướng dẫn giả định rằng gói đã được tham chiếu. + +## Bước 1: Tải tài liệu và lấy hình dạng mục tiêu – **How to Move Shadow** bắt đầu ở đây + +Điều đầu tiên chúng ta làm là tải tài liệu nguồn và tìm vị trí hình dạng cần chỉnh sửa. Aspose.Words xem mỗi đối tượng (đoạn văn, bảng, hình dạng) như một nút trong cây, vì vậy chúng ta có thể truy vấn trực tiếp. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // 📂 Load the source DOCX that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // 🎯 Retrieve the first shape in the document. + // The GetChild method walks the node tree; the third argument (true) means “search deep”. + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + // If no shape is found, bail out early. + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // ------------------------------------------------- + // The next sections show **how to move shadow**, + // **add shadow to shape**, **how to change blur**, + // **how to set transparency**, and **how to rotate shadow**. + // ------------------------------------------------- +``` + +> **Tại sao điều này quan trọng:** Tải tài liệu một lần và tái sử dụng cùng một đối tượng `Document` là hiệu quả. Lệnh gọi `GetChild` an toàn vì nó trả về `null` nếu chỉ số vượt quá phạm vi, cho phép chúng ta xử lý các hình dạng thiếu một cách nhẹ nhàng. + +## Bước 2: Điều chỉnh bán kính làm mờ – Nắm vững **How to Change Blur** + +Bóng mềm trông chuyên nghiệp, trong khi cạnh cứng có thể cảm giác rẻ tiền. Thuộc tính `BlurRadius` kiểm soát độ mềm trong điểm (1 pt ≈ 1/72 inch). Hãy tăng nó lên 8 pt. + +```csharp + // Increase the blur radius to soften the shadow edges. + shape.ShadowFormat.BlurRadius = 8.0; // 8 points ≈ 0.11 inches +``` + +> **Mẹo chuyên nghiệp:** Độ mờ mặc định là 0.5 pt. Bất kỳ giá trị nào trên 5 pt thường dễ nhận thấy, nhưng hãy cẩn thận khi tăng quá lớn—nó có thể làm cho hình dạng trông tách rời khỏi trang. + +## Bước 3: Đặt độ trong suốt – Câu trả lời cho **How to Set Transparency** + +Độ trong suốt quyết định mức độ trong suốt của bóng. Giá trị `0` nghĩa là hoàn toàn đục; `1` nghĩa là hoàn toàn trong suốt. Để tạo hiệu ứng nhẹ nhàng, chúng ta sẽ dùng `0.3` (30 % trong suốt). + +```csharp + // Make the shadow semi‑transparent so the shape remains visible through it. + shape.ShadowFormat.Transparency = 0.3; // 30% transparent +``` + +> **Tại sao bạn có thể quan tâm:** Nếu hình dạng màu tối, bóng hoàn toàn đục có thể làm lấn át văn bản phía dưới. Điều chỉnh độ trong suốt giúp tài liệu vẫn đọc được đồng thời tạo độ sâu. + +## Bước 4: Di chuyển bóng – Cốt lõi của **How to Move Shadow** + +Thuộc tính `Distance` xác định khoảng cách bóng lệch so với hình dạng, đo bằng điểm. Khoảng cách lớn hơn đẩy bóng ra xa hơn, tạo hiệu ứng kịch tính hơn. + +```csharp + // Move the shadow farther from the shape for a more pronounced effect. + shape.ShadowFormat.Distance = 4.0; // 4 points ≈ 0.055 inches +``` + +> **Nếu bạn cần độ lệch rất nhỏ?** Đặt `Distance` thành `0` sẽ khiến bóng nằm ngay sau hình dạng, hữu ích cho hiệu ứng khắc nổi. + +## Bước 5: Xoay nguồn sáng – Giải quyết **How to Rotate Shadow** + +Bóng không chỉ thẳng xuống; chúng tuân theo góc của nguồn sáng. Thuộc tính `Angle` (độ) xoay bóng quanh hình dạng. Hãy nghiêng nó 45°. + +```csharp + // Rotate the light source to change the shadow direction. + shape.ShadowFormat.Angle = 45; // 45 degrees clockwise from the vertical axis +``` + +> **Thí nghiệm nhanh:** Thử `90` để có bóng phía bên phải hoặc `-30` cho bóng nghiêng sang trái. Thay đổi trực quan ngay lập tức. + +## Bước 6: Lưu tài liệu – Nhìn kết quả của **Add Shadow to Shape** + +Bây giờ chúng ta đã chỉnh sửa bóng, chúng ta sẽ ghi tài liệu trở lại đĩa. Bạn có thể ghi đè lên tệp gốc hoặc tạo tệp mới; ví dụ sử dụng tệp đầu ra mới. + +```csharp + // Save the modified document with the adjusted shadow. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +> **Kết quả mong đợi:** Mở `output.docx`. Bóng của hình dạng sẽ mềm hơn, hơi lệch, bán trong suốt và nghiêng 45°. Nếu bạn so sánh cạnh nhau với `input.docx`, sự khác biệt là rõ ràng. + +### Ví dụ đầy đủ hoạt động (Sẵn sàng sao chép‑dán) + +Dưới đây là toàn bộ chương trình trong một khối. Dán vào một dự án console mới, thay thế `YOUR_DIRECTORY` bằng đường dẫn thư mục thực tế, và chạy. + +```csharp +using Aspose.Words; +using Aspose.Words.Drawing; + +class ShadowDemo +{ + static void Main() + { + // Load the source document that already contains a shape with a shadow. + Document doc = new Document(@"YOUR_DIRECTORY\input.docx"); + + // Retrieve the first shape in the document (the one we will modify). + Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); + + if (shape == null) + { + System.Console.WriteLine("No shape found in the document."); + return; + } + + // 1️⃣ Change blur – soften the edges. + shape.ShadowFormat.BlurRadius = 8.0; + + // 2️⃣ Set transparency – make it 30% see‑through. + shape.ShadowFormat.Transparency = 0.3; + + // 3️⃣ Move the shadow – increase distance from the shape. + shape.ShadowFormat.Distance = 4.0; + + // 4️⃣ Rotate the shadow – change light direction. + shape.ShadowFormat.Angle = 45; + + // Save the result. + doc.Save(@"YOUR_DIRECTORY\output.docx"); + System.Console.WriteLine("Shadow adjustments applied and saved to output.docx"); + } +} +``` + +## Các câu hỏi thường gặp & Trường hợp đặc biệt + +### Nếu tài liệu có nhiều hình dạng thì sao? + +Bạn có thể lặp qua tất cả các hình dạng: + +```csharp +foreach (Shape s in doc.GetChildNodes(NodeType.Shape, true)) +{ + // Apply the same shadow settings or customize per shape. +} +``` + +### Tôi có thể thêm bóng vào một hình dạng hiện chưa có bóng không? + +Chắc chắn. Đối tượng `ShadowFormat` luôn tồn tại; bạn chỉ cần bật nó: + +```csharp +shape.ShadowFormat.Enabled = true; +``` + +### Điều này có hoạt động với ảnh và SmartArt không? + +Có. Bất kỳ nút nào kế thừa từ `Shape`—bao gồm ảnh, biểu đồ và SmartArt—cũng có `ShadowFormat`. Các thuộc tính giống nhau áp dụng. + +### Làm sao để điều khiển màu bóng? + +Sử dụng thuộc tính `Color`: + +```csharp +shape.ShadowFormat.Color = System.Drawing.Color.Gray; +``` + +### Lo ngại về khả năng tương thích? + +Aspose.Words 23.12+ hỗ trợ .NET 6, .NET Core 3.1 và .NET Framework 4.6.2+. API được trình bày ổn định trên các phiên bản này. + +## Kết luận + +Chúng ta vừa mới khám phá **how to move shadow** trên một hình dạng bằng Aspose.Words, và trong quá trình đó chúng tôi cũng đã trình diễn **add shadow to shape**, **how to change blur**, **how to set transparency**, và **how to rotate shadow**. Ví dụ đầy đủ, có thể chạy ngay cho phép bạn chỉnh sửa bóng của bất kỳ hình dạng nào trong vài giây, mang lại cho tài liệu của bạn vẻ ngoài chuyên nghiệp, tinh tế mà không cần mở Word. + +Sẵn sàng cho bước tiếp theo? Hãy thử kết hợp các điều chỉnh bóng này với **conditional formatting**—ví dụ, chỉ áp dụng bóng sâu hơn cho tiêu đề hoặc cho biểu đồ vượt quá một kích thước nhất định. Hoặc khám phá **gradient fills** cho chính hình dạng để tạo thiết kế thực sự bắt mắt. + +Nếu gặp bất kỳ vấn đề nào, hãy để lại bình luận bên dưới. Chúc lập trình vui vẻ, và mong bóng của bạn luôn rơi đúng nơi bạn muốn! + +![Sơ đồ minh họa hiệu ứng di chuyển bóng trên một hình dạng – ví dụ cách di chuyển bóng](https://example.com/images/shadow-demo.png "ví dụ cách di chuyển bóng") + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file