diff --git a/words/arabic/java/document-conversion-and-export/_index.md b/words/arabic/java/document-conversion-and-export/_index.md index be066ac46d..8f36dd7126 100644 --- a/words/arabic/java/document-conversion-and-export/_index.md +++ b/words/arabic/java/document-conversion-and-export/_index.md @@ -98,18 +98,33 @@ weight: 22 ### [تحويل docx إلى markdown – تصدير المعادلات الرياضية إلى LaTeX باستخدام Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) تعلم كيفية تحويل ملفات DOCX إلى تنسيق Markdown وتصدير المعادلات الرياضية إلى LaTeX باستخدام Aspose.Words. +### [حفظ مستند Word كملف markdown – تصدير المعادلات إلى LaTeX باستخدام Java](./save-word-as-markdown-export-math-to-latex-with-java/) +تعلم كيفية حفظ مستند Word كملف markdown وتصدير المعادلات الرياضية إلى LaTeX باستخدام Aspose.Words for Java. + ### [حفظ المستند كملف TXT – دليل سريع لتصدير معادلات Word Math](./save-document-as-txt-quick-guide-to-exporting-word-math/) تعلم كيفية حفظ المستند كملف TXT وتصدير معادلات Word Math بسهولة باستخدام Aspose.Words for Java. +### [تصدير docx إلى txt باستخدام Java – دليل برمجة كامل](./export-docx-to-txt-with-java-complete-programming-guide/) +تعلم كيفية تحويل ملفات DOCX إلى TXT باستخدام Aspose.Words for Java خطوة بخطوة. + ### [Aspose Word إلى PDF – تحويل DOCX إلى PDF في Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) تعلم كيفية تحويل ملفات DOCX إلى PDF باستخدام Aspose.Words for Java بخطوات بسيطة. ### [كيفية تضمين الصور في Markdown عند تحويل DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) كيفية تضمين الصور في ملفات Markdown عند تحويل مستندات DOCX باستخدام Aspose.Words. +### [تضمين الصور كـ Base64 عند تحويل DOCX إلى Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +تعلم كيفية تضمين الصور في ملفات Markdown كبيانات Base64 أثناء تحويل مستندات DOCX باستخدام Aspose.Words. + ### [إنشاء ملف PDF ميسّر من DOCX – دليل شامل](./create-accessible-pdf-from-docx-complete-guide/) تعلم كيفية تحويل مستندات DOCX إلى ملفات PDF ميسّرة وفق معايير الوصول باستخدام Aspose.Words for Java. +### [حفظ المستند كملف PDF باستخدام Aspose.Words Java – دليل الوصول الكامل](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +تعلم كيفية حفظ المستندات كملفات PDF ميسّرة وفق معايير الوصول باستخدام Aspose.Words for Java. + +### [إنشاء PDF ميسّر في Java – دليل كامل للوسم](./create-accessible-pdf-in-java-full-tagging-guide/) +تعلم كيفية إنشاء ملفات PDF ميسّرة مع وسم كامل باستخدام Aspose.Words for Java لضمان توافق مع معايير الوصول. + ## الأسئلة المتكررة **س: كيف يمكنني إضافة علامة مائية إلى ملف PDF موجود باستخدام Aspose.Words؟** diff --git a/words/arabic/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/arabic/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..05f2f89934 --- /dev/null +++ b/words/arabic/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-05-26 +description: إنشاء PDF قابل للوصول في Java مع كود خطوة بخطوة. تعلّم كيفية وضع علامات + PDF لتسهيل الوصول وتمكين وضع العلامات باستخدام PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: ar +og_description: إنشاء ملف PDF قابل للوصول في Java مع كود خطوة بخطوة. تعلم كيفية وضع + علامات PDF لتسهيل الوصول وتمكين وضع العلامات باستخدام PdfSaveOptions. +og_title: إنشاء PDF قابل للوصول في Java – دليل كامل للوسم +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: إنشاء PDF ميسّر في جافا – دليل كامل للوسم +url: /ar/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء PDF يمكن الوصول إليه في Java – دليل كامل للوسم + +هل تساءلت يومًا كيف يمكنك **إنشاء PDF يمكن الوصول إليه** مباشرةً من كود Java؟ لست وحدك. يحتاج العديد من المطورين إلى خدمة المستخدمين الذين يعتمدون على قارئات الشاشة، والفارق بين PDF عادي وPDF يمكن الوصول إليه يمكن أن يكون هائلًا. في هذا الدرس سنستعرض **كيفية وسم PDF لتسهيل الوصول**, ونظهر لك **كيفية إنشاء PDF موسوم** باستخدام Aspose PDF for Java، ونكشف الخطوات الدقيقة **لإضافة وسوم الوصول إلى PDF** حتى يحصل كل قارئ على نفس المعلومات. + +سنغطي أيضًا **أفضل ممارسات تمكين وسم PDF**، والمشكلات الشائعة، ومثالًا كاملاً قابلًا للتنفيذ يمكنك إدراجه في مشروعك اليوم. لا مراجع غامضة—فقط كود ملموس، شروحات، وملف نهائي يمكنك فتحه في Adobe Acrobat للتحقق من الوسوم. + +## ما ستتعلمه + +- السبب وراء وسم PDF والامتثال لإمكانية الوصول. +- المتطلبات وإعداد المكتبة (Aspose PDF for Java 23.10 أو أحدث). +- **كيفية إنشاء PDF يمكن الوصول إليه** من الصفر، خطوة بخطوة. +- طرق **إضافة وسوم الوصول إلى PDF** بخلاف استدعاء `setTagDocumentStructure` الأساسي. +- نصائح لاختبار النتيجة وحل المشكلات الشائعة. + +بنهاية هذا الدليل ستكون قادرًا على توليد ملفات PDF تجتاز فحوصات WCAG 2.1 AA وتبدو احترافية في الوقت نفسه. + +--- + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +| المتطلبات | السبب | +|-------------|--------| +| **Java 8+** | ميزات لغة حديثة وتعامل أفضل مع Unicode. | +| **Aspose PDF for Java** (v23.10 أو أحدث) | يوفر الفئة `PdfSaveOptions` ودعم الوسم. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, إلخ) | لتسهيل التجميع وتصحيح الأخطاء. | +| **إذن كتابة** إلى مجلد سيتم حفظ PDF فيه | استدعاء `doc.save` يحتاج مسارًا قابلًا للكتابة. | + +إذا لم تقم بعد بإضافة Aspose PDF إلى مشروعك، ضع تبعية Maven التالية في ملف `pom.xml` الخاص بك: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **نصيحة احترافية:** استخدم أحدث إصدار؛ الإصدارات الأحدث تحسن دقة الوسم وتضيف ميزات إمكانية وصول مخصصة للغة. + +--- + +## الخطوة 1: إعداد هيكل المستند + +أولاً، نقوم بإنشاء كائن `Document` جديد. فكر فيه كقماش فارغ سيحمل لاحقًا الوسوم التي نحتاجها لإمكانية الوصول. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**لماذا هذا مهم:** بدون أي محتوى، لا شيء يمكن وسمه. إضافة حتى `TextFragment` بسيط يمنح محرك الوسم شيئًا للعمل معه، وهو ينشئ تلقائيًا وسم `

` (فقرة) عندما نقوم بتمكين وسم الهيكل لاحقًا. + +## الخطوة 2: إنشاء خيارات حفظ PDF (جوهر الوسم) + +الآن نجهز الخيارات التي تخبر Aspose PDF بدمج شجرة هيكل منطقية داخل الملف. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +الاستدعاء `setTagDocumentStructure(true)` هو مفتاح **تمكين وسم PDF**. عندما يكون true، تُنشئ المكتبة شجرة وسوم تعكس التخطيط البصري، مما يجعل PDF قابلًا للقراءة بواسطة تقنيات المساعدة. + +> **ملاحظة:** هذه أبسط طريقة لـ **كيفية إنشاء PDF موسوم**. للحصول على تحكم أكثر تفصيلًا (مثل تعيين اللغة أو وسوم مخصصة)، يمكنك استكشاف `pdfOptions.setTagLanguage("en-US")` و `pdfOptions.setTagStructureTreeRoot(...)`. + +## الخطوة 3: حفظ PDF القابل للوصول + +أخيرًا، نكتب المستند إلى القرص باستخدام الخيارات التي أعددناها للتو. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +عند انتهاء `doc.save`، ستجد الملف `accessible.pdf` في مجلد `output`. افتحه في Adobe Acrobat وانتقل إلى **File → Properties → Description → Tags** – يجب أن ترى شجرة وسوم مكتملة. + +## كيفية وسم PDF لتسهيل الوصول – ما بعد الأساسيات + +المقتطف المكوّن من ثلاث خطوات أعلاه يضيف بالفعل **وسوم الوصول إلى PDF**، لكن المستندات الواقعية غالبًا ما تحتاج إلى لمسة إضافية. إليك بعض التحسينات التي يمكنك إضافتها: + +### 1. تعيين لغة المستند + +تستخدم قارئات الشاشة سمة اللغة لنطق النص بشكل صحيح. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. توفير عنوان وموضوع + +البيانات الوصفية تساعد الأدوات المساعدة على إعطاء سياق قبل أن يفتح المستخدم الملف. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. وسم الصور بنص بديل + +إذا أدرجت صورًا، تحتاج إلى أوصاف `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. تعليم رؤوس الجداول + +الجداول تميل إلى إرباك القارئات ما لم تُعلم صفوف الرؤوس. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +هذه الخطوات الإضافية تجعل PDF الخاص بك ليس مجرد *موسوم* تقنيًا، بل **قابلًا للوصول** حقًا لجمهور متنوع. + +## المشكلات الشائعة عند تمكين وسم PDF + +| العَرَض | السبب المحتمل | الحل | +|---------|--------------|-----| +| الوسوم مفقودة في Acrobat | ترك `setTagDocumentStructure` على `false` | تأكد من استدعاء `pdfOptions.setTagDocumentStructure(true)`. | +| ترتيب القراءة خاطئ | تخطيط معقد بدون وسوم صريحة | استخدم `pdfOptions.setTagStructureTreeRoot(...)` لتحديد ترتيب مخصص. | +| تُقرأ الصور كـ “image” بدون وصف | عدم تعيين نص بديل | استدعِ `image.getAlternativeText().setValue("...")`. | +| اللغة غير معترف بها | إغفال `setTagLanguage` أو تعيين locale غير صحيح | قدم رمز لغة BCP‑47 (`en-US`, `fr-FR`). | + +الوعي بهذه القضايا سيوفر لك ساعات من التصحيح لاحقًا. + +## التحقق من النتيجة – ما المتوقع + +بعد تشغيل البرنامج، افتح `output/accessible.pdf` في Adobe Acrobat Reader: + +1. **لوحة الوسوم** (`View → Show/Hide → Navigation Panes → Tags`) يجب أن تعرض تسلسلًا هرميًا مثل `/Document → /Part → /Sect → /Para`. +2. **ترتيب القراءة** يجب أن يتبع التدفق البصري (النص أولًا، ثم الصور). +3. **قارئ الشاشة** (NVDA, VoiceOver) سيقرأ “Hello, accessible PDF!” بدلاً من مجرد “Page 1”. + +إذا كان أي من هذه العناصر مفقودًا، راجع الخطوات السابقة—خاصة استدعاء `setTagDocumentStructure`. + +## مثال كامل جاهز للتنفيذ (انسخه‑الصق) + + + +## دروس ذات صلة + +- [إنشاء PDF يمكن الوصول إليه من Word – التحويل إلى PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [إنشاء PDF يمكن الوصول إليه من DOCX – دليل كامل](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [كيفية حفظ المستند كـ PDF باستخدام Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/arabic/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..3118a8ae45 --- /dev/null +++ b/words/arabic/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-26 +description: قم بتضمين الصور بصيغة base64 أثناء تحويل ملف docx إلى markdown باستخدام + Aspose.Words for Java. تعلم كيفية تحويل Word إلى markdown، وحفظ Word كـ markdown، + ومعالجة الصور. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: ar +og_description: تضمين الصور بصيغة base64 أثناء تحويل ملف docx إلى markdown باستخدام + Aspose.Words للغة Java. دليل كامل لتحويل مستند Word إلى markdown وحفظه كملف markdown. +og_title: تضمين الصور كـ Base64 عند تحويل DOCX إلى Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: تضمين الصور بصيغة Base64 عند تحويل DOCX إلى Markdown +url: /ar/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تضمين الصور كـ Base64 عند تحويل DOCX إلى Markdown + +هل تساءلت يومًا كيف **تضمين الصور كـ base64** أثناء **تحويل docx إلى markdown**؟ لست وحدك—المطورون يسألون باستمرار كيف يمكن الحفاظ على الصور مدمجة دون الحاجة إلى ملفات منفصلة. الخبر السار هو أن Aspose.Words for Java يجعل الأمر سهلًا: يمكنك تحويل مستند Word إلى Markdown وتضمين كل صورة تلقائيًا كسلسلة Base64. + +في هذا الدرس سنستعرض العملية بالكامل—من تحميل ملف `.docx` يحتوي على صور، إلى تكوين رد نداء `MarkdownSaveOptions` الذي يقوم بالعمل الشاق، وأخيرًا حفظ النتيجة كملف `.md` نظيف. بنهاية الدرس ستعرف بالضبط كيف **تحويل word إلى markdown**، **تحويل الصور إلى base64**، و**حفظ word كـ markdown** دون ترك مجلدات صور متبقية. لا أدوات خارجية، لا معالجة يدوية بعد—فقط كود Java نقي يمكنك إدراجه في أي مشروع. + +## ما ستحتاجه + +- **Java 17** (أو أي JDK حديث) – يستخدم الكود صيغة lambda، لكن يمكنك تكييفه مع الإصدارات القديمة. +- مكتبة **Aspose.Words for Java** (أحدث إصدار حتى 2026). أضف تبعية Maven أو ملف JAR إلى مسار الفئة الخاص بك. +- ملف **DOCX** تجريبي يحتوي على صورة واحدة على الأقل. +- بيئة تطوير متكاملة أو محرر نصوص بسيط—Visual Studio Code، IntelliJ IDEA، أو حتى `vim` يكفي. + +إذا كان لديك هذه الأدوات بالفعل، رائع—لنبدأ مباشرة. + +## الخطوة 1: تحميل مستند Word + +أولاً ننشئ كائن `Document` يشير إلى ملف المصدر. هذه هي نفس الخطوة سواء كنت **تحويل docx إلى markdown** أو مجرد قراءة الملف لأغراض أخرى. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **لماذا هذا مهم:** كائن `Document` هو نقطة الدخول لكل عملية في Aspose. فهو يحتوي على بنية Word بالكامل—بما في ذلك الصور والجداول والأنماط—حتى يتمكن رد النداء اللاحق من فحص كل مورد. + +## الخطوة 2: إنشاء MarkdownSaveOptions وتسجيل رد نداء حفظ المورد + +السحر يكمن في `MarkdownSaveOptions`. من خلال إرفاق `IResourceSavingCallback` نحصل على التحكم في كيفية كتابة كل مورد خارجي (مثل الصورة). + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: لماذا نستخدم `setSaveToMemory(true)`؟ + +عندما تكون `saveToMemory` صحيحة، تقوم Aspose بكتابة بايتات الصورة إلى تدفق ذاكرة بدلاً من ملف. ثم يقوم مُصدّر Markdown بتحويل هذا التدفق إلى سلسلة Base64 وإدراجها مباشرةً في وسم صورة Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +هذا هو جوهر **تضمين الصور كـ base64**. + +## الخطوة 3: حفظ المستند كـ Markdown + +الآن بعد إعداد رد النداء، الخطوة الأخيرة هي ببساطة استدعاء `save`. هنا نقوم فعليًا **تحويل word إلى markdown** وبسبب رد النداء أيضًا **تحويل الصور إلى base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **النتيجة:** يحتوي `out.md` على نص Markdown مع تمثيل كل صورة كـ URI من نوع `data:`. لا يتم إنشاء ملفات صور إضافية على القرص، لذا يبقى المجلد مرتبًا. + +## الخطوة 4: التحقق من الناتج والمشكلات الشائعة + +افتح الملف `out.md` المُولد في أي عارض Markdown (VS Code، GitHub، أو مولد موقع ثابت). يجب أن ترى شيئًا مشابهًا لـ: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### قائمة التحقق من الأخطاء + +| المشكلة | السبب المحتمل | الحل | +|-------|--------------|-----| +| تظهر الصورة كرابط مكسور | تم حذف `setSaveToMemory` | تأكد من وجود `args.setSaveToMemory(true);` داخل رد النداء | +| سلسلة Base64 مقطوعة | عدم توافق ترميز ملف الإخراج | احفظ ملف Markdown باستخدام UTF‑8 (الإعداد الافتراضي لـ Aspose) | +| أسماء ملفات غير متوقعة | `setKeepResourceOriginalName(true)` | اجعلها `false` لفرض منطق التسمية المخصص | + +## الخطوة 5: تنويعات متقدمة (اختياري) + +### تحويل الصور المختارة فقط + +إذا كنت تريد فقط تضمين صور معينة (مثل تلك التي حجمها أكبر من 100 KB)، أضف فحصًا للحجم: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### استخدام تنسيق صورة مختلف + +`ResourceSavingArgs` يمنحك البايتات الخام، لذا يمكنك إعادة ترميز JPEGs إلى PNGs قبل التضمين—مفيد عندما يفضل مستهلك Markdown الهدف تنسيق PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +هذه التعديلات توضح مدى مرونة نهج **تضمين الصور كـ base64** عند **تحويل docx إلى markdown**. + +## الخلاصة + +لقد تعلمت الآن كيفية **تضمين الصور كـ base64** أثناء **تحويل docx إلى markdown** باستخدام Aspose.Words for Java. من خلال ربط `IResourceSavingCallback` بسيط، تقوم المكتبة بكل العمل الشاق: **تحويل word إلى markdown**، **تحويل الصور إلى base64**، وأخيرًا **حفظ word كـ markdown** باستدعاء `save` واحد. + +لا تتردد في التجربة—جرب قواعد تصفية صور مختلفة، أو التحويل إلى مخرجات HTML، أو ربط هذه الخطوة مع مولد موقع ثابت. النمط نفسه يعمل مع صيغ أخرى (HTML، EPUB) أيضًا، لذا يمكنك إعادة استخدام رد النداء أينما احتجت موارد مدمجة. + +**الخطوات التالية:** +- استكشف `HtmlSaveOptions` للحصول على صور HTML مدمجة بـ Base64. +- اجمع هذا مع خط أنابيب CI لأتمتة إنشاء الوثائق. +- تعمق في `DocumentVisitor` الخاص بـ Aspose إذا كنت تحتاج إلى تحكم أدق في عملية التحويل. + +برمجة سعيدة، واستمتع بملفات Markdown النظيفة والمتكاملة! + +## دروس ذات صلة + +- [كيفية تضمين الصور في Markdown عند تحويل DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [تحويل docx إلى markdown – تصدير المعادلات الرياضية إلى LaTeX باستخدام Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [حفظ الصور من Word – دليل Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/arabic/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..97803297f4 --- /dev/null +++ b/words/arabic/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: تصدير ملف docx إلى txt باستخدام Java و Aspose.Words. تعرّف على كيفية + تحويل docx إلى نص، والحفاظ على Unicode، وتصدير ملف Word كـ txt في بضع خطوات. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: ar +og_description: تصدير ملف docx إلى txt في Java. يوضح هذا الدليل كيفية تحويل docx إلى + نص، مع الحفاظ على النص العادي Unicode، وتصدير ملف Word كـ txt بكفاءة. +og_title: تصدير ملف docx إلى txt باستخدام Java – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: تصدير ملف docx إلى txt باستخدام Java – دليل برمجي شامل +url: /ar/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تصدير ملف docx إلى txt باستخدام Java – دليل برمجة شامل + +هل احتجت يوماً إلى **تصدير docx إلى txt** لكنك كنت قلقاً من فقدان الأحرف الخاصة؟ لست وحدك. عندما تقوم بتحويل مستندات Word إلى ملفات نصية عادية، قد تختفي رموز Unicode، الجداول، وحتى بعض التنسيقات البسيطة كالسحر. + +في هذا الدليل سنستعرض طريقة موثوقة لـ **تصدير docx إلى txt** باستخدام Aspose.Words for Java، مع الحفاظ على كل رموز Unicode وجعل تخطيطات الجداول قابلة للقراءة. في النهاية ستعرف أيضاً كيفية **تحويل docx إلى نص**، **تحويل Word إلى نص**، وحتى **تصدير Word كملف txt** دون أي مشاكل. + +## ما يغطيه هذا الدرس + +* إعداد Aspose.Words في مشروع Java +* تحميل ملف DOCX وتجهيزه لإخراج نص عادي +* تكوين دعم **النص العادي Unicode** عبر `TxtSaveOptions` +* حيل اختيارية للحفاظ على قابلية قراءة الجداول في ملف `.txt` الناتج +* حفظ الملف والتحقق من النتيجة + +لا توجد سكريبتات خارجية، ولا أدوات سطر أوامر غامضة—فقط كود Java نقي يمكنك وضعه في أي مشروع Maven أو Gradle. + +> **لماذا يهم؟** ملفات النص العادي خفيفة الوزن، صديقة لأنظمة التحكم بالإصدار، ومثالية لفهرسة البحث أو خطوط المعالجة اللاحقة. إذا جربت يوماً تشغيل `cat` على ملف Word وحصلت على رموز غير مفهومة، فإن هذا الدرس يحل تلك المشكلة. + +--- + +## تصدير docx إلى txt – نظرة عامة + +قبل الغوص في الكود، دعنا نوضح المصطلحات. **تصدير docx إلى txt** يعني أخذ حزمة Microsoft Word `.docx` وكتابة محتواها النصي إلى ملف `.txt` بسيط. على عكس تحويل PDF، يزيل تصدير النص التنسيق لكنه يمكن أن يحتفظ بفواصل الأسطر، علامات الفقرات،—وإذا قمت بتكوينه بشكل صحيح—الأحرف Unicode مثل الإيموجي، الحروف ذات اللكنات، أو النصوص الآسيوية. + +Aspose.Words يجعل ذلك سهلًا لأنه ي抽象 تنسيق ملف Word ويوفر فئة `TxtSaveOptions` حيث يمكنك تحديد الترميز، معالجة الجداول، وأكثر. + +### المتطلبات المسبقة + +* Java 11 أو أحدث (تعمل الواجهة البرمجية مع Java 8+، لكننا نفترض JDK حديث) +* Aspose.Words for Java JAR (متاح عبر Maven Central) +* ملف عينة `unicode.docx` يحتوي على أحرف Unicode متنوعة—مثل “こんにちは”، “😊”، وجدول بسيط + +إذا كان لديك كل ذلك، لنبدأ. + +--- + +## الخطوة 1: تحميل ملف DOCX (تحويل docx إلى نص) + +أول شيء تحتاج إلى فعله هو قراءة المستند المصدر إلى الذاكرة. هنا يبدأ عملية **تحويل docx إلى نص** رسميًا. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*لماذا هذا مهم:* `Document` هو تمثيل Aspose.Words لملف Word. بتحميله، تحصل على وصول إلى جميع الفقرات، الجداول، وحتى العناصر المخفية. إذا لم يُعثر على الملف، ستلقي Aspose استثناء `FileNotFoundException` واضح، لتعرف فورًا ما الخطأ. + +--- + +## الخطوة 2: تكوين TxtSaveOptions لـ Unicode (نص عادي Unicode) + +ملفات النص العادي هي مجرد تدفقات من البايتات، لذا يجب إبلاغ Java بمجموعة الأحرف التي ستستخدمها. UTF‑8 هو المعيار الفعلي لـ **النص العادي Unicode** لأنه يستطيع ترميز كل نقطة شفرة Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **نصيحة محترف:** إذا تخطيت استدعاء `setEncoding`، فإن Aspose يستخدم الترميز الافتراضي للمنصة، والذي على العديد من أجهزة Windows يكون Windows‑1252. هذا الترميز سيحذف بصمت أحرفًا مثل “ß” أو “—”. + +--- + +## الخطوة 3: الحفاظ على تخطيط الجدول (اختياري، لكنه مفيد للقراءة) + +عند **تصدير Word كملف txt**، عادةً ما تُسطح الجداول إلى سطر نصي واحد، مما يجعلها غير قابلة للقراءة. Aspose.Words يقدم علمًا بسيطًا للحفاظ على البنية البصرية. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*متى تستخدمه:* إذا كان ملف DOCX المصدر يحتوي على فواتير، جداول مواعيد، أو أي بيانات على شكل شبكة، فإن تمكين `PreserveTableLayout` سيضيف علامات تبويب وفواصل أسطر بحيث لا يزال الملف الناتج يشبه جدولًا. إذا لم تحتاج ذلك، يمكنك حذف السطر والحصول على إخراج أكثر اختصارًا. + +--- + +## الخطوة 4: حفظ المستند كنص عادي (تصدير Word كملف txt) + +الآن تم إنجاز الجزء الأصعب—فقط اكتب البايتات إلى القرص. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +تشغيل البرنامج ينتج ملف `plain.txt` في نفس المجلد. افتحه بأي محرر نصوص (Notepad++، VS Code، أو حتى `cat` في الطرفية) وسترى: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +لاحظ كيف بقي التحية اليابانية والرمز المبتسم، وكيف حافظ الجدول على أعمدته بفضل `PreserveTableLayout`. هذه هي جوهر **تصدير docx إلى txt** النظيف. + +--- + +## الخطوة 5: التحقق من النتيجة (فحص صحة تحويل Word إلى نص) + +فحص سريع يمنع فقدان البيانات الصامت. إليك بعض الطرق لتأكيد أنك **تحول Word إلى نص** بشكل صحيح: + +1. **مقارنة التجزئة** – احسب تجزئة SHA‑256 لملف `.txt` قبل وبعد تحويل ذهابًا وإيابًا (txt → docx → txt) لضمان الاستقرار. +2. **البحث عن علامات Unicode** – استخدم `grep` أو خاصية البحث في IDE للعثور على أحرف مثل “😊”. +3. **الفتح في محررات متعددة** – بعض إصدارات Notepad القديمة لا تفسر UTF‑8 بدون BOM؛ فتح الملف في VS Code يؤكد الترميز الصحيح. + +إذا فشل أي من هذه الفحوصات، تحقق من وجود `saveOptions.setEncoding(StandardCharsets.UTF_8)` وأن ملف DOCX المصدر يحتوي فعلاً على نص Unicode. + +--- + +## مشاكل شائعة وكيفية تجنبها + +| المشكلة | السبب | الحل | +|--------|-------|------| +| **فقدان الأحرف** | الترميز الافتراضي للنظام (مثل Windows‑1252) يحذف الرموز غير ASCII. | عيّن UTF‑8 صراحةً عبر `saveOptions.setEncoding`. | +| **تحول الجداول إلى سطر واحد** | `PreserveTableLayout` يبقى على القيمة الافتراضية `false`. | استدعِ `saveOptions.setPreserveTableLayout(true)`. | +| **الملف غير موجود** | مسار خاطئ أو أذونات قراءة غير كافية. | استخدم مسارات مطلقة أو `Paths.get(...)` مع معالجة الاستثناءات المناسبة. | +| **تباطؤ الأداء مع المستندات الضخمة** | تحميل المستند بالكامل في الذاكرة. | قم بتدفق المستند على أجزاء باستخدام `DocumentBuilder` إذا كنت تحتاج أقسامًا محددة فقط. | + +--- + +## إضافي: تصدير ملفات DOCX متعددة دفعة واحدة + +إذا كنت بحاجة إلى **تحويل docx إلى نص** لمجلد كامل، غلف المنطق داخل حلقة: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +هذا المقتطف **يصدر docx إلى txt** لكل ملف في الدليل، مما يوفر لك ساعات من العمل اليدوي. + +--- + +## الخلاصة + +لقد تعلمت الآن كيفية **تصدير docx إلى txt** باستخدام Java، مع ضمان بقاء كل حرف Unicode سليماً، والجداول قابلة للقراءة، والعملية قابلة للتكرار. من خلال تكوين `TxtSaveOptions` للترميز UTF‑8 واختيارياً الحفاظ على تخطيط الجداول، يمكنك بثقة **تحويل docx إلى نص**، **تحويل Word إلى نص**، و**تصدير Word كملف txt** لأي سير عمل لاحق. + +مستعد للتحدي التالي؟ جرّب التصدير إلى صيغ نصية أخرى مثل markdown (`.md`) أو CSV، أو استكشف قدرات Aspose.Words في تحويل PDF. المبادئ نفسها—الترميز الصريح، الحفاظ على التخطيط، والتحقق الدقيق—تنطبق على جميع الحالات. + +برمجة سعيدة، ولتظل ملفاتك النصية دائمًا غنية بـ Unicode! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="مخطط تدفق تصدير docx إلى txt"} + +## دروس ذات صلة + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/arabic/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..10c26480df --- /dev/null +++ b/words/arabic/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: احفظ المستند كملف PDF باستخدام Aspose.Words Java وأضف إمكانية الوصول + إلى PDF. تعلم تحويل ملف docx إلى PDF، وضع علامات على الخطوط الأفقية، وضمان الامتثال + لمعيار PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: ar +og_description: احفظ المستند كملف PDF باستخدام Aspose.Words Java مع إضافة إمكانية + الوصول إلى PDF. دليل خطوة بخطوة لتحويل ملف docx إلى PDF ووضع علامات على الخطوط الأفقية + للامتثال لمعيار PDF/UA‑2. +og_title: حفظ المستند بصيغة PDF باستخدام Aspose.Words Java – تسهيل إمكانية الوصول +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: حفظ المستند كملف PDF باستخدام Aspose.Words Java – دليل شامل للوصولية +url: /ar/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ المستند كملف PDF باستخدام Aspose.Words Java – دليل كامل لإمكانية الوصول + +هل تساءلت يومًا كيف **تحفظ المستند كملف PDF** مع الحفاظ على إمكانية الوصول لقارئات الشاشة؟ لست وحدك. يحتاج العديد من المطورين إلى *تحويل docx إلى pdf* مع الالتزام بمعايير PDF/UA‑2، خاصةً عندما يحتوي المصدر على خطوط أفقية يجب وضع العلامات عليها بشكل صحيح. في هذا الدرس سنستعرض الخطوات الدقيقة **لحفظ المستند كملف PDF** باستخدام Aspose.Words for Java، وإضافة إمكانية الوصول إلى PDF تلقائيًا، وضمان أن كل خط أفقي يتم **وضع علامة** عليه كعنصر غير محتوى (artifact). + +سنبدأ بمشروع Java نظيف، نحمل ملف DOCX يحتوي بالفعل على خطوط أفقية، نضبط خيارات حفظ PDF لتتوافق مع PDF/UA‑2، وأخيرًا نكتب ملف PDF كامل إمكانية الوصول. بنهاية الدرس، ستتمكن من **حفظ المستند كملف pdf** بثقة أنه يجتاز فحوصات إمكانية الوصول. + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من وجود ما يلي: + +- Java 8 أو أحدث مثبت (تم اختبار الدرس على JDK 17). +- Maven 3.6+ (أو Gradle إذا كنت تفضله) لإدارة الاعتمادات. +- رخصة صالحة لـ Aspose.Words for Java (الإصدار التجريبي المجاني يعمل، لكن الرخصة تزيل علامات التقييم). +- ملف DOCX (`input.docx`) يحتوي على حد أفقي واحد على الأقل—فكر في خط فاصل بسيط تضيفه في Word. + +> **نصيحة احترافية:** إذا لم يكن لديك ملف DOCX جاهز، أنشئ مستند Word جديد، اكتب بضع فقرات، أدخل *Insert → Horizontal Line*، احفظه باسم `input.docx`، وضعه في المجلد الذي تختاره. + +## الخطوة 1: إعداد مشروع Maven + +أولاً، أنشئ مشروع Maven جديد (أو أضفه إلى مشروع موجود). يحتاج ملف `pom.xml` إلى اعتماد Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **لماذا هذا مهم:** إضافة العنصر `aspose-words` هو الخطوة الأولى لـ *تحويل docx إلى pdf*. بدونها، لن يتعرف المترجم على `Document`، `PdfSaveOptions`، وغيرها من الفئات الحيوية. + +## الخطوة 2: تحميل ملف DOCX المصدر الذي يحتوي على خطوط أفقية + +الآن سنكتب فئة Java صغيرة تقوم بتحميل ملف DOCX. هنا يبدأ جزء **وضع علامة على الخطوط الأفقية**—فإن Aspose.Words يتعامل تلقائيًا مع الخط الأفقي كفقرة ذات حد، لكننا سنترك محرك PDF/UA يتولى وضع العلامات. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +لاحظ أننا لم نقم بحفظ أي شيء بعد—نحن فقط **نحمّل** ملف DOCX، وهو النصف الأول من *تحويل docx إلى pdf*. الآن يحمل كائن `Document` كل محتوى Word، بما في ذلك أي خطوط أفقية قمت بإدراجها. + +## الخطوة 3: ضبط خيارات حفظ PDF لتتوافق مع PDF/UA‑2 + +السحر في **إضافة إمكانية الوصول إلى PDF** يكمن في `PdfSaveOptions`. عبر ضبط مستوى الامتثال إلى `PDF_UA_2`، سيقوم Aspose.Words بـ: + +1. وضع علامات على العناصر الهيكلية (العناوين، الجداول، إلخ). +2. تعليم العناصر الزخرفية—مثل الخطوط الأفقية—كـ *artifact*، بحيث تتجاهلها قارئات الشاشة. +3. إدراج بيانات التعريف اللازمة لـ PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **لماذا نضبط الامتثال؟** بدون `PDF_UA_2` قد يكون PDF قابلًا للقراءة لكنه لن يجتاز أدوات التحقق الآلية من إمكانية الوصول. يتم تلبية متطلب **وضع علامة على الخطوط الأفقية** تلقائيًا لأن PDF/UA يعاملها كـ *artifact* عندما يكون علم الامتثال مفعلاً. + +## الخطوة 4: حفظ المستند كملف PDF + +الآن نصل أخيرًا إلى **حفظ المستند كملف pdf**. هذا السطر الواحد يقوم بالعمل الثقيل—تحويل DOCX، تطبيق علامات إمكانية الوصول، وكتابة الملف على القرص. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +شغّل الفئة (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) وسترى رسالة تأكيد. افتح الملف الناتج `ua_compliant.pdf` في Adobe Acrobat وتحقق من **File → Properties → Description → PDF/A, PDF/UA**—يجب أن ترى “PDF/UA‑2” مدرجًا. + +### النتيجة المتوقعة + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +افتح ملف PDF وستلاحظ: + +- نص المستند قابل للتحديد والبحث. +- الخط الأفقي غير مرئي لقارئات الشاشة (مُعامل كـ artifact). +- PDF يجتاز أدوات التحقق الأساسية من PDF/UA (مثل PAC 3). + +## الخطوة 5: التحقق من إمكانية الوصول – قائمة مراجعة سريعة + +على الرغم من أن Aspose.Words يقوم بمعظم العمل، من الجيد التحقق من النتيجة. + +| الفحص | طريقة التحقق | +|-------|----------------| +| **عنوان المستند** | افتح Acrobat → File → Properties → حقل Title (يجب أن يطابق `pdfOptions.setTitle`). | +| **وضع علامة Artifact** | استخدم أداة “Reading Order” في Acrobat. يجب أن تظهر الخطوط الأفقية كـ *Artifact* (رمادي). | +| **ترتيب القراءة المنطقي** | شغّل “Accessibility Checker” في Acrobat؛ تأكد من عدم وجود أخطاء هيكلية. | +| **PDF مع علامات** | في Acrobat، انظر إلى لوحة “Tags” – يجب أن ترى تسلسل هرمي (Document → Section → Paragraph، إلخ). | +| **امتثال PDF/UA** | سيظهر Acrobat “PDF/UA‑2” تحت تبويب “Standards”. | + +إذا فشل أي من هذه الفحوصات، تحقق مرة أخرى من أنك تستخدم أحدث نسخة من Aspose.Words وأن `setCompliance(PdfCompliance.PDF_UA_2)` تم تطبيقه بشكل صحيح. + +## المشكلات الشائعة وكيفية تجنبها + +1. **غياب الرخصة** – النسخة التجريبية تضيف علامة مائية قد تُفسد تحقق PDF/UA. طبّق رخصتك مبكرًا في `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **مسار الإدخال غير صحيح** – سيؤدي `FileNotFoundException` إلى إيقاف التحويل. استخدم مسارات مطلقة أو ضع ملف DOCX في جذر المشروع واشره بـ `new File("input.docx").getAbsolutePath()`. +3. **استخدام نسخة قديمة من Aspose** – تم إضافة دعم PDF/UA في الإصدار 22.9. قم بالترقية إلى أحدث إصدار لتجنب فقدان الميزات. +4. **الخط الأفقي كصورة** – إذا أدخلت الخط كصورة بدلاً من خط Word أصلي، سيعامل Aspose الصورة كصورة عادية، غير كـ artifact. استبدل الصورة بـ *Horizontal Line* المدمج في Word للحصول على العلامة الصحيحة. + +## توسيع الحل – ماذا لو احتجت إلى المزيد؟ + +- **علامات مخصصة**: إذا كان لديك عناصر زخرفية أخرى (مثل أيقونات زخرفية)، يمكنك وضع علامة عليها يدويًا كـ artifacts باستخدام `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **مستندات متعددة**: كرّر العملية على مجلد من ملفات DOCX وقم بالتحويل على دفعات، مع إعادة استخدام نفس كائن `PdfSaveOptions` لتحسين الأداء. +- **إضافة علامة لغة**: للـ PDFs متعددة اللغات، اضبط `pdfOptions.setLanguage("en-US")` لمساعدة التقنيات المساعدة على اختيار الصوت المناسب. + +## مثال كامل يعمل (كل الشيفرة معًا) + +فيما يلي البرنامج الكامل القابل للتنفيذ بلغة Java. انسخه إلى بيئتك التطويرية، عدّل المسارات حسب الحاجة، ثم شغّله. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +شغّله، افتح ملف PDF الناتج، وستحصل على ملف نظيف ومتاح للتوزيع. + +## الخلاصة + +لقد أظهرنا للتو كيفية **حفظ المستند كملف pdf** باستخدام Aspose.Words for Java مع **إضافة إمكانية الوصول إلى pdf** تلقائيًا و**وضع علامة على الخطوط الأفقية** كـ artifacts. النقاط الأساسية: + +- استخدم `PdfSaveOptions` مع امتثال `PDF_UA_2` لتلبية معايير إمكانية الوصول. +- تحميل DOCX واستدعاء `doc.save(..., pdfOptions)` هو كل ما تحتاجه لـ **تحويل docx إلى pdf**. +- يتم التعامل مع الخطوط الأفقية تلقائيًا—لا حاجة لكود إضافي، مما يفي بمتطلب **وضع علامة على الخطوط الأفقية**. +- النهج متوافق تمامًا مع **aspose convert docx pdf**، يعمل مع أحدث نسخة من المكتبة، وينتج PDF جاهزًا للتحقق. + +هل أنت مستعد للتحدي التالي؟ جرّب إضافة بيانات تعريف مخصصة، تضمين الخطوط، أو معالجة مجموعة من ملفات DOCX دفعةً واحدة. كل هذه الإضافات تبني على الأساس الذي وضعناه هنا. + +هل لديك أسئلة حول امتثال PDF/UA، الترخيص، أو معالجة عناصر Word أخرى؟ اترك تعليقًا أو راجع وثائق Aspose الرسمية—هناك الكثير من الأمثلة للاستكشاف. برمجة سعيدة، واستمتع بإنشاء ملفات PDF متاحة! + +![حفظ المستند كملف pdf باستخدام Aspose.Words Java – مثال PDF متاح](placeholder-image.png "حفظ المستند كملف pdf باستخدام Aspose.Words Java") + +## دروس ذات صلة + +- [كيفية حفظ المستند كملف pdf باستخدام Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [كيفية تحويل Word إلى PDF باستخدام Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – تحويل DOCX إلى PDF في Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/arabic/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..4084fe28e6 --- /dev/null +++ b/words/arabic/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: احفظ مستند Word كملف markdown واكتشف كيفية تصدير المعادلات الرياضية إلى + LaTeX باستخدام Aspose.Words للغة Java. حوّل معادلات Word إلى LaTeX في بضع أسطر فقط. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: ar +og_description: احفظ مستند Word كملف Markdown وتعلم كيفية تصدير المعادلات الرياضية + إلى LaTeX باستخدام Aspose.Words للغة Java. دليل كامل وقابل للتنفيذ. +og_title: احفظ Word كـ Markdown – تصدير الرياضيات إلى LaTeX باستخدام Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: حفظ Word كـ markdown – تصدير الرياضيات إلى LaTeX باستخدام Java +url: /ar/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ Word كـ Markdown – تصدير الرياضيات إلى LaTeX باستخدام Java + +هل احتجت يوماً إلى **حفظ Word كـ Markdown** لكنك كنت قلقاً من أن تتحول معادلاتك إلى فوضى غير مفهومة؟ لست وحدك. في هذا الدليل سنستعرض **كيفية تصدير الرياضيات** من ملف `.docx` مباشرة إلى LaTeX بينما يصبح باقي المستند Markdown نظيفاً. + +سنتناول كل شيء من إعداد مكتبة Aspose.Words إلى التحقق من ملف `out.md` النهائي. في النهاية ستتمكن من **تحويل معادلات Word إلى LaTeX** باستدعاء طريقة واحدة، وستفهم التفاصيل الصغيرة التي تجعل التحويل موثوقاً. + +--- + +## ما ستحتاجه + +- **Java 8+** – الكود يعمل على أي JDK حديث. +- **Aspose.Words for Java** – إما الاعتماد عبر Maven/Gradle أو ملف JAR إذا كنت تفضّل الإعداد اليدوي. +- مستند Word (`math.docx`) يحتوي على معادلة Office Math واحدة على الأقل. +- بيئة تطوير متكاملة (IDE) أو سطر أوامر بسيط `javac`/`java` – حسب ما تفضله. + +إذا كان لديك هذه بالفعل، فهذا رائع. إذا لا، القسم التالي يوضح بالضبط كيفية إضافة المكتبة إلى مشروعك. + +--- + +## حفظ Word كـ Markdown – الخطوة 1: إضافة Aspose.Words إلى مشروعك + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **نصيحة احترافية:** Aspose تقدم رخصة مؤقتة مجانية للاختبار. ضع ملف `license.xml` في مجلد الموارد الخاص بك واستدعِ `License license = new License(); license.setLicense("license.xml");` قبل تحميل أي مستند. + +بعد حل الاعتماد، ستكون جاهزاً لكتابة كود التحويل. + +--- + +## كيفية تصدير معادلات الرياضيات إلى LaTeX + +العمل الشاق يتم بواسطة `MarkdownSaveOptions`. عند تغيير `OfficeMathExportMode` إلى `LATEX`، يتم تحويل كل كائن Office Math إلى جزء LaTeX داخل ناتج الـ Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### لماذا يعمل هذا + +- **`Document`** هو نقطة الدخول في Aspose؛ فهو يُجَسِّد ملف `.docx` ويمنحك الوصول إلى كل عقدة، بما في ذلك المعادلات. +- **`MarkdownSaveOptions`** يخبر المكتبة *كيف* تريد النتيجة. السلوك الافتراضي هو تحويل المعادلات إلى صور، مما يتعارض مع هدف التنسيق النصي. +- **`OfficeMathExportMode.LATEX`** يجبر المحرك على تحويل كل عقدة `OfficeMath` إلى ما يعادلها في LaTeX، مما يتيح لمحللات Markdown (مثل GitHub أو Jekyll) عرضها عند دمجها مع إضافة MathJax. + +--- + +## تحويل معادلات Word إلى LaTeX – الخطوة 2: التحقق من ناتج الـ Markdown + +بعد تشغيل البرنامج، افتح `out.md`. يجب أن ترى شيئاً مشابهاً لهذا: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **ملاحظة:** يتم تغليف أجزاء LaTeX بـ `$…$` للرياضيات داخل السطر و `$$…$$` للرياضيات ككتل. هذه هي الصيغة القياسية التي يفهمها معظم مولّدات المواقع الثابتة عندما يكون MathJax مفعلاً. + +إذا كنت تفضّل أن تبقى المعادلات داخل السطر فقط، يمكنك تعديل `MarkdownSaveOptions` أكثر: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## تحويل Docx إلى Markdown LaTeX – الخطوة 3: الحالات الخاصة والمشكلات الشائعة + +| الحالة | ما الذي يجب مراقبته | الحل | +|-----------|-------------------|-----| +| **معادلات متداخلة معقدة** | قد تُخرج Aspose أقواساً إضافية `{}` يتعامل معها بعض المحللات حرفياً. | قم بمعالجة الـ Markdown بعد الإنشاء باستخدام تعبير نمطي بسيط لتقليص `{{` → `{`. | +| **غياب MathJax على الموقع المستهدف** | تظهر المعادلات ككود LaTeX خام. | أضف `` إلى قالب HTML الخاص بك. | +| **مستندات كبيرة** | ارتفاع استهلاك الذاكرة لأن المستند بالكامل يُحمَّل دفعة واحدة. | استخدم `LoadOptions.setLoadFormat(LoadFormat.DOCX)` وفكّر في معالجة الصفحات على دفعات إذا واجهت `OutOfMemoryError`. | +| **عدم تعيين الرخصة** | ستظهر لك تحذير وقد يكون الناتج مائيًا (مُعلَّم). | حمِّل الرخصة مبكراً في `main` كما هو موضح في نصيحة Maven أعلاه. | + +--- + +## حفظ Word كـ Markdown – مثال عملي كامل + +فيما يلي فئة مستقلة يمكنك نسخها ولصقها في أي مشروع Java. فقط استبدل `YOUR_DIRECTORY` بالمسار إلى ملفاتك. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +شغِّل البرنامج (`java MathToLatexMarkdown`) وسترى رسالة في وحدة التحكم تؤكد النجاح. افتح `out.md` في أي محرر – يجب أن تكون المعادلات مقتطفات LaTeX نظيفة جاهزة للعرض. + +--- + +## لقطة من الناتج المتوقع + +![ناتج حفظ Word كـ Markdown مع معادلات LaTeX](https://example.com/images/markdown-latex-output.png "ناتج حفظ Word كـ Markdown مع معادلات LaTeX") + +*تُظهر الصورة مقتطفاً من الـ Markdown المُولَّد حيث تُغلف المعادلة `\int_{a}^{b} f(x)\,dx` بـ `$$`.* + +--- + +## الخلاصة + +لقد أظهرنا للتو كيفية **حفظ Word كـ Markdown** مع الحفاظ على كل معادلة Office Math كـ LaTeX أصلي. الخطوة الأساسية كانت ضبط `MarkdownSaveOptions` باستخدام `OfficeMathExportMode.LATEX`، مما يحول خط أنابيب تحويل Word إلى Markdown التقليدي إلى أداة تحويل تدعم الرياضيات بالكامل. + +الآن يمكنك: + +1. كيفية تصدير الرياضيات من أي ملف `.docx` دون فقدان الدقة. +2. تحويل معادلات Word إلى LaTeX لمولدات المواقع الثابتة أو الوثائق أو المدونات الأكاديمية. +3. توسيع النهج لمعالجة دفعات متعددة من الملفات، دمجه مع خطوط أنابيب CI، أو حتى بناء خدمة ويب صغيرة. + +إذا كنت فضوليًا بشأن الخطوة التالية، جرّب دمج هذا مع **docx to markdown latex** للمستندات التي تحتوي على الكثير من الصور، أو استكشف `HtmlSaveOptions` من Aspose للحصول على نسخة HTML جاهزة للويب. الاحتمالات لا حصر لها—جرّب، واختبر، ثم شارك نتائجك مع المجتمع. + +هل لديك أسئلة أو معادلة صعبة لم تُعرض كما هو متوقع؟ اترك تعليقًا أدناه، وبرمجة سعيدة! + +## دروس ذات صلة + +- [كيفية تصدير LaTeX من Word: تحويل DOCX إلى Markdown وحفظه كـ PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [تحويل docx إلى markdown – تصدير معادلات الرياضيات إلى LaTeX باستخدام Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [كيفية تحويل Word إلى PDF باستخدام Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/arabic/java/document-loading-and-saving/_index.md index 7169854844..6e69b5a125 100644 --- a/words/arabic/java/document-loading-and-saving/_index.md +++ b/words/arabic/java/document-loading-and-saving/_index.md @@ -109,6 +109,9 @@ Aspose.Words for Java يجعل من السهل **حفظ الصور من Word** دليل شامل لاستعادة ملفات DOCX التالفة وإصلاحها ومعالجتها باستخدام Aspose.Words for Java. ### [التقاط تحذيرات استبدال الخطوط في Java باستخدام Aspose.Words – دليل شامل](./capture-font-substitution-warnings-in-java-with-aspose-words/) +### [فتح مستند Word تالف – تعيين وضع الاسترداد في Aspose.Words لـ Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +تعلم كيفية فتح مستندات Word التالفة وتفعيل وضع الاسترداد باستخدام Aspose.Words for Java لتجنب الأخطاء. + #### الحفظ بصيغ مختلفة استكشف مرونة Aspose.Words for Java بينما نتعمق في حفظ المستندات بصيغ مختلفة. حوّل مستنداتك إلى PDF أو DOCX أو حتى HTML بسهولة. *(هنا ستجد أيضًا نمط “save pdf java” قيد التنفيذ.)* diff --git a/words/arabic/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/arabic/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..7b0cd042d0 --- /dev/null +++ b/words/arabic/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: افتح مستند Word تالف في Java باستخدام Aspose.Words. تعلّم كيفية ضبط وضع + الاستعادة واستعادة ملفات Word التالفة بشكل موثوق. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: ar +og_description: افتح مستند Word تالف في Java باستخدام Aspose.Words. يوضح هذا الدليل + كيفية ضبط وضع الاسترداد واستعادة ملفات Word التالفة بكفاءة. +og_title: فتح مستند Word تالف – تعيين وضع الاسترداد في Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: فتح مستند Word تالف – تعيين وضع الاسترداد في Java +url: /ar/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# فتح مستند Word تالف – تعيين وضع الاسترداد في Java + +هل حاولت يومًا فتح مستند Word تالف وشاهدت البرنامج يتعطل بسبب استثناء؟ لست وحدك—تلك الملفات .docx المكسورة يمكن أن تكون صداعًا حقيقيًا. الخبر السار هو أن Aspose.Words for Java يمنحك تحكمًا دقيقًا حتى تتمكن من **open corrupted word document** دون تعطل التطبيق، وحتى تقرر ما إذا كنت تريد تحذيرات، أو استرداد صامت، أو رفض صارم. + +في هذا البرنامج التعليمي سنستعرض العملية الكاملة: من إنشاء `LoadOptions` المناسب، إلى اختيار قيمة **set recovery mode** المناسبة، وأخيرًا التأكد من أن المستند تم تحميله بالفعل. في النهاية ستعرف **how to recover corrupted word file** برمجيًا، دون الحاجة إلى النسخ واللصق يدويًا. + +> **ما ستحتاجه** +> * Java 8 أو أحدث (الـ API يعمل مع Java 11 أيضًا) +> * Aspose.Words for Java 23.9 (أو أحدث نسخة) +> * ملف .docx تالف تجريبي—فقط أعد تسمية أي ملف صالح لمحاكاة الفساد إذا لم يتوفر لديك ملف جاهز + +هيا نبدأ. + +## فتح مستند Word تالف – نظرة عامة خطوة بخطوة + +فيما يلي تدفق المستوى العالي الذي سننفذه: + +1. **Create `LoadOptions`** – هذا الكائن يخبر Aspose.Words كيف يتصرف عندما يواجه مشكلة. +2. **Set recovery mode** – اختر `RECOVER_WITH_WARNINGS` أو `RECOVER_WITHOUT_WARNINGS` أو `REJECT_CORRUPTED`. +3. **Load the document** باستخدام الخيارات المكوّنة. +4. **Verify** أن التحميل نجح (مثلاً، طباعة عدد الصفحات). + +كل خطوة مشروحة بالتفصيل، مع مقتطفات الشيفرة التي يمكنك نسخها ولصقها مباشرة في بيئة التطوير المتكاملة الخاصة بك. + +## تعيين وضع الاسترداد لمختلف السيناريوهات + +تحدد Aspose.Words ثلاث استراتيجيات استرداد داخل `LoadOptions.RecoveryMode`: + +| الوضع | السلوك | متى يُستخدم | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | يحاول تحميل المستند، لكنه يعرض أي مشكلات كتحذيرات في وحدة التحكم. | تريد رؤية *ما* حدث خطأً دون إيقاف العملية. | +| `RECOVER_WITHOUT_WARNINGS` | يصلح ما يمكن بصمت ويقمع التحذيرات. | بيئات الإنتاج حيث يجب أن تكون السجلات نظيفة. | +| `REJECT_CORRUPTED` | يرمي استثناءً فور اكتشاف الفساد. | خطوط التحقق الصارمة التي يجب أن تفشل بسرعة. | + +اختيار الوضع الصحيح هو جوهر **set recovery mode** بشكل صحيح. في معظم جلسات التصحيح، يكون `RECOVER_WITH_WARNINGS` هو الخيار المثالي لأنه يخبرك بالضبط أي الأجزاء تم إصلاحها. + +## كيفية استعادة ملف Word تالف باستخدام Aspose.Words + +فيما يلي **برنامج Java كامل وقابل للتنفيذ** يوضح العملية بأكملها. لا تتردد في وضعه في ملف `RecoveryModeDemo.java`، تعديل المسار، وتشغيله. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### لماذا كل سطر مهم + +* **`LoadOptions loadOptions = new LoadOptions();`** – بدون هذا الكائن يستخدم Aspose.Words الاسترداد الافتراضي، الذي *يرفض* الملفات التالفة. إنشاؤه يمنحك وسيلة لتغيير هذا السلوك. +* **`setRecoveryMode(...)`** – هذا هو استدعاء **set recovery mode** الذي يحدد ما إذا كانت التحذيرات ستظهر، أو تبقى مخفية، أو تتسبب في استثناء. +* **`new Document(path, loadOptions);`** – المُنشئ يقبل `LoadOptions` التي قمنا بتكوينها للتو، لذا تعرف المكتبة كيف تتعامل مع الملف المكسور من البداية. +* **`doc.getPageCount()`** – فحص سريع للتأكد. إذا تم تحميل المستند وعاد بعدد الصفحات، فقد نجحت في **how to recover corrupted word file**. +* **`doc.save(...)`** – اختياري لكنه مفيد؛ يمكنك كتابة النسخة المُصَحَّحة إلى القرص للاستخدام لاحقًا. + +## معالجة الحالات الحدية الشائعة + +### 1. الملف غير موجود + +إذا كان المسار غير صحيح، يرمي `Document` استثناءً من نوع `FileNotFoundException`. ضع عملية التحميل داخل كتلة try‑catch وسجّل رسالة ودية: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. فساد لا يمكن استرداده + +حتى مع `RECOVER_WITH_WARNINGS`، بعض البُنى تكون خارج نطاق الإصلاح. في هذه الحالة لا يزال Aspose.Words يحمل ما يستطيع، لكنك سترى تحذيرات مثل “Cannot read paragraph properties”. انتبه إلى مخرجات وحدة التحكم؛ فهذه التحذيرات غالبًا ما تشير إلى أقسام مفقودة قد تحتاج إلى إعادة بنائها يدويًا. + +### 3. الملفات الكبيرة والأداء + +الإسترداد يضيف عبئًا بسيطًا لأن المكتبة تقوم بتحليل الملف مرتين—مرة لاكتشاف المشكلات، ومرة أخرى لإعادة بنائه. بالنسبة للمستندات متعددة الجيجابايت، فكر في تدفق الملف أو زيادة حجم الذاكرة المخصصة للـ JVM (`-Xmx2g`) لتجنب `OutOfMemoryError`. + +## نصائح احترافية – جعل الاسترداد قويًا + +* **سجّل التحذيرات إلى ملف** – أعد توجيه `System.err` إلى مسجل لتملك سجل تدقيق لما تم إصلاحه. +* **تحقق بعد الاسترداد** – نفّذ `doc.updatePageLayout();` ثم أعد فحص عدد الصفحات؛ أحيانًا يتغير التخطيط بعد إصلاح الأقسام المكسورة. +* **أتمتة الاسترداد الجماعي** – ضع العرض التوضيحي داخل حلقة تعالج مجلدًا من الملفات التالفة، باستخدام نفس `LoadOptions` في كل مرة. + +## الخلاصة + +أنت الآن تعرف بالضبط **how to recover corrupted word file** باستخدام Aspose.Words for Java. من خلال إنشاء كائن `LoadOptions`، واستخدام **set recovery mode** للاستراتيجية التي تناسب حالتك، وتحميل المستند بهذه الخيارات، يمكنك بأمان **open corrupted word document** دون تعطل تطبيقك. الشيفرة النموذجية أعلاه هي حل كامل وجاهز للتنفيذ يطبع عدد الصفحات وحتى يحفظ نسخة مُنقَّحة. + +ما التالي؟ جرّب تبديل وضع الاسترداد إلى `RECOVER_WITHOUT_WARNINGS` وقارن مخرجات وحدة التحكم، أو جرب تحميل مستندات مشفرة (ستحتاج إلى توفير كلمة مرور عبر + +## دروس ذات صلة + +- [Aspose.Words Java: دليل شامل لمعالجة مستندات Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [كيفية تحويل Word إلى PDF باستخدام Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [كيفية مقارنة ملفي Word باستخدام Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/arabic/java/document-styling/_index.md index 2c241d5d94..5ea6cfdc80 100644 --- a/words/arabic/java/document-styling/_index.md +++ b/words/arabic/java/document-styling/_index.md @@ -43,6 +43,8 @@ تعلّم كيفية إضافة العلامات المائية وإعداد إعدادات الصفحات باستخدام Aspose.Words لجافا. دليل شامل مع الكود المصدر. ### [تنسيق رأس وتذييل المستند](./document-header-footer-styling/) تعرّف على كيفية تنسيق رؤوس وتذييلات المستندات باستخدام Aspose.Words لجافا في هذا الدليل المفصل. يتضمن تعليمات خطوة بخطوة وشيفرة المصدر. +### [تعيين إعدادات الخط الافتراضية في Aspose.Words لجافا – دليل شامل](./set-default-font-settings-in-aspose-words-for-java-complete/) +تعلّم كيفية تعيين الخط الافتراضي للمستندات باستخدام Aspose.Words لجافا مع أمثلة عملية وشاملة. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/arabic/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..c6e48ab723 --- /dev/null +++ b/words/arabic/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: قم بتعيين إعدادات الخط الافتراضية في Aspose.Words للـ Java وتعلم كيفية + تعيين إعدادات الخط واكتشاف الخطوط المفقودة في بضع أسطر من الشيفرة فقط. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: ar +og_description: تعيين إعدادات الخط الافتراضية في Aspose.Words للغة Java، وتعلم كيفية + ضبط إعدادات الخط واكتشاف الخطوط المفقودة بسرعة وموثوقية. +og_title: تعيين إعدادات الخط الافتراضية في Aspose.Words لـ Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: تعيين إعدادات الخط الافتراضية في Aspose.Words للغة جافا – دليل كامل +url: /ar/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تعيين إعدادات الخط الافتراضية في Aspose.Words for Java – دليل كامل + +هل تساءلت يومًا كيف **تعيين إعدادات الخط الافتراضية** عند تحميل مستند Word باستخدام Aspose.Words for Java؟ لست وحدك. يمكن أن تحول الأحرف المفقودة تقريرًا مصقولًا إلى فوضى مشوشة، وإن اكتشاف تحذيرات استبدال الخط مبكرًا يوفر ساعات من تصحيح الأخطاء. + +في هذا البرنامج التعليمي سنستعرض مثالًا مختصرًا وشاملًا **يحدد إعدادات الخط الافتراضية**، ويُظهر لك كيفية **تحديد إعدادات الخط** برمجيًا، ويُظهر طريقة موثوقة **لاكتشاف الخطوط المفقودة** قبل أن تُفسد تخطيطك. + +--- + +## ما ستتعلمه + +- كيفية إنشاء كائن `LoadOptions` مع نسخة جديدة من `FontSettings`. +- كيفية إرفاق مستمع تحذير سيقوم **باكتشاف الخطوط المفقودة** أثناء تحميل المستند. +- كيفية تحميل ملف DOCX بينما يقوم المستمع بالإبلاغ بصمت عن أي استبدالات. +- نصائح لتخصيص خطوط الاحتياطي ومعالجة الحالات الخاصة في بيئة الإنتاج. + +لا مكتبات إضافية، ولا ملفات تكوين غامضة—فقط Java عادية و Aspose.Words. + +--- + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من أن لديك: + +1. **Aspose.Words for Java** (الإصدار 23.10 أو أحدث) في مسار الفئات الخاص بك. +2. مجموعة تطوير Java 17 (أو أحدث) – أي JDK حديث يعمل. +3. ملف DOCX يستخدم عمدًا خطًا غير مثبت لديك (مثال، *“MissingFont.ttf”*). + +إذا كنت تفتقد ملف JAR الخاص بـ Aspose، احصل عليه من مستودع Maven الرسمي: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +هذا كل شيء—لا حاجة لتثبيت خطوط إضافية لهذا العرض. + +--- + +## الخطوة 1: إنشاء LoadOptions و **تحديد إعدادات الخط الافتراضية** + +أول شيء نحتاجه هو كائن `LoadOptions` نظيف يخبر Aspose كيف يتصرف عندما يصادف خطوطًا غير معروفة. باستدعاء `setFontSettings(new FontSettings())` نقوم **بتحديد إعدادات الخط الافتراضية** التي تبدأ بقائمة احتياطي فارغة. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **لماذا هذا مهم:** +> عندما لا تقوم بتكوين الخطوط صراحةً، يلجأ Aspose إلى مجموعة الخطوط الافتراضية للنظام، مما قد يخفي مشاكل الخطوط المفقودة. ببدء استخدام نسخة جديدة من `FontSettings` تحصل على سيطرة كاملة على الخطوط التي تُعتبر صالحة. + +--- + +## الخطوة 2: إرفاق مستمع تحذير **لاكتشاف الخطوط المفقودة** + +يقوم Aspose بإصدار كائن `WarningInfo` لكل استبدال يقوم به. بالاستماع إلى `WarningType.FONT_SUBSTITUTION` يمكننا **اكتشاف الخطوط المفقودة** فور تحليل المستند. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **نصيحة احترافية:** يعمل المستمع على نفس الخيط الذي يحمل المستند، لذا لا يوجد تقريبًا أي تأثير على الأداء. إذا كنت بحاجة لجمع التحذيرات للتحليل لاحقًا، ادفعها إلى `List` بدلاً من طباعتها مباشرة. + +--- + +## الخطوة 3: تحميل المستند باستخدام الخيارات المكوَّنة + +الآن بعد أن **حددنا إعدادات الخط** وأعددنا مستمعًا، نقوم ببساطة بتحميل الملف. أي خط مفقود سيُطلق رد النداء الخاص بنا فورًا. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +إذا كان الملف المصدر يشير إلى خط غير مثبت، سترى مخرجات مشابهة لـ: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +هذا السطر يخبرك بالضبط أي خط كان مفقودًا وأي خط احتياطي تم استخدامه—مثالي للتسجيل أو ملاحظات المستخدم. + +--- + +## الخطوة 4: متابعة المعالجة العادية (اختياري) + +في هذه المرحلة يكون المستند محملاً بالكامل، ويمكنك المتابعة بأي تعديل ترغب به—تحرير، تحويل إلى PDF، أو استخراج النص. المستمع التحذيري قد أتم مهمته بالفعل، لذا لا تحتاج إلى فحوصات إضافية. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **ماذا لو أردت احتياطيًا مخصصًا؟** +> بدلاً من ترك `FontSettings` فارغًا، يمكنك إضافة خطوط محددة: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +الآن أي خط مفقود سيُستبدل بـ *Times New Roman*—خيار موثوق لمعظم المستندات الغربية. + +--- + +## نظرة بصرية + +![مخطط يوضح كيفية تعيين إعدادات الخط الافتراضية في Aspose.Words for Java](image.png "مخطط لتدفق تعيين إعدادات الخط الافتراضية") + +*نص بديل: مخطط تدفق تعيين إعدادات الخط الافتراضية في Aspose.Words for Java.* + +--- + +## الأخطاء الشائعة وكيفية تجنبها + +| المشكلة | لماذا يحدث | الحل | +|---------|------------|------| +| **نسيت استدعاء `setFontSettings`** | Aspose يستخدم الإعدادات الافتراضية للنظام، مما يخفي الخطوط المفقودة. | دائمًا أنشئ نسخة جديدة من `FontSettings` وعيّنها إلى `LoadOptions`. | +| **المستمع لم يُفعَّل** | تم إضافة المستمع بعد تحميل المستند. | أضف مستمع التحذير *قبل* استدعاء `new Document(...)`. | +| **خطأ إملائي في المسار يؤدي إلى `FileNotFoundException`** | المسار المكتوب صلبًا لا يتطابق مع حساسية حالة نظام التشغيل. | استخدم `Paths.get("...").toAbsolutePath()` أو اضبط مسارًا نسبيًا من جذر المشروع. | +| **الخطوط المفقودة المتعددة تغمر السجلات** | المستندات الكبيرة قد تولد العشرات من التحذيرات. | صَفِّ التكرارات أو اجمع الرسائل في `Set` قبل الطباعة. | + +--- + +## توسيع الحل + +إذا كنت بحاجة إلى **تحديد إعدادات الخط** لتطبيق كامل، فكر في إنشاء `FontSettings` ككائن مفرد وإعادة استخدامه عبر جميع `LoadOptions`. بهذه الطريقة تحافظ على استراتيجية احتياطي متسقة وتجنب إنشاء كائنات متكررة. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +الآن يمكن لأي جزء من قاعدة الكود الخاصة بك ببساطة استدعاء `FontConfig.getLoadOptions()` والاستفادة فورًا من نفس منطق **تعيين إعدادات الخط الافتراضية**. + +--- + +## الخلاصة + +لقد غطينا الآن كل ما تحتاجه **لتعيين إعدادات الخط الافتراضية** في Aspose.Words for Java، **تحديد إعدادات الخط** برمجيًا، و **اكتشاف الخطوط المفقودة** قبل أن تفسد مخرجاتك. المثال الكامل القابل للتنفيذ موجود في مقتطفات الشيفرة أعلاه، ويمكنك لصقه مباشرةً في بيئة التطوير المتكاملة (IDE) لرؤية التحذيرات تعمل. + +خطوات قادمة؟ جرّب استبدال خط الاحتياطي، جرب صيغ مستندات مختلفة (DOC، RTF، HTML)، أو دمج جامع التحذيرات في لوحة مراقبة. كلما لعبت أكثر مع `FontSettings`، كلما زادت ثقتك بأن المستندات التي تُنشئها تظهر بالضبط كما هو مقصود—بدون مفاجآت، بدون أحرف مكسورة. + +هل لديك أسئلة أو سيناريو استبدال خط معقد؟ اترك تعليقًا أدناه، وتمنياتنا لك بالبرمجة السعيدة! + +## دروس ذات صلة + +- [تعيين إعدادات احتياطي الخط](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [تعيين إعدادات احتياطي الخط](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [تعيين إعدادات احتياطي الخط](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/java/images-shapes/_index.md b/words/arabic/java/images-shapes/_index.md index 447e2fbc6b..3974fb5694 100644 --- a/words/arabic/java/images-shapes/_index.md +++ b/words/arabic/java/images-shapes/_index.md @@ -37,6 +37,9 @@ ### [إنشاء مستند Word في Java – إضافة شكل مستطيل مع تأثير الظل](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) تعلم كيفية إضافة شكل مستطيل بظل إلى مستند Word باستخدام Aspose.Words for Java +### [إنشاء شكل مستطيل في مستند Word باستخدام Java – دليل كامل خطوة بخطوة](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +دليل شامل يوضح كيفية إنشاء شكل مستطيل في مستند Word باستخدام Aspose.Words for Java خطوة بخطوة + ## موارد إضافية - [توثيق Aspose.Words لـ Java](https://reference.aspose.com/words/java/) diff --git a/words/arabic/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/arabic/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..a2b64e9690 --- /dev/null +++ b/words/arabic/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-26 +description: إنشاء شكل مستطيل في مستند Word باستخدام Java وتطبيق تأثير الظل. تعلم + كيفية إضافة ظل للشكل، ضبط مسافة الظل، وحفظ الملف. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: ar +og_description: إنشاء شكل مستطيل في مستند Word باستخدام Java، تطبيق تأثير الظل، إضافة + ظل للشكل، وتعيين مسافة الظل باستخدام Aspose.Words. +og_title: إنشاء شكل مستطيل في مستند Word باستخدام Java – دليل كامل +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: إنشاء شكل مستطيل في مستند Word باستخدام Java – دليل كامل خطوة بخطوة +url: /ar/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء شكل مستطيل في مستند Word باستخدام Java – دليل خطوة‑بخطوة كامل + +هل احتجت يوماً إلى **create rectangle shape** في مستند Word باستخدام Java لكن لم تكن متأكدًا من أين تبدأ؟ لست وحدك—العديد من المطورين يواجهون هذه المشكلة عند توليد التقارير أو الفواتير برمجيًا. في هذا الدرس سنستعرض بالضبط كيفية **create rectangle shape**، إضافة ظل مصقول، وضبط مسافة الظل بدقة لتظهر النتيجة بشكل احترافي. + +سنستخدم Aspose.Words for Java، مكتبة قوية تتيح لك تعديل ملفات Word دون الحاجة إلى تثبيت Microsoft Office. بنهاية هذا الدليل ستكون قادرًا على إنشاء مشاريع **create word document java** التي **add shape shadow**، **apply shadow effect**، و**set shadow distance** ببضع أسطر من الشيفرة فقط. + +--- + +## ما ستبنيه + +- ملف `.docx` جديد يحتوي على مستطيل سينا. +- ظل إسقاط واقعي مُطمس، مائل، وشفاف جزئيًا. +- تحكم كامل في مسافة الظل عن الشكل. +- فئة Java جاهزة للتنفيذ يمكنك وضعها في أي مشروع Maven أو Gradle. + +بدون أدوات خارجية، بدون خطوات يدوية في الواجهة—فقط شيفرة صافية. + +--- + +## المتطلبات المسبقة + +- Java 8 أو أحدث (الشيفرة تعمل على Java 11، Java 17، إلخ). +- مكتبة Aspose.Words for Java (متوفرة عبر Maven Central). +- بيئة تطوير أو محرر نصوص تفضله (IntelliJ IDEA، Eclipse، VS Code…). +- إلمام أساسي بصياغة Java. + +إذا لم تضف اعتماد Maven من قبل، إليك المقتطف السريع: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +الآن، لنبدأ. + +--- + +## الخطوة 1: إنشاء شكل مستطيل في مستند Word + +أول شيء نحتاجه هو مستند فارغ و`DocumentBuilder`. فكر في الـ builder كقلم يكتب داخل المستند. بمجرد حصولنا عليه، يمكننا **create rectangle shape** باستدعاء طريقة واحدة. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **لماذا هذا مهم:** طريقة `insertShape` لا تُنشئ الشكل الهندسي فقط بل تضيفه أيضًا إلى مجموعة الأشكال الداخلية للمستند، بحيث يمكنك البدء فورًا في تنسيقه. + +--- + +## الخطوة 2: تطبيق تأثير الظل على الشكل + +الآن بعد أن أصبح المستطيل موجودًا على الصفحة، سنقوم **apply shadow effect**. الظلال تُضيف عمقًا، تجعل الشكل يبدو كأنه مرتفع عن الصفحة—تحسين بسيط في واجهة المستخدم يمكن أن يعزز قابلية القراءة في التقارير. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **نصيحة احترافية:** قيمة التمويه `5.0` تبدو طبيعية لمعظم المستندات المعروضة على الشاشات. إذا كنت تطبع، قد ترغب في قيمة أقل قليلًا لتجنب مظهر ضبابي. + +--- + +## الخطوة 3: ضبط مسافة الظل – تحسين الموضع + +الظلال ليست مجرد تمويه؛ فهي تحتاج أيضًا إلى الإزاحة الصحيحة. هنا نستخدم **set shadow distance**. مسافة `7.0` نقطة تُنشئ إزاحة معتدلة تُلاحظ ولكنها ليست مفرطة. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **ماذا لو احتجت إزاحة أكبر؟** زد القيمة؛ قللها للحصول على مظهر أكثر إحكامًا. تذكر أن المسافة تعمل مع الزاوية لتحديد موضع الظل بدقة. + +--- + +## الخطوة 4: حفظ المستند – تثبيت عملك + +أخيرًا، نكتب المستند إلى القرص. غيّر المسار إلى المكان الذي تريد حفظ الملف فيه. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +تشغيل الفئة يُنشئ ملف `shadow.docx`، وعند فتحه في Microsoft Word أو LibreOffice، سيظهر مستطيل سينا مع ظل رمادي ناعم مائل بزاوية 45° وإزاحة 7 نقاط. + +--- + +## مثال كامل يعمل + +فيما يلي الشيفرة الكاملة جاهزة للنسخ واللصق. تشمل جميع الاستيرادات، التعليقات، واستدعاء `save` النهائي. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**الناتج المتوقع:** افتح `shadow.docx` → سترى مستطيلًا سيناًا مركزيًا في الصفحة الأولى، يُسقط ظلًا رماديًا خفيفًا مائلًا قليلًا إلى أسفل‑يمين. تمويه الظل وشفافيته يجعلان المظهر كإضاءة طبيعية. + +--- + +## أسئلة شائعة وحالات خاصة + +### “هل يمكنني استخدام شكل مختلف؟” + +بالطبع. استبدل `ShapeType.RECTANGLE` بـ `ShapeType.OVAL` أو `ShapeType.LINE` أو أي تعداد مدعوم آخر. يبقى باقي شيفرة الظل كما هو. + +### “ماذا لو احتجت ظلالًا متعددة؟” + +Aspose.Words يدعم ظلًا واحدًا فقط لكل شكل. لمحاكاة ظلال متعددة، قم بنسخ الشكل، إزاحة كل نسخة، وضبط الشفافية. + +### “هل الظل مرئي في LibreOffice؟” + +نعم—Aspose.Words يكتب OOXML قياسيًا، والذي تفسره LibreOffice بشكل صحيح. قد يختلف مظهر الظل قليلًا بسبب محركات العرض، لكن التأثير يبقى موجودًا. + +### “كيف أغيّر لون الظل ليتطابق مع علامتي التجارية؟” + +ما عليك سوى استبدال `java.awt.Color.GRAY` بأي `java.awt.Color` تفضله، مثل `new java.awt.Color(0, 120, 215)` للون أزرق مؤسسي. + +--- + +## توضيح بصري + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*نص بديل:* **create rectangle shape** توضيح يُظهر مستطيلًا سيناًا مع ظل رمادي إسقاطي في مستند Word. + +--- + +## ملخص وخطوات مستقبلية + +غطّينا كيفية **create rectangle shape**، **apply shadow effect**، **add shape shadow**، و**set shadow distance** باستخدام Aspose.Words for Java. الشيفرة مستقلة، تعمل على أي JDK حديث، وتنتج ملف `.docx` مصقول جاهز للتوزيع. + +هل تريد التعمق أكثر؟ جرّب: + +- إضافة نص داخل المستطيل باستخدام `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- إنشاء جدول من الأشكال لبناء مخطط. +- تصدير المستند إلى PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +كل هذه الخطوات تبني على الأساسيات التي استعرضناها للتو، لذا ستشعر بالراحة في توسيع المثال. + +--- + +## الخاتمة + +إتقان مهام **create word document java** مثل تشكيل الأشكال وتظليلها يمنحك ميزة كبيرة عند أتمتة التقارير، العقود، أو المواد التسويقية. النهج المعروض هنا نظيف، قابل للصيانة،—والأهم—سهل التعديل لأي نمط بصري تحتاجه. + +جرّب الشيفرة، عدّل التمويه، الزاوية، والمسافة، وشاهد مستنداتك تتحول من عادية إلى مصقولة. إذا واجهت أي عائق، اترك تعليقًا أدناه؛ أنا سعيد بالمساعدة. + +برمجة سعيدة! + +## دروس ذات صلة + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/chinese/java/document-conversion-and-export/_index.md index b30bf2fb11..5cab85978d 100644 --- a/words/chinese/java/document-conversion-and-export/_index.md +++ b/words/chinese/java/document-conversion-and-export/_index.md @@ -88,8 +88,13 @@ Aspose.Words for Java 的关键功能之一是能够 **convert docx to pdf** 并 本教程展示如何使用 Aspose.Words for Java 将 DOCX 文件快速转换为 PDF,包含代码示例和关键设置。 ### [从 DOCX 创建可访问 PDF – 完整指南](./create-accessible-pdf-from-docx-complete-guide/) + 学习如何使用 Aspose.Words for Java 将 DOCX 转换为符合 WCAG 标准的可访问 PDF,涵盖标签、结构和元数据设置。 +### [在 Java 中创建可访问 PDF – 完整标记指南](./create-accessible-pdf-in-java-full-tagging-guide/) + +本教程详细演示如何使用 Aspose.Words for Java 在 Java 环境下生成符合 WCAG 标准的可访问 PDF,并完整添加标签。 + ### [在 Aspose.Words for Java 中格式化表格和表格样式](./formatting-tables-and-table-styles/) 了解如何在 Aspose.Words for Java 中格式化表格并应用表格样式。通过带源码的分步指南学习有效的表格格式化。使用 Aspose.Words 提升文档布局。 @@ -97,10 +102,20 @@ Aspose.Words for Java 的关键功能之一是能够 **convert docx to pdf** 并 本教程演示如何使用 Aspose.Words for Java 将 DOCX 文件转换为 Markdown,并将文档中的数学公式导出为 LaTeX 代码。 +### [在 Aspose.Words for Java 中将 Word 保存为 Markdown – 导出数学为 LaTeX](./save-word-as-markdown-export-math-to-latex-with-java/) + +本教程演示如何使用 Aspose.Words for Java 将 Word 文档保存为 Markdown,并将文档中的数学公式导出为 LaTeX 代码。 + ### [将文档另存为 TXT – 导出 Word 数学的快速指南](./save-document-as-txt-quick-guide-to-exporting-word-math/) +### [使用 Java 将 docx 导出为 txt – 完整编程指南](./export-docx-to-txt-with-java-complete-programming-guide/) + ### [在 Aspose.Words for Java 中将 DOCX 转换为 Markdown 时嵌入图像](./how-to-embed-images-in-markdown-when-converting-docx/) +### [在将 DOCX 转换为 Markdown 时嵌入图像为 Base64](./embed-images-as-base64-when-converting-docx-to-markdown/) + +### [在 Aspose.Words for Java 中将文档保存为 PDF – 完整可访问性指南](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) + ## 常见问题 **Q: How do I add a watermark to an existing PDF using Aspose.Words?** diff --git a/words/chinese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/chinese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..830d2d82c7 --- /dev/null +++ b/words/chinese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: 使用逐步代码在 Java 中创建可访问的 PDF。了解如何为可访问性标记 PDF,并使用 PdfSaveOptions 启用 PDF 标记。 +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: zh +og_description: 使用逐步代码在 Java 中创建可访问的 PDF。了解如何为可访问性标记 PDF,并使用 PdfSaveOptions 启用 PDF + 标记。 +og_title: 在 Java 中创建可访问的 PDF – 完整标记指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: 在 Java 中创建可访问的 PDF – 完整标记指南 +url: /zh/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Java 中创建可访问的 PDF – 完整标签指南 + +有没有想过如何直接从 Java 代码创建 **可访问的 PDF** 文件?你并不孤单。许多开发者需要为依赖屏幕阅读器的用户提供服务,而普通 PDF 与可访问 PDF 之间的差距可能非常大。在本教程中,我们将演示 **如何为可访问性标记 PDF**,展示使用 Aspose PDF for Java **如何创建带标签的 PDF**,并揭示 **向 PDF 添加可访问性标签** 的具体步骤,以便每位阅读器都能获取相同的信息。 + +我们还将介绍 **启用 PDF 标记** 的最佳实践、常见陷阱,以及一个完整、可直接运行的示例,您可以立即将其放入项目中。没有模糊的引用——只有具体的代码、解释以及一个可以在 Adobe Acrobat 中打开以验证标签的最终文件。 + +## 您将学习的内容 + +- PDF 标记及可访问性合规背后的原因。 +- 先决条件和库设置(Aspose PDF for Java 23.10 或更高)。 +- 如何从头 **创建可访问的 PDF**,一步步进行。 +- 在基本的 `setTagDocumentStructure` 调用之外,**向 PDF 添加可访问性标签** 的方法。 +- 测试输出和排查常见问题的技巧。 + +通过本指南,您将能够生成符合 WCAG 2.1 AA 检查且外观专业的 PDF。 + +--- + +## 前提条件 + +在开始之前,请确保您具备以下条件: + +| 要求 | 原因 | +|------|------| +| **Java 8+** | 现代语言特性和更好的 Unicode 处理。 | +| **Aspose PDF for Java** (v23.10 or newer) | 提供 `PdfSaveOptions` 类和标签支持。 | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | 便于编译和调试。 | +| **Write permission** to a folder where the PDF will be saved | `doc.save` 调用需要可写路径。 | + +如果您尚未将 Aspose PDF 添加到项目中,请在 `pom.xml` 中加入以下 Maven 依赖: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **专业提示:** 使用最新版本;更新的发布会提升标签准确性并添加语言特定的可访问性功能。 + +--- + +## 步骤 1:设置文档骨架 + +首先,我们创建一个全新的 `Document` 对象。可以把它看作一块空白画布,稍后会在其中放入我们为可访问性所需的标签。 + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**为什么这很重要:** 没有任何内容就没有可标记的对象。即使只添加一个简单的 `TextFragment`,也会为标记引擎提供可操作的对象,并且在我们随后启用结构标记时,它会自动创建一个 `

`(段落)标签。 + +--- + +## 步骤 2:创建 PDF 保存选项(标记核心) + +现在我们准备选项,告诉 Aspose PDF 在文件中嵌入逻辑结构树。 + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +调用 `setTagDocumentStructure(true)` 即是 **启用 PDF 标记** 的开关。设为 true 时,库会构建一个与视觉布局相对应的标签树,使辅助技术能够读取 PDF。 + +> **注意:** 这是最简便的 **如何创建带标签的 pdf** 方法。若需更细粒度的控制(例如设置语言或自定义标签),可以探索 `pdfOptions.setTagLanguage("en-US")` 和 `pdfOptions.setTagStructureTreeRoot(...)`。 + +--- + +## 步骤 3:保存可访问的 PDF + +最后,使用我们刚配置好的选项将文档写入磁盘。 + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +当 `doc.save` 完成后,您将在 `output` 文件夹中看到 `accessible.pdf`。在 Adobe Acrobat 中打开并查看 **File → Properties → Description → Tags**——您应该能看到已填充的标签树。 + +--- + +## 如何为 PDF 添加可访问性标签 – 超越基础 + +上述三步代码已经 **向 PDF 添加可访问性标签**,但实际文档往往需要更多细节。以下是一些可以加入的增强措施: + +### 1. 设置文档语言 + +屏幕阅读器使用语言属性来正确发音文本。 + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. 提供标题和主题 + +元数据帮助辅助工具在用户打开文件之前提供上下文信息。 + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. 为图像添加替代文本标签 + +如果嵌入图片,需要提供 `alt` 描述。 + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. 标记表格标题行 + +表格如果不标记标题行,阅读器往往会感到困惑。 + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +这些额外步骤使您的 PDF 不仅在 *技术上* 带标签,而且真正对多元化受众 **可访问**。 + +--- + +## 启用 PDF 标记时的常见陷阱 + +| 症状 | 可能原因 | 解决办法 | +|------|----------|----------| +| Acrobat 中缺少标签 | `setTagDocumentStructure` 保持为 `false` | 确保调用 `pdfOptions.setTagDocumentStructure(true)`。 | +| 阅读顺序错误 | 复杂布局未显式标记标签 | 使用 `pdfOptions.setTagStructureTreeRoot(...)` 定义自定义顺序。 | +| 图像被读取为“image”,没有描述 | 未设置替代文本 | 调用 `image.getAlternativeText().setValue("...")`。 | +| 语言未被识别 | `setTagLanguage` 缺失或使用错误的地区设置 | 提供 BCP‑47 语言代码(如 `en-US`、`fr-FR`)。 | + +了解这些问题可以为您后续节省大量调试时间。 + +--- + +## 验证结果 – 预期表现 + +运行程序后,在 Adobe Acrobat Reader 中打开 `output/accessible.pdf`: + +1. **标签面板**(`View → Show/Hide → Navigation Panes → Tags`)应显示类似 `/Document → /Part → /Sect → /Para` 的层级结构。 +2. **阅读顺序**应遵循视觉流(先是文本,然后是图像)。 +3. **屏幕阅读器**(NVDA、VoiceOver)会朗读 “Hello, accessible PDF!” 而不是仅仅 “Page 1”。 + +如果上述任意项目缺失,请再次检查上述步骤——尤其是 `setTagDocumentStructure` 调用。 + +--- + +## 完整可运行示例(复制粘贴即用) + + + +## 相关教程 + +- [从 Word 创建可访问的 PDF – 转换为 PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [从 DOCX 创建可访问的 PDF – 完整指南](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [如何使用 Aspose.Words for Java 将文档保存为 PDF](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/chinese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..c166db28c2 --- /dev/null +++ b/words/chinese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-26 +description: 在使用 Aspose.Words for Java 将 docx 转换为 markdown 时,将图像嵌入为 base64。学习如何将 Word + 转换为 markdown、将 Word 保存为 markdown,并处理图像。 +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: zh +og_description: 在使用 Aspose.Words for Java 将 docx 转换为 markdown 时,将图像嵌入为 base64。完整指南,教您将 + Word 转换为 markdown 并将 Word 保存为 markdown。 +og_title: 在将 DOCX 转换为 Markdown 时将图像嵌入为 Base64 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: 在将 DOCX 转换为 Markdown 时嵌入 Base64 图像 +url: /zh/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在将 DOCX 转换为 Markdown 时将图像嵌入为 Base64 + +是否曾想过在 **将 docx 转换为 markdown** 的同时 **将图像嵌入为 base64**?你并不是唯一有此需求的人——开发者们经常询问如何在不处理单独文件的情况下保持图像内联。好消息是 Aspose.Words for Java 能轻松实现:你可以将 Word 文档转换为 Markdown,并自动将每张图片嵌入为 Base64 字符串。 + +在本教程中,我们将完整演示整个过程——从加载包含图片的 `.docx`,到配置一个执行核心工作的 `MarkdownSaveOptions` 回调,最后将结果保存为干净的 `.md` 文件。结束后,你将清楚地知道如何 **convert word to markdown**、**convert images to base64**,以及 **save word as markdown**,且不会留下零散的图片文件夹。无需外部工具,无需手动后处理——只需一段可以直接放入任何项目的纯 Java 代码。 + +## 你需要准备的环境 + +- **Java 17**(或任意近期 JDK)——代码使用 lambda 语法,若使用旧版本可自行改写。 +- **Aspose.Words for Java** 库(截至 2026 年的最新版本)。将 Maven 依赖或 JAR 包加入 classpath。 +- 一个包含至少一张图片的示例 **DOCX** 文件。 +- 一个 IDE 或简单的文本编辑器——Visual Studio Code、IntelliJ IDEA,甚至 `vim` 都可以。 + +如果你已经具备以上条件,太好了——直接进入下一步。 + +## 第一步:加载 Word 文档 + +首先创建指向源文件的 `Document` 实例。无论是 **convert docx to markdown** 还是仅仅读取文件,这一步都是相同的。 + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **为什么重要:** `Document` 对象是所有 Aspose 操作的入口。它包含完整的 Word 结构——包括图片、表格和样式——因此后续回调能够检查每个资源。 + +## 第二步:创建 MarkdownSaveOptions 并注册资源保存回调 + +魔法就在 `MarkdownSaveOptions` 中。通过附加 `IResourceSavingCallback`,我们可以控制每个外部资源(如图片)的写入方式。 + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: 为什么使用 `setSaveToMemory(true)`? + +当 `saveToMemory` 为 true 时,Aspose 会将图片字节写入内存流而不是文件。Markdown 导出器随后将该流转换为 Base64 字符串,并直接插入到 Markdown 的图片标签中: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +这就是 **embed images as base64** 的核心。 + +## 第三步:将文档保存为 Markdown + +回调就位后,最后一步只需调用 `save`。此时我们真正完成了 **convert word to markdown**,并且通过回调实现了 **convert images to base64**。 + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **结果:** `out.md` 包含了带有每张图片的 `data:` URI 的 Markdown 文本。磁盘上不会生成额外的图片文件,文件夹保持整洁。 + +## 第四步:验证输出并注意常见陷阱 + +在任意 Markdown 查看器(VS Code、GitHub 或静态站点生成器)中打开生成的 `out.md`。你应该会看到类似下面的内容: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### 故障排查清单 + +| 问题 | 可能原因 | 解决办法 | +|------|----------|----------| +| 图片显示为破损链接 | 未使用 `setSaveToMemory` | 确保在回调中调用 `args.setSaveToMemory(true);` | +| Base64 字符串被截断 | 输出文件编码不匹配 | 使用 UTF‑8 保存 Markdown(Aspose 默认即为 UTF‑8) | +| 文件名异常 | `setKeepResourceOriginalName(true)` | 保持为 `false` 以强制使用自定义命名逻辑 | + +## 第五步:高级变体(可选) + +### 仅转换选定的图片 + +如果只想嵌入满足特定条件的图片(例如大于 100 KB),可以加入大小检查: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### 使用不同的图片格式 + +`ResourceSavingArgs` 提供原始字节,你可以在嵌入前将 JPEG 重新编码为 PNG——当目标 Markdown 阅读器更倾向于 PNG 时非常有用。 + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +这些调整展示了在 **convert docx to markdown** 时 **embed images as base64** 方法的灵活性。 + +## 结论 + +你已经学会了在使用 Aspose.Words for Java 将 **docx 转换为 markdown** 时 **embed images as base64**。只需简单地接入 `IResourceSavingCallback`,库就会完成所有繁重工作:它 **convert word to markdown**、**convert images to base64**,并通过一次 `save` 调用 **save word as markdown**。 + +尽情实验吧——尝试不同的图片过滤规则、切换到 HTML 输出,或将此步骤与静态站点生成器链式组合。同样的模式也适用于其他格式(HTML、EPUB),因此你可以在任何需要内联资源的场景中复用该回调。 + +**后续步骤:** +- 探索 `HtmlSaveOptions`,实现 HTML‑with‑Base64 图像。 +- 将此过程与 CI 流水线结合,实现文档自动生成。 +- 若需更细粒度的转换控制,可深入研究 Aspose 的 `DocumentVisitor`。 + +祝编码愉快,享受干净的自包含 Markdown 文件吧! + +## 相关教程 + +- [在将 DOCX 转换为 Markdown 时嵌入图像](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – 将数学公式导出为 LaTeX](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [从 Word 中保存图像 – Aspose.Words for Java 指南](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/chinese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..f6418b4321 --- /dev/null +++ b/words/chinese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-26 +description: 使用 Java 和 Aspose.Words 将 docx 导出为 txt。了解如何将 docx 转换为文本,保留 Unicode,并在几步内将 + Word 导出为 txt。 +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: zh +og_description: 在 Java 中将 docx 导出为 txt。本教程展示如何将 docx 转换为文本,保持纯文本 Unicode,并高效地将 Word + 导出为 txt。 +og_title: 使用 Java 将 docx 导出为 txt – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: 使用 Java 将 docx 导出为 txt – 完整编程指南 +url: /zh/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Java 将 docx 导出为 txt – 完整编程指南 + +是否曾经需要 **export docx to txt** 但担心丢失特殊字符?你并不是唯一的。当你将 Word 文档转换为纯文本文件时,Unicode 符号、表格,甚至简单的格式都可能像魔法一样消失。 + +在本指南中,我们将演示一种使用 Aspose.Words for Java 的可靠方法来 **export docx to txt**,保留每个 Unicode 字形并保持表格布局可读。完成后,你还将了解如何 **convert docx to text**、**convert word to text**,甚至 **export word as txt**,轻松实现。 + +## 本教程涵盖内容 + +* 在 Java 项目中设置 Aspose.Words +* 加载 DOCX 文件并为纯文本输出做准备 +* 通过 `TxtSaveOptions` 配置 **plain text unicode** 支持 +* 可选技巧:在生成的 `.txt` 文件中保持表格可读 +* 保存文件并验证输出 + +无需外部脚本,也不需要神秘的命令行工具——只需纯 Java 代码,直接放入任何 Maven 或 Gradle 项目中即可。 + +> **Why care?** 纯文本文件轻量、易于版本控制,并且非常适合搜索索引或下游处理流水线。如果你曾尝试 `cat` 一个 Word 文件却得到乱码,本教程可以解决该问题。 + +## 导出 docx 为 txt – 概览 + +在深入代码之前,让我们先澄清术语。**Export docx to txt** 指的是将 Microsoft Word `.docx` 包的文本内容写入一个简单的 `.txt` 文件。与 PDF 转换不同,文本导出会去除样式,但可以保留换行、段落标记,以及——如果正确配置——Unicode 字符,如表情符号、重音字母或亚洲文字。 + +Aspose.Words 让这变得轻而易举,因为它抽象了 Word 文件格式,并提供了 `TxtSaveOptions` 类,可让你指定编码、表格处理方式等。 + +### 前置条件 + +* Java 11 或更高(API 兼容 Java 8+,但我们假设使用较新的 JDK) +* Aspose.Words for Java JAR(可从 Maven Central 获取) +* 一个示例 `unicode.docx` 文件,包含多种 Unicode 字符——比如 “こんにちは”、 “😊” 以及一个简单表格 + +如果你已经准备好这些,让我们开始吧。 + +## 步骤 1:加载 DOCX 文件(Convert docx to text) + +首先需要做的是将源文档读取到内存中。这就是 **convert docx to text** 过程正式开始的地方。 + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*这点为何重要:* `Document` 是 Aspose.Words 对 Word 文件的表示。加载后,你可以访问所有段落、表格,甚至隐藏元素。如果文件未找到,Aspose 会抛出明确的 `FileNotFoundException`,让你立刻知道出了什么问题。 + +## 步骤 2:为 Unicode 配置 TxtSaveOptions(Plain text unicode) + +纯文本文件只是字节流,因此必须告诉 Java 使用哪种字符集。UTF‑8 是 **plain text unicode** 的事实标准,因为它能够编码所有 Unicode 代码点。 + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **技巧提示:** 如果跳过 `setEncoding` 调用,Aspose 会默认使用平台的默认字符集,在许多 Windows 机器上是 Windows‑1252。该默认会悄悄丢弃像 “ß” 或 “—” 这样的字符。 + +## 步骤 3:保留表格布局(可选,但有助于可读性) + +当你 **export word as txt** 时,表格通常会被压平成单行文本,导致难以阅读。Aspose.Words 提供了一个简单的标志来保持视觉结构。 + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*使用时机:* 如果源 DOCX 包含发票、时间表或任何网格状数据,启用 `PreserveTableLayout` 将插入制表符和换行符,使生成的文件仍然类似表格。如果不需要此功能,可以省略此行,以获得更紧凑的输出。 + +## 步骤 4:将文档保存为纯文本(Export word as txt) + +现在繁重的工作已经完成——只需将字节写入磁盘。 + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +运行程序后会在同一文件夹生成 `plain.txt`。使用任意文本编辑器(Notepad++、VS Code,甚至终端中的 `cat`)打开,你会看到: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +请注意,日文问候语和笑脸表情得以保留,表格也因 `PreserveTableLayout` 而保持列对齐。这正是一次干净的 **export docx to txt** 所体现的要点。 + +## 步骤 5:验证输出(Convert word to text 完整性检查) + +快速的完整性检查可以防止静默的数据丢失。以下是几种确认你已正确 **convert word to text** 的方法: + +1. **Checksum comparison** – 计算 `.txt` 文件在往返转换(txt → docx → txt)前后的 SHA‑256 哈希,以确保稳定性。 +2. **Search for Unicode markers** – 使用 `grep` 或 IDE 的文件搜索功能定位像 “😊” 这样的字符。 +3. **Open in multiple editors** – 某些旧版 Windows Notepad 在没有 BOM 的情况下仍会误解 UTF‑8;在 VS Code 中打开文件可确认编码正确。 + +如果这些检查中的任意一项失败,请再次确认已设置 `saveOptions.setEncoding(StandardCharsets.UTF_8)`,并且源 DOCX 确实包含 Unicode 文本。 + +## 常见陷阱及避免方法 + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **缺失字符** | 默认系统字符集(例如 Windows‑1252)会丢弃非 ASCII 字形。 | 通过 `saveOptions.setEncoding` 明确设置为 UTF‑8。 | +| **表格变成单行** | `PreserveTableLayout` 保持默认 `false`。 | 调用 `saveOptions.setPreserveTableLayout(true)`。 | +| **文件未找到** | 路径错误或缺少读取权限。 | 使用绝对路径或 `Paths.get(...)` 并进行适当的异常处理。 | +| **大文档性能下降** | 将整个文档加载到内存中。 | 如果只需要特定章节,可使用 `DocumentBuilder` 分块流式读取文档。 | + +## 额外内容:批量导出多个 DOCX 文件 + +如果需要对整个文件夹的 **convert docx to text**,可以将逻辑包装在循环中: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +此代码片段会对目录中的每个文件执行 **export docx to txt**,为你节省数小时的手动工作。 + +## 结论 + +你刚刚学习了如何使用 Java **export docx to txt**,确保每个 Unicode 字符保持完整,表格保持可读,且整个过程可重复。通过为 UTF‑8 配置 `TxtSaveOptions` 并可选地保留表格布局,你可以可靠地 **convert docx to text**、**convert word to text**,以及 **export word as txt**,以满足任何下游工作流的需求。 + +准备好迎接下一个挑战了吗?尝试导出为其他纯文本格式,如 markdown(`.md`)或 CSV,或探索 Aspose.Words 的 PDF 转换功能。同样的原则——显式编码、布局保留以及彻底验证——在所有场景中都适用。 + +祝编码愉快,愿你的文本文件始终保持丰富的 Unicode! + +--- + +![导出 docx 为 txt 流程图](/images/export-docx-to-txt-pipeline.png){alt="导出 docx 为 txt 流程图"} + +## 相关教程 + +- [将 Docx 转换为 Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – 在 Java 中将 DOCX 转换为 PDF](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [将 docx 转换为 markdown – 使用 Aspose.Words 导出数学公式为 LaTeX](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/chinese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..142c3bdb51 --- /dev/null +++ b/words/chinese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-05-26 +description: 使用 Aspose.Words Java 将文档保存为 PDF 并为 PDF 添加可访问性。学习将 docx 转换为 PDF、标记水平线,并确保符合 + PDF/UA‑2 标准。 +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: zh +og_description: 使用 Aspose.Words Java 将文档保存为 PDF 并为 PDF 添加可访问性。一步一步的指南,将 docx 转换为 PDF + 并为水平线标记以符合 PDF/UA‑2 标准。 +og_title: 使用 Aspose.Words Java 将文档保存为 PDF – 轻松实现可访问性 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: 使用 Aspose.Words Java 将文档保存为 PDF – 完整可访问性指南 +url: /zh/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.Words Java 将文档保存为 PDF – 完整可访问性指南 + +有没有想过在将 **文档保存为 PDF** 的同时保持其对屏幕阅读器的可访问性?你并不孤单。许多开发者需要 *convert docx to pdf* 并仍然满足 PDF/UA‑2 标准,尤其是当源文件包含必须正确标记的水平线时。在本教程中,我们将逐步演示如何使用 Aspose.Words for Java **将文档保存为 PDF**,自动 **add accessibility to PDF**,并确保每条水平线都 **tagged** 为 artifact。 + +我们将从一个全新的 Java 项目开始,加载一个已经包含水平线的 DOCX,配置 PDF 保存选项以符合 PDF/UA‑2 标准,最后生成一个完整可访问的 PDF。完成后,你将能够 **save document as pdf**,并确信它通过可访问性检查。 + +## 前提条件 + +- 已安装 Java 8 或更高版本(本教程在 JDK 17 上测试)。 +- Maven 3.6+(如果喜欢也可以使用 Gradle)用于管理依赖。 +- 有效的 Aspose.Words for Java 许可证(免费试用可用,但许可证会去除评估水印)。 +- 一个包含至少一条水平线的 DOCX 文件(`input.docx`),想象一下在 Word 中添加的简单分隔线。 + +> **技巧提示:** 如果没有现成的 DOCX,只需新建一个 Word 文档,输入几段文字,插入 *Insert → Horizontal Line*,保存为 `input.docx`,并放置在你选择的文件夹中。 + +## 步骤 1:设置 Maven 项目 + +首先,创建一个新的 Maven 项目(或在已有项目中添加)。`pom.xml` 需要加入 Aspose.Words 依赖: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** 添加 `aspose-words` 架构是 *convert docx to pdf* 的第一步。没有它,编译器将无法识别 `Document`、`PdfSaveOptions` 等关键类。 + +## 步骤 2:加载包含水平线的源 DOCX + +现在我们编写一个小的 Java 类来加载 DOCX。这是 **tag horizontal rules** 部分的开始——Aspose.Words 会自动将水平线视为带边框的段落,但我们让 PDF/UA 引擎处理标记。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +注意我们尚未保存任何内容——我们只是 **loading** 了 DOCX,这已经是 *convert docx to pdf* 的前半段。`Document` 对象现在包含了所有 Word 内容,包括你插入的任何水平线。 + +## 步骤 3:配置 PDF 保存选项以符合 PDF/UA‑2 标准 + +**adding accessibility to PDF** 的关键在于 `PdfSaveOptions`。将合规级别设置为 `PDF_UA_2`,Aspose.Words 将: + +1. 标记结构元素(标题、表格等)。 +2. 将装饰性元素——如水平线——标记为 *artifacts*,使屏幕阅读器忽略它们。 +3. 插入必要的 PDF/UA 元数据。 + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** 如果不使用 `PDF_UA_2`,生成的 PDF 可能仍可阅读,但无法通过自动化的可访问性验证器。**tag horizontal rules** 的需求会自动满足,因为在开启合规标志时 PDF/UA 会将它们视为 *artifacts*。 + +## 步骤 4:将文档保存为 PDF + +现在我们终于 **save document as pdf**。这一行代码完成了繁重的工作——转换 DOCX、应用可访问性标签并写入磁盘。 + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +运行类 (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) 后,你会看到确认信息。打开生成的 `ua_compliant.pdf`,在 Adobe Acrobat 中检查 **File → Properties → Description → PDF/A, PDF/UA**——应显示 “PDF/UA‑2”。 + +### 预期输出 + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +打开 PDF,你会注意到: + +- 文本可选择且可搜索。 +- 水平线对屏幕阅读器不可见(被视为 artifact)。 +- PDF 通过了基本的 PDF/UA 验证工具(例如 PAC 3)。 + +## 步骤 5:验证可访问性 – 快速检查清单 + +即使 Aspose.Words 已完成大部分工作,最好仍然手动验证输出。 + +| 检查 | 验证方法 | +|-------|----------------| +| **文档标题** | 打开 Acrobat → File → Properties → Title 字段(应与 `pdfOptions.setTitle` 匹配)。 | +| **Artifact 标记** | 使用 Acrobat 的 “Reading Order” 工具。水平线应显示为 *Artifact*(灰色)。 | +| **逻辑阅读顺序** | 在 Acrobat 中运行 “Accessibility Checker”;确保没有结构错误。 | +| **Tagged PDF** | 在 Acrobat 的 “Tags” 面板下查看——应看到层次结构(Document → Section → Paragraph 等)。 | +| **PDF/UA 合规性** | Acrobat 在 “Standards” 选项卡下会显示 “PDF/UA‑2”。 | + +如果这些检查中的任何一项未通过,请再次确认使用了最新的 Aspose.Words 版本,并且已正确调用 `setCompliance(PdfCompliance.PDF_UA_2)`。 + +## 常见陷阱及避免方法 + +1. **Missing License** – 试用版会添加水印,可能导致 PDF/UA 验证失败。请在 `main` 方法开头尽早应用许可证: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` 会中止转换。使用绝对路径或将 DOCX 放在项目根目录,并使用 `new File("input.docx").getAbsolutePath()` 引用。 +3. **Using Older Aspose Version** – PDF/UA 支持在 22.9 版加入。请升级到最新发布以避免功能缺失。 +4. **Horizontal Rule as Image** – 若将线条插入为图片而非 Word 原生水平线,Aspose 会将其视为普通图片,而非 artifact。请使用 Word 内置的 *Horizontal Line* 替代图片,以实现正确标记。 + +## 扩展方案 – 如果需要更多功能怎么办? + +- **Custom Tags**:如果还有其他装饰元素(如装饰性图标),可以使用 `PdfSaveOptions.setArtifactTaggingEnabled(true)` 手动将它们标记为 artifacts。 +- **Multiple Documents**:遍历一个 DOCX 文件夹进行批量转换,复用同一个 `PdfSaveOptions` 实例以提升性能。 +- **Adding a Language Tag**:针对多语言 PDF,设置 `pdfOptions.setLanguage("en-US")`,帮助辅助技术选择正确的语音。 + +## 完整工作示例(全部代码) + +下面是完整的可运行 Java 程序。复制粘贴到 IDE,调整路径后运行。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +运行后打开生成的 PDF,你将得到一个干净、可访问的文件,随时可以分发。 + +## 结论 + +我们已经演示了如何使用 Aspose.Words for Java **save document as pdf**,同时自动 **add accessibility to pdf** 并 **tag horizontal rules** 为 artifacts。关键要点: + +- 使用 `PdfSaveOptions` 并将合规级别设为 `PDF_UA_2`,即可满足可访问性标准。 +- 加载 DOCX 并调用 `doc.save(..., pdfOptions)` 就能完成 **convert docx to pdf**。 +- 水平线已自动处理——无需额外代码,即满足 **tag horizontal rules** 的要求。 +- 该方案完全 **aspose convert docx pdf** 合规,适用于最新库版本,并生成可通过验证的 PDF。 + +准备好迎接下一个挑战了吗?尝试添加自定义元数据、嵌入字体,或批量处理整个 DOCX 文件夹。所有这些扩展都基于我们在此奠定的相同基础。 + +如果对 PDF/UA 合规、许可证或其他 Word 元素的处理有疑问,欢迎留言或查阅 Aspose 官方文档——那里有大量示例可供参考。祝编码愉快,尽情创建可访问的 PDF 吧! + +![使用 Aspose.Words Java 将文档保存为 PDF – 可访问 PDF 示例](placeholder-image.png "使用 Aspose.Words Java 将文档保存为 PDF – 可访问 PDF 示例") + +## 相关教程 + +- [如何使用 Aspose.Words for Java 将文档保存为 PDF](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [如何使用 Aspose.Words for Java 将 Word 转换为 PDF](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – 在 Java 中将 DOCX 转换为 PDF](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/chinese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..525f21fa9e --- /dev/null +++ b/words/chinese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-26 +description: 将 Word 保存为 Markdown,并了解如何使用 Aspose.Words for Java 将数学公式导出为 LaTeX。只需几行代码即可将 + Word 公式转换为 LaTeX。 +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: zh +og_description: 将 Word 保存为 Markdown,并学习如何使用 Aspose.Words for Java 将数学公式导出为 LaTeX。完整可运行的指南。 +og_title: 将 Word 保存为 Markdown – 使用 Java 导出数学为 LaTeX +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: 将 Word 保存为 Markdown – 用 Java 导出数学为 LaTeX +url: /zh/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 Word 保存为 Markdown – 使用 Java 导出数学为 LaTeX + +是否曾经需要**将 Word 保存为 Markdown**,但担心你的公式会变成一团乱码?你并不孤单。在本指南中,我们将演示如何**导出数学**,直接将 `.docx` 文件中的公式转换为 LaTeX,而文档的其余部分则转换为干净的 Markdown。 + +我们将涵盖从设置 Aspose.Words 库到验证最终的 `out.md` 文件的全部内容。完成后,你将能够通过一次方法调用**将 Word 公式转换为 LaTeX**,并了解使转换可靠的细微差别。 + +--- + +## 你需要的环境 + +- **Java 8+** – 代码可在任何近期的 JDK 上运行。 +- **Aspose.Words for Java** – 可以使用 Maven/Gradle 依赖,也可以手动使用 JAR。 +- 一个包含至少一个 Office Math 公式的 Word 文档(`math.docx`)。 +- 一个 IDE 或者普通的 `javac`/`java` 命令行——随你喜欢的方式。 + +如果你已经具备这些,那太好了。如果没有,下一节将详细说明如何将库引入项目。 + +--- + +## 将 Word 保存为 Markdown – 步骤 1:将 Aspose.Words 添加到项目中 + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **小技巧:** Aspose 提供免费临时许可证用于测试。将 `license.xml` 文件放入 resources 文件夹,并在加载任何文档之前调用 `License license = new License(); license.setLicense("license.xml");`。 + +依赖解析完成后,你就可以编写转换代码了。 + +--- + +## 如何将数学公式导出为 LaTeX + +繁重的工作由 `MarkdownSaveOptions` 完成。将其 `OfficeMathExportMode` 切换为 `LATEX`,即可将每个 Office Math 对象渲染为 Markdown 输出中的 LaTeX 片段。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### 为什么这样可行 + +- **`Document`** 是 Aspose 的入口点;它抽象化 `.docx` 文件,提供对每个节点(包括公式)的访问。 +- **`MarkdownSaveOptions`** 告诉库*如何*输出。默认行为是将公式渲染为图片,这违背了基于文本的格式目的。 +- **`OfficeMathExportMode.LATEX`** 强制引擎将每个 `OfficeMath` 节点转换为其对应的 LaTeX 形式,Markdown 解析器(如 GitHub 或 Jekyll)在配合 MathJax 插件时即可渲染。 + +--- + +## 将 Word 公式转换为 LaTeX – 步骤 2:验证 Markdown 输出 + +运行程序后,打开 `out.md`。你应该会看到类似如下内容: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **注意:** LaTeX 片段使用 `$…$` 包裹用于行内数学,使用 `$$…$$` 包裹用于块级数学。这是大多数静态站点生成器在启用 MathJax 时能够识别的标准语法。 + +如果你希望公式仅保持行内形式,可以进一步调整 `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx 转 Markdown LaTeX – 步骤 3:边缘情况与常见陷阱 + +| 情况 | 需要注意的点 | 解决方案 | +|-----------|-------------------|-----| +| **复杂的嵌套公式** | Aspose 可能会输出额外的 `{}`,而某些解析器会将其字面解释。 | 使用简单的正则后处理 Markdown,将 `{{` 合并为 `{`。 | +| **目标站点缺少 MathJax** | 公式显示为原始 LaTeX 代码。 | 在 HTML 模板中添加 ``。 | +| **大型文档** | 因为一次性加载整个文档,内存消耗会激增。 | 使用 `LoadOptions.setLoadFormat(LoadFormat.DOCX)`,如果出现 `OutOfMemoryError`,考虑分批处理页面。 | +| **未设置许可证** | 会收到警告,且输出可能带有水印。 | 如上面的 Maven 小技巧所示,在 `main` 中尽早加载许可证。 | + +--- + +## 将 Word 保存为 Markdown – 完整工作示例 + +下面是一个独立的类,你可以复制粘贴到任何 Java 项目中。只需将 `YOUR_DIRECTORY` 替换为你的文件路径即可。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +运行程序(`java MathToLatexMarkdown`),你会在控制台看到成功的提示信息。用任意编辑器打开 `out.md`——公式应为干净的 LaTeX 代码片段,已准备好渲染。 + +--- + +## 预期输出快照 + +![保存 Word 为 Markdown 输出(含 LaTeX 公式)](https://example.com/images/markdown-latex-output.png "保存 Word 为 Markdown 输出(含 LaTeX 公式)") + +*该图片展示了生成的 Markdown 片段,其中公式 `\int_{a}^{b} f(x)\,dx` 被 `$$` 包裹。* + +--- + +## 结论 + +我们刚刚演示了如何**将 Word 保存为 Markdown**,同时将每个 Office Math 公式保留为原生 LaTeX。关键步骤是使用 `OfficeMathExportMode.LATEX` 配置 `MarkdownSaveOptions`,这使得典型的 Word 到 Markdown 流程转变为完整的数学感知转换工具。 + +现在你可以: + +1. **从任何 `.docx` 导出数学**,且不失真。 +2. **将 Word 公式转换为 LaTeX**,用于静态站点生成器、文档或学术博客。 +3. 扩展此方法以批量处理多个文件、集成到 CI 流水线,甚至构建小型 Web 服务。 + +如果你对下一步感兴趣,可以尝试将其与**docx 转 markdown latex**结合,用于图像密集的文档,或探索 Aspose 的 `HtmlSaveOptions` 以获得适合网页的 HTML 版本。可能性无限——大胆实验、突破局限,然后与社区分享你的发现。 + +有问题或遇到未如预期渲染的复杂公式?在下方留言吧,祝编码愉快! + +## 相关教程 + +- [如何从 Word 导出 LaTeX:将 DOCX 转换为 Markdown 并保存为 PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [将 docx 转换为 markdown – 使用 Aspose.Words 导出数学公式为 LaTeX](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [如何使用 Aspose.Words for Java 将 Word 转换为 PDF](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/chinese/java/document-loading-and-saving/_index.md index 9e81fd2de3..3a53e836ef 100644 --- a/words/chinese/java/document-loading-and-saving/_index.md +++ b/words/chinese/java/document-loading-and-saving/_index.md @@ -132,6 +132,9 @@ Aspose.Words for Java 让 **从 Word 文档中保存图像** 变得简单,同 ### [恢复损坏的 docx – 完整指南:修复和处理文档](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) 学习如何修复损坏的 docx 文件并进行后续处理,提供完整步骤和代码示例。 +### [打开损坏的 Word 文档 – 在 Java 中设置恢复模式](./open-corrupted-word-document-set-recovery-mode-in-java/) +了解如何在 Java 中使用 Aspose.Words 设置恢复模式以打开损坏的 Word 文档。分步指南配有代码示例。 + ### [在 Java 中捕获字体替换警告 – Aspose.Words 完整指南](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## 常见问题 diff --git a/words/chinese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/chinese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..219b7dabe7 --- /dev/null +++ b/words/chinese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,189 @@ +--- +category: general +date: 2026-05-26 +description: 在 Java 中使用 Aspose.Words 打开损坏的 Word 文档。了解如何设置恢复模式并可靠地恢复损坏的 Word 文件。 +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: zh +og_description: 在 Java 中使用 Aspose.Words 打开损坏的 Word 文档。本指南展示了如何设置恢复模式并高效恢复损坏的 Word + 文件。 +og_title: 打开损坏的Word文档 – 在Java中设置恢复模式 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: 打开损坏的 Word 文档 – 在 Java 中设置恢复模式 +url: /zh/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 打开损坏的 Word 文档 – 在 Java 中设置恢复模式 + +是否曾尝试打开损坏的 Word 文档,却看到程序因异常而卡死?你并不孤单——这些破损的 .docx 文件真的让人头疼。好消息是 Aspose.Words for Java 提供了细粒度的控制,让你可以 **打开损坏的 word 文档** 而不会导致应用崩溃,甚至可以决定是显示警告、静默恢复,还是直接拒绝。 + +在本教程中,我们将完整演示整个过程:从创建合适的 `LoadOptions`,到选择合适的 **set recovery mode** 值,最后确认文档确实已加载。完成后,你将了解 **如何以编程方式恢复损坏的 word 文件**,无需手动复制粘贴。 + +> **你需要准备的内容** +> * Java 8 或更高版本(API 也兼容 Java 11) +> * Aspose.Words for Java 23.9(或最新版本) +> * 一个示例损坏的 .docx 文件——如果手头没有,可以将任意有效文件改名来模拟损坏 + +让我们开始吧。 + +## 打开损坏的 Word 文档 – 步骤概览 + +下面是我们将实现的高级流程: + +1. **创建 `LoadOptions`** – 该对象告诉 Aspose.Words 在遇到问题时该如何行为。 +2. **设置恢复模式** – 选择 `RECOVER_WITH_WARNINGS`、`RECOVER_WITHOUT_WARNINGS` 或 `REJECT_CORRUPTED`。 +3. **使用配置好的选项加载文档**。 +4. **验证** 加载是否成功(例如,打印页数)。 + +每一步都会详细说明,并附有可以直接复制粘贴到 IDE 的代码片段。 + +## 针对不同场景设置恢复模式 + +Aspose.Words 在 `LoadOptions.RecoveryMode` 中定义了三种恢复策略: + +| 模式 | 行为 | 何时使用 | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | 尝试加载文档,但将任何问题以警告形式输出到控制台。 | 想要看到 *出错原因* 而不终止加载时。 | +| `RECOVER_WITHOUT_WARNINGS` | 静默修复能够修复的部分,并抑制警告。 | 生产环境,需要保持日志整洁时。 | +| `REJECT_CORRUPTED` | 一旦检测到损坏立即抛出异常。 | 必须快速失败的严格校验流水线。 | + +正确选择模式就是 **set recovery mode** 的核心。在大多数调试会话中,`RECOVER_WITH_WARNINGS` 是最佳选择,因为它会明确指出哪些部分被修复。 + +## 使用 Aspose.Words 恢复损坏的 Word 文件 + +下面是一个 **完整、可运行的 Java 程序**,演示整个过程。将其放入 `RecoveryModeDemo.java` 文件,调整路径后直接运行即可。 + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### 每行代码的意义 + +* **`LoadOptions loadOptions = new LoadOptions();`** – 没有此对象时,Aspose.Words 使用默认恢复策略,默认会 *拒绝* 损坏的文件。创建它可以让你改变这种行为。 +* **`setRecoveryMode(...)`** – 这就是 **set recovery mode** 的调用,决定是显示警告、隐藏警告,还是抛出异常。 +* **`new Document(path, loadOptions);`** – 构造函数接受我们刚配置好的 `LoadOptions`,因此库能够从一开始就按指定方式处理损坏的文件。 +* **`doc.getPageCount()`** – 一个快速的合理性检查。如果文档成功加载并返回页数,说明你已经成功 **如何恢复损坏的 word 文件**。 +* **`doc.save(...)`** – 可选但实用;你可以将修复后的版本写回磁盘,以便后续使用。 + +## 处理常见的边缘情况 + +### 1. 文件未找到 + +如果路径错误,`Document` 会抛出 `FileNotFoundException`。将加载代码放在 try‑catch 块中,并记录友好的提示信息: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. 无法恢复的损坏 + +即使使用 `RECOVER_WITH_WARNINGS`,某些结构仍可能超出修复范围。此时 Aspose.Words 仍会加载能恢复的部分,但会在控制台显示类似 “Cannot read paragraph properties” 的警告。请注意这些输出;它们通常指向缺失的章节,需要手动重新构建。 + +### 3. 大文件与性能 + +恢复会带来少量额外开销,因为库会对文件进行两次解析——一次检测问题,一次重建。对于多 GB 的文档,建议使用流式读取或增大 JVM 堆内存 (`-Xmx2g`) 以避免 `OutOfMemoryError`。 + +## 专业技巧 – 让恢复更稳健 + +* **将警告记录到文件** – 将 `System.err` 重定向到日志记录器,便于留下修复痕迹。 +* **恢复后进行验证** – 调用 `doc.updatePageLayout();` 然后重新检查页数;有时在修复破损章节后布局会发生变化。 +* **批量自动恢复** – 将演示代码包装在循环中,处理一个文件夹中的所有损坏文件,并在每次循环中复用同一个 `LoadOptions` 实例。 + +## 结论 + +现在,你已经完全掌握了使用 Aspose.Words for Java **如何恢复损坏的 word 文件**。只需创建 `LoadOptions` 实例,**set recovery mode** 为符合场景的策略,然后使用该选项加载文档,即可安全 **打开损坏的 word 文档** 而不会导致应用崩溃。上面的示例代码是完整的、可直接运行的解决方案,能够打印页数并可选地保存清理后的副本。 + +接下来可以尝试将恢复模式切换为 `RECOVER_WITHOUT_WARNINGS`,比较控制台输出,或尝试加载加密文档(需要通过密码参数提供密码)。 + +## 相关教程 + +- [Aspose.Words Java:Word 文档处理完整指南](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [使用 Aspose.Words for Java 将 Word 转换为 PDF](/words/english/java/document-converting/using-document-converting/) +- [使用 Aspose.Words for Java 比较两个 Word 文件](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/chinese/java/document-styling/_index.md index 85365c42ed..7d0595d25e 100644 --- a/words/chinese/java/document-styling/_index.md +++ b/words/chinese/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aspose.Words for Java 提供了强大的文档样式工具,帮助开发人员 学习如何使用 Aspose.Words for Java 添加水印并设置页面配置。包含源代码的全面指南。 ### [文档页眉和页脚样式](./document-header-footer-styling/) 在本详细指南中学习如何使用 Aspose.Words for Java 设置文档页眉和页脚的样式。指南包含分步说明和源代码。 +### [在 Aspose.Words for Java 中设置默认字体 – 完整指南](./set-default-font-settings-in-aspose-words-for-java-complete/) +学习如何在 Aspose.Words for Java 中设置默认字体,包括字体名称、大小和样式的完整示例,帮助统一文档外观。 {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/chinese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..6fb20a3fb9 --- /dev/null +++ b/words/chinese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: 在 Aspose.Words for Java 中设置默认字体,并学习如何仅用几行代码设置字体以及检测缺失的字体。 +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: zh +og_description: 在 Aspose.Words for Java 中设置默认字体,学习如何设置字体并快速可靠地检测缺失的字体。 +og_title: 在 Aspose.Words for Java 中设置默认字体设置 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: 在 Aspose.Words for Java 中设置默认字体设置 – 完整指南 +url: /zh/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Aspose.Words for Java 中设置默认字体设置 – 完整指南 + +有没有想过在使用 Aspose.Words for Java 加载 Word 文档时 **set default font settings**?你并不孤单。缺失的字形会把精美的报告变成乱码,而提前捕获这些字体替换警告可以节省数小时的调试时间。 + +在本教程中,我们将通过一个简洁的端到端示例,演示如何 **set default font settings**、如何以编程方式 **set font settings**,以及如何在布局崩溃之前可靠地 **detect missing fonts**。 + +--- + +## 您将学到 + +- 如何使用全新的 `FontSettings` 实例创建 `LoadOptions` 对象。 +- 如何附加一个警告监听器,以在文档加载期间 **detect missing fonts**。 +- 如何在加载 DOCX 文件时让监听器静默报告任何替换。 +- 在生产环境中自定义回退字体和处理边缘情况的技巧。 + +无需额外库,无需晦涩的配置文件——只需纯 Java 和 Aspose.Words。 + +--- + +## 前置条件 + +在开始之前,请确保您已经具备: + +1. **Aspose.Words for Java**(版本 23.10 或更高)已加入 classpath。 +2. Java 17(或更高)开发工具包——任何现代 JDK 都可以。 +3. 一个特意使用了您未安装的字体(例如 *“MissingFont.ttf”*)的 DOCX 文件。 + +如果缺少 Aspose JAR,请从官方 Maven 仓库获取: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +就这么简单——此演示不需要额外安装字体。 + +--- + +## 第一步:创建 LoadOptions 并 **Set Default Font Settings** + +我们首先需要一个干净的 `LoadOptions` 对象,用来告诉 Aspose 在遇到未知字体时的行为。通过调用 `setFontSettings(new FontSettings())`,我们 **set default font settings**,并从空的回退列表开始。 + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **为何重要:** +> 当您未显式配置字体时,Aspose 会回退到系统默认集合,这可能会掩盖缺失字体的问题。通过从全新的 `FontSettings` 实例开始,您可以完全控制哪些字体被视为有效。 + +--- + +## 第二步:附加警告监听器以 **Detect Missing Fonts** + +Aspose 会为每一次替换生成一个 `WarningInfo` 对象。监听 `WarningType.FONT_SUBSTITUTION`,即可在文档解析时 **detect missing fonts**。 + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **专业提示:** 监听器在加载文档的同一线程上运行,几乎没有性能损耗。如果需要稍后分析警告,可将它们推入 `List` 而不是直接打印。 + +--- + +## 第三步:使用已配置的选项加载文档 + +既然我们已经 **set font settings** 并准备好监听器,只需加载文件即可。任何缺失的字体都会立即触发回调。 + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +如果源文件引用了未安装的字体,您会看到类似以下的输出: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +该行明确指出缺失的字体以及使用的回退字体——非常适合日志记录或用户反馈。 + +--- + +## 第四步:继续正常处理(可选) + +此时文档已完整加载,您可以进行任意后续操作——编辑、转换为 PDF,或提取文本。警告监听器已经完成工作,无需额外检查。 + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **如果想要自定义回退字体怎么办?** +> 不必让 `FontSettings` 为空,您可以添加特定字体: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +现在,任何缺失的字形都会被替换为 *Times New Roman*——这是大多数西文文档的可靠选择。 + +--- + +## 可视化概览 + +![Diagram showing how to set default font settings in Aspose.Words for Java](image.png "Diagram of set default font settings flow") + +*Alt text: set default font settings in Aspose.Words for Java flowchart.* + +该图展示了从初始化 `LoadOptions`(我们 **set default font settings** 的位置)到附加警告监听器(用于 **detect missing fonts**)再到最终加载文档的整个流程。 + +--- + +## 常见陷阱及规避方法 + +| 陷阱 | 产生原因 | 解决方案 | +|------|----------|----------| +| **忘记调用 `setFontSettings`** | Aspose 使用系统默认,隐藏缺失字体。 | 始终创建新的 `FontSettings` 实例并分配给 `LoadOptions`。 | +| **监听器未触发** | 在加载文档后才添加监听器。 | 在调用 `new Document(...)` 之前 *先* 添加警告监听器。 | +| **路径拼写错误导致 `FileNotFoundException`** | 硬编码路径与操作系统大小写敏感不匹配。 | 使用 `Paths.get("...").toAbsolutePath()` 或从项目根目录配置相对路径。 | +| **大量缺失字体淹没日志** | 大文档可能生成数十条警告。 | 在打印前使用 `Set` 过滤重复或聚合消息。 | + +--- + +## 扩展方案 + +如果需要为整个应用 **set font settings**,可以考虑创建单例 `FontSettings` 并在所有 `LoadOptions` 中复用。这样可以保持一致的回退策略,避免重复创建对象。 + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +现在,代码库的任何位置只需调用 `FontConfig.getLoadOptions()`,即可立即受益于相同的 **set default font settings** 逻辑。 + +--- + +## 结论 + +我们已经完整覆盖了在 Aspose.Words for Java 中 **set default font settings**、以编程方式 **set font settings**,以及在破坏输出之前 **detect missing fonts** 的全部要点。完整、可运行的示例已在上述代码片段中提供,您可以直接粘贴到 IDE 中查看警告效果。 + +接下来可以尝试更换回退字体、实验不同的文档格式(DOC、RTF、HTML),或将警告收集器集成到监控仪表盘中。对 `FontSettings` 的深入使用会让您对生成的文档外观充满信心——没有意外,没有破碎的字形。 + +有疑问或遇到棘手的字体替换场景?在下方留言,我们一起讨论,祝编码愉快! + +## 相关教程 + +- [Set Font Fallback Settings](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/java/images-shapes/_index.md b/words/chinese/java/images-shapes/_index.md index b94fe2e0fb..c8e3e83f28 100644 --- a/words/chinese/java/images-shapes/_index.md +++ b/words/chinese/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aspose.Words Java 代码教程 ### [使用 Aspose.Words for Java 创建 Word 文档 – 添加带阴影效果的矩形形状](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) 演示如何在 Word 文档中使用 Aspose.Words for Java 添加带阴影效果的矩形形状。 +### [使用 Aspose.Words for Java 在 Word 文档中创建矩形形状 – 完整分步指南](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +本教程提供在 Java 环境下使用 Aspose.Words 为 Word 文档创建矩形形状的完整步骤和代码示例。 + ## 其他资源 - [Aspose.Words for Java 文档](https://reference.aspose.com/words/java/) diff --git a/words/chinese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/chinese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..59dd0a56bc --- /dev/null +++ b/words/chinese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-26 +description: 在 Java Word 文档中创建矩形形状并应用阴影效果。了解如何添加形状阴影、设置阴影距离并保存文件。 +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: zh +og_description: 在 Java Word 文档中创建矩形形状,应用阴影效果,添加形状阴影,并使用 Aspose.Words 设置阴影距离。 +og_title: 在 Java Word 文档中创建矩形形状 – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: 在 Java Word 文档中创建矩形形状 – 完整分步指南 +url: /zh/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Java Word 文档中创建矩形形状 – 完整分步指南 + +是否曾经需要在 Java Word 文档中 **创建矩形形状**,却不知从何入手?你并不孤单——许多开发者在以编程方式生成报告或发票时都会遇到这个难题。在本教程中,我们将逐步演示如何 **创建矩形形状**、应用精致的阴影,并微调阴影距离,使效果看起来专业。 + +我们将使用 Aspose.Words for Java,这是一款强大的库,能够在无需安装 Microsoft Office 的情况下操作 Word 文件。阅读完本指南后,你将能够在 **create word document java** 项目中 **add shape shadow**、**apply shadow effect**,以及 **set shadow distance**,只需几行代码。 + +--- + +## 你将构建的内容 + +- 一个包含青色矩形的全新 `.docx` 文件。 +- 一个真实感的投影阴影,具有模糊、倾斜和部分透明的效果。 +- 完全可控的阴影与形状之间的距离。 +- 一个可直接运行的 Java 类,可放入任意 Maven 或 Gradle 项目中。 + +无需外部工具,无需手动 UI 步骤——纯代码实现。 + +--- + +## 前置条件 + +- Java 8 或更高版本(代码在 Java 11、Java 17 等均可运行)。 +- Aspose.Words for Java 库(可通过 Maven Central 获取)。 +- 你喜欢的 IDE 或文本编辑器(IntelliJ IDEA、Eclipse、VS Code…)。 +- 对 Java 语法有基本了解。 + +如果你从未添加过 Maven 依赖,下面是一段快速示例: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +现在,开始动手吧。 + +--- + +## 第一步:在 Word 文档中创建矩形形状 + +首先需要一个空白文档和一个 `DocumentBuilder`。可以把 builder 看作是向文档写入内容的笔。有了它,就可以通过一次方法调用 **创建矩形形状**。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **为什么重要:** `insertShape` 方法不仅创建几何形状,还会将该形状添加到文档的内部集合中,因而可以立即对其进行样式设置。 + +--- + +## 第二步:为形状应用阴影效果 + +矩形已经出现在页面上后,我们将 **apply shadow effect**。阴影能够增加深度,让形状看起来像是从页面上方悬浮出来——这是一种细微的 UI 改进,能够提升报告的可读性。 + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **小技巧:** `5.0` 的模糊值在大多数屏幕显示的文档中看起来自然。如果是打印文档,可能需要稍低的数值,以免出现模糊感。 + +--- + +## 第三步:设置阴影距离 – 精细调节位置 + +阴影不仅仅是模糊,还需要合适的偏移。这就是我们 **set shadow distance** 的地方。`7.0` 点的距离会产生适度的偏移,既明显又不显得突兀。 + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **如果需要更大的偏移怎么办?** 增大该数值;想要更紧凑的效果则减小。记住,距离会与角度一起决定阴影的最终位置。 + +--- + +## 第四步:保存文档 – 持久化你的工作 + +最后,将文档写入磁盘。将路径改为你希望文件保存的位置即可。 + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +运行该类后会生成 `shadow.docx` 文件,使用 Microsoft Word 或 LibreOffice 打开时,可看到一个青色矩形,带有 45° 角、偏移 7 点的柔和灰色阴影。 + +--- + +## 完整可运行示例 + +下面是完整的、可直接复制粘贴的代码。包括所有 import、注释以及最终的 `save` 调用。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**预期输出:** 打开 `shadow.docx` → 你会看到第一页居中的青色矩形,投射出轻微偏移至右下角的灰色阴影。阴影的模糊度和透明度让它看起来像自然光照射的效果。 + +--- + +## 常见问题与边缘情况 + +### “可以使用其他形状吗?” + +当然可以。将 `ShapeType.RECTANGLE` 替换为 `ShapeType.OVAL`、`ShapeType.LINE` 或其他受支持的枚举。其余阴影代码保持不变。 + +### “如果需要多个阴影怎么办?” + +Aspose.Words 每个形状仅支持单个阴影。若想模拟多个阴影,可复制形状、分别偏移并调整透明度。 + +### “LibreOffice 能看到阴影吗?” + +能——Aspose.Words 会写入标准 OOXML,LibreOffice 能正确解析。由于渲染引擎不同,阴影外观可能略有差异,但效果仍然存在。 + +### “如何将阴影颜色改为品牌色?” + +只需将 `java.awt.Color.GRAY` 替换为任意 `java.awt.Color`,例如 `new java.awt.Color(0, 120, 215)` 用于企业蓝。 + +--- + +## 图片示例 + +![在 Java Word 文档中创建矩形形状](https://example.com/images/rectangle-shadow.png) + +*替代文字:* **create rectangle shape** 插图,展示了在 Word 文档中带有灰色投影的青色矩形。 + +--- + +## 小结与后续 + +我们已经学习了如何使用 Aspose.Words for Java **创建矩形形状**、**应用阴影效果**、**添加形状阴影**,以及 **设置阴影距离**。代码独立、可在任何现代 JDK 上运行,并生成可直接分发的精美 `.docx` 文件。 + +想进一步探索?可以尝试: + +- 使用 `builder.moveTo(rectangleShape.getAbsolutePosition())` 在矩形内部添加文本。 +- 创建形状表格以绘制流程图。 +- 将文档导出为 PDF(`doc.save("output.pdf", SaveFormat.PDF);`)。 + +这些操作都基于我们刚才掌握的基础,能够帮助你轻松扩展示例。 + +--- + +## 最后感想 + +掌握 **create word document java** 这类任务(如形状绘制与阴影处理),在自动化生成报告、合同或营销素材时会拥有巨大的优势。本文展示的方法简洁、易维护,且最重要的是——可以轻松根据任何视觉风格进行微调。 + +快去运行代码,调节模糊度、角度和距离,让你的文档从单调变得精致。如果遇到问题,欢迎在下方留言,我会乐意帮助。 + +祝编码愉快! + + +## 相关教程 + +- [创建 Word 文档 Java – 添加矩形形状并应用阴影效果](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [使用 Aspose.Words for Java 的 DocumentBuilder 创建表单字段并添加内容](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [使用 Aspose.Words for Java 从 Word 创建带条码的 PDF](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/czech/java/document-conversion-and-export/_index.md index 9f97aad568..fd4f7623b4 100644 --- a/words/czech/java/document-conversion-and-export/_index.md +++ b/words/czech/java/document-conversion-and-export/_index.md @@ -97,18 +97,33 @@ Naučte se formátovat tabulky a aplikovat styly tabulek v Aspose.Words for Java ### [Převod DOCX na Markdown – Export matematických rovnic do LaTeXu s Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Naučte se převést soubory DOCX na Markdown a exportovat rovnice do LaTeXu pomocí Aspose.Words. +### [Uložení Wordu jako Markdown – Export matematických rovnic do LaTeXu v Javě](./save-word-as-markdown-export-math-to-latex-with-java/) +Naučte se uložit dokument Word jako Markdown a exportovat rovnice do LaTeXu pomocí Aspose.Words for Java. + ### [Uložení dokumentu jako TXT – Rychlý průvodce exportem rovnic Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Naučte se, jak uložit dokument jako textový soubor TXT a exportovat matematické rovnice z Wordu pomocí Aspose.Words. +### [Export docx do txt pomocí Javy – Kompletní programovací průvodce](./export-docx-to-txt-with-java-complete-programming-guide/) +Naučte se, jak pomocí Aspose.Words for Java exportovat soubory DOCX do formátu TXT v několika krocích. + ### [Aspose Word na PDF – Převod DOCX do PDF v Javě](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Naučte se, jak pomocí Aspose.Words for Java převést soubory DOCX do PDF jedním jednoduchým kódem. ### [Jak vložit obrázky do Markdown při konverzi DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Naučte se, jak při konverzi DOCX do Markdown vložit obrázky tak, aby byly správně zobrazeny v cílovém souboru. +### [Vkládání obrázků jako Base64 při konverzi DOCX do Markdownu](./embed-images-as-base64-when-converting-docx-to-markdown/) +Naučte se, jak při převodu DOCX na Markdown vložit obrázky jako Base64 kód, aby se zobrazily přímo v Markdown souboru. + ### [Vytvořit přístupný PDF z DOCX – Kompletní průvodce](./create-accessible-pdf-from-docx-complete-guide/) Naučte se, jak pomocí Aspose.Words for Java převést DOCX na PDF s podporou přístupnosti a splnit standardy WCAG. +### [Uložit dokument jako PDF pomocí Aspose.Words pro Java – Kompletní průvodce přístupností](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Naučte se, jak vytvořit PDF s plnou přístupností (WCAG) pomocí Aspose.Words for Java, včetně nastavení značek a struktury dokumentu. + +### [Vytvořit přístupný PDF v Javě – Kompletní průvodce značkováním](./create-accessible-pdf-in-java-full-tagging-guide/) +Naučte se, jak pomocí Aspose.Words for Java vytvořit PDF s plným značkováním pro přístupnost podle WCAG. + ## Často kladené otázky **Q: Jak přidám vodoznak do existujícího PDF pomocí Aspose.Words?** diff --git a/words/czech/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/czech/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..ec9f393245 --- /dev/null +++ b/words/czech/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-05-26 +description: Vytvořte přístupný PDF v Javě pomocí krok‑za‑krokem kódu. Naučte se, + jak označit PDF pro přístupnost a povolit označování PDF pomocí PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: cs +og_description: Vytvořte přístupný PDF v Javě pomocí krok‑za‑krokem kódu. Naučte se, + jak označit PDF pro přístupnost a povolit označování PDF pomocí PdfSaveOptions. +og_title: Vytvořte přístupný PDF v Javě – Kompletní průvodce značkováním +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Vytvořte přístupný PDF v Javě – Kompletní průvodce značkováním +url: /cs/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření přístupného PDF v Javě – Kompletní průvodce značkováním + +Už jste se někdy ptali, jak **vytvořit přístupné PDF** soubory přímo z Java kódu? Nejste v tom sami. Mnoho vývojářů potřebuje obsluhovat uživatele, kteří spoléhají na čtečky obrazovky, a rozdíl mezi obyčejným PDF a přístupným může být obrovský. V tomto tutoriálu vás provedeme **značením PDF pro přístupnost**, ukážeme vám **jak vytvořit označené PDF** pomocí Aspose PDF for Java a odhalíme přesné kroky k **přidání značek přístupnosti do PDF**, aby každý čtenář získal stejné informace. + +Také se podíváme na nejlepší postupy pro **povolení značkování PDF**, běžné úskalí a kompletní, spustitelný příklad, který můžete dnes vložit do svého projektu. Žádné vágní odkazy – jen konkrétní kód, vysvětlení a finální soubor, který můžete otevřít v Adobe Acrobat a ověřit značky. + +## Co se naučíte + +- Proč stojí za značkování PDF a shodu s požadavky na přístupnost. +- Požadavky a nastavení knihovny (Aspose PDF for Java 23.10 nebo novější). +- Jak **vytvořit přístupné PDF** od nuly, krok po kroku. +- Způsoby, jak **přidat značky přístupnosti do PDF** nad rámec základního volání `setTagDocumentStructure`. +- Tipy na testování výstupu a řešení běžných problémů. + +Na konci tohoto průvodce budete schopni generovat PDF, která projdou kontrolou WCAG 2.1 AA a zároveň budou vypadat profesionálně. + +--- + +## Požadavky + +Než se ponoříme, ujistěte se, že máte: + +| Požadavek | Důvod | +|-------------|--------| +| **Java 8+** | Moderní jazykové funkce a lepší zpracování Unicode. | +| **Aspose PDF for Java** (v23.10 nebo novější) | Poskytuje třídu `PdfSaveOptions` a podporu značkování. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, atd.) | Pro snadnou kompilaci a ladění. | +| **Write permission** to a folder where the PDF will be saved | Volání `doc.save` potřebuje zapisovatelnou cestu. | + +Pokud jste ještě nepřidali Aspose PDF do svého projektu, vložte následující Maven závislost do souboru `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Tip:** Používejte nejnovější verzi; novější vydání zlepšují přesnost značkování a přidávají jazykově specifické funkce přístupnosti. + +## Krok 1: Nastavení kostry dokumentu + +Nejprve vytvoříme nový objekt `Document`. Představte si jej jako prázdné plátno, které později bude obsahovat značky potřebné pro přístupnost. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Proč je to důležité:** Bez jakéhokoli obsahu není co značkovat. Přidání i jednoduchého `TextFragment` poskytne značkovacímu enginu něco, s čím může pracovat, a automaticky vytvoří značku `

` (odstavec), když později povolíme strukturové značkování. + +## Krok 2: Vytvoření možností uložení PDF (jádro značkování) + +Nyní připravíme možnosti, které řeknou Aspose PDF, aby do souboru vložil logický strom struktury. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Volání `setTagDocumentStructure(true)` je přepínač **povolení značkování PDF**. Když je nastaveno na true, knihovna vytvoří strom značek, který odráží vizuální rozložení, což umožní čtení PDF asistenčními technologiemi. + +> **Poznámka:** Toto je nejjednodušší způsob, jak **vytvořit označené pdf**. Pro podrobnější kontrolu (např. nastavení jazyka nebo vlastních značek) můžete prozkoumat `pdfOptions.setTagLanguage("en-US")` a `pdfOptions.setTagStructureTreeRoot(...)`. + +## Krok 3: Uložení přístupného PDF + +Nakonec zapíšeme dokument na disk pomocí právě nakonfigurovaných možností. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Po dokončení `doc.save` najdete `accessible.pdf` ve složce `output`. Otevřete jej v Adobe Acrobat a podívejte se na **File → Properties → Description → Tags** – měli byste vidět vyplněný strom značek. + +## Jak značkovat PDF pro přístupnost – nad rámec základů + +Výše uvedený tříkrokový úryvek již **přidává značky přístupnosti do PDF**, ale dokumenty v reálném světě často potřebují trochu víc vylepšení. Zde je několik vylepšení, která můžete přidat: + +### 1. Nastavení jazyka dokumentu + +Čtečky obrazovky používají atribut jazyka k správnému vyslovení textu. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Poskytnutí názvu a předmětu + +Metadata pomáhají asistenčním nástrojům poskytnout kontext ještě před otevřením souboru uživatelem. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Označení obrázků alternativním textem + +Pokud vkládáte obrázky, potřebují popisy `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Označení záhlaví tabulky + +Tabulky jsou notoricky matoucí pro čtenáře, pokud neoznačíte řádky záhlaví. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Tato další kroky učiní vaše PDF nejen *technicky* označené, ale skutečně **přístupné** pro různorodé publikum. + +## Běžné úskalí při povolení značkování PDF + +| Příznak | Předpokládaná příčina | Řešení | +|---------|-----------------------|--------| +| Chybějící značky v Acrobat | `setTagDocumentStructure` left as `false` | Ujistěte se, že voláte `pdfOptions.setTagDocumentStructure(true)`. | +| Špatné pořadí čtení | Komplexní rozložení bez explicitních značek | Použijte `pdfOptions.setTagStructureTreeRoot(...)` k definování vlastního pořadí. | +| Obrázky jsou čteny jako „image“ bez popisu | Není nastaven alternativní text | Zavolejte `image.getAlternativeText().setValue("...")`. | +| Jazyk není rozpoznán | `setTagLanguage` omitted or wrong locale | Poskytněte kód jazyka BCP‑47 (`en-US`, `fr-FR`). | + +Být si těchto problémů vědom vám ušetří hodiny ladění později. + +## Ověření výsledku – Co očekávat + +Po spuštění programu otevřete `output/accessible.pdf` v Adobe Acrobat Reader: + +1. **Panel značek** (`View → Show/Hide → Navigation Panes → Tags`) by měl zobrazovat hierarchii jako `/Document → /Part → /Sect → /Para`. +2. **Pořadí čtení** by mělo následovat vizuální tok (nejprve text, pak obrázky). +3. **Čtečka obrazovky** (NVDA, VoiceOver) přečte „Hello, accessible PDF!“ místo pouhého „Page 1“. + +Pokud některá z těchto položek chybí, zkontrolujte znovu výše uvedené kroky – zejména volání `setTagDocumentStructure`. + +## Kompletní funkční příklad (připravený ke zkopírování) + + + +## Související tutoriály + +- [Vytvořit přístupné PDF z Wordu – převod na PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Vytvořit přístupné PDF z DOCX – kompletní průvodce](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Jak uložit dokument jako PDF pomocí Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/czech/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/czech/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..cacb2031db --- /dev/null +++ b/words/czech/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Vkládejte obrázky jako base64 při převodu docx na markdown pomocí Aspose.Words + pro Java. Naučte se převádět Word na markdown, ukládat Word jako markdown a pracovat + s obrázky. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: cs +og_description: Vkládejte obrázky jako base64 při převodu docx na markdown pomocí + Aspose.Words pro Java. Kompletní průvodce převodem Wordu na markdown a uložením + Wordu jako markdown. +og_title: Vkládejte obrázky jako Base64 při převodu DOCX na Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Vkládejte obrázky jako Base64 při převodu DOCX na Markdown +url: /cs/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vkládání obrázků jako Base64 při převodu DOCX na Markdown + +Už jste se někdy zamysleli, jak **vložit obrázky jako base64** při **převodu docx na markdown**? Nejste jediní – vývojáři se neustále ptají, jak udržet obrázky vložené přímo v textu, aniž by museli spravovat samostatné soubory. Dobrou zprávou je, že Aspose.Words for Java to usnadňuje: můžete převést dokument Word na Markdown a automaticky vložit každý obrázek jako řetězec Base64. + +V tomto tutoriálu projdeme celý proces – od načtení `.docx`, který obsahuje obrázky, přes nastavení callbacku `MarkdownSaveOptions`, který udělá těžkou práci, až po uložení výsledku jako čistý soubor `.md`. Na konci budete přesně vědět, jak **convert word to markdown**, **convert images to base64** a **save word as markdown** bez zbylých složek s obrázky. Žádné externí nástroje, žádné ruční post‑processing – jen čistý Java kód, který můžete vložit do libovolného projektu. + +## Co budete potřebovat + +- **Java 17** (nebo jakýkoli novější JDK) – kód používá lambda syntaxi, ale můžete jej přizpůsobit i starším verzím. +- **Aspose.Words for Java** knihovna (nejnovější verze k roku 2026). Přidejte Maven závislost nebo JAR do classpath. +- Ukázkový **DOCX** soubor, který obsahuje alespoň jeden obrázek. +- IDE nebo jednoduchý textový editor – Visual Studio Code, IntelliJ IDEA nebo i `vim` vám postačí. + +Pokud už toto máte, skvělé – pojďme rovnou do toho. + +## Krok 1: Načtení Word dokumentu + +Nejprve vytvoříme instanci `Document`, která ukazuje na zdrojový soubor. Tento krok je stejný, ať už **convert docx to markdown** nebo jen čtete soubor pro jiné účely. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Proč je to důležité:** Objekt `Document` je vstupním bodem pro každou operaci Aspose. Obsahuje celou strukturu Wordu – včetně obrázků, tabulek a stylů – takže pozdější callback může prozkoumat každý zdroj. + +## Krok 2: Vytvoření MarkdownSaveOptions a registrace zpětného volání pro ukládání zdrojů + +Magie spočívá v `MarkdownSaveOptions`. Připojením `IResourceSavingCallback` získáme kontrolu nad tím, jak je každý externí zdroj (např. obrázek) zapisován. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Proč použít `setSaveToMemory(true)`? + +Když je `saveToMemory` nastaveno na true, Aspose zapíše bajty obrázku do paměťového proudu místo souboru. Exportér Markdownu pak tento proud převede na Base64 řetězec a vloží jej přímo do tagu obrázku v Markdownu: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +To je jádro **embed images as base64**. + +## Krok 3: Uložení dokumentu jako Markdown + +Nyní, když je callback nastaven, poslední krok je jednoduše zavolat `save`. Tím skutečně **convert word to markdown** a díky callbacku také **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Výsledek:** `out.md` obsahuje Markdown text, kde je každý obrázek reprezentován jako `data:` URI. Žádné další soubory s obrázky nejsou vytvořeny na disku, takže složka zůstává přehledná. + +## Krok 4: Ověření výstupu a běžné úskalí + +Otevřete vygenerovaný `out.md` v libovolném Markdown prohlížeči (VS Code, GitHub nebo statický generátor stránek). Měli byste vidět něco jako: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Kontrolní seznam řešení problémů + +| Problém | Pravděpodobná příčina | Řešení | +|-------|--------------|-----| +| Obrázek se zobrazuje jako poškozený odkaz | `setSaveToMemory` byl vynechán | Ujistěte se, že `args.setSaveToMemory(true);` je uvnitř callbacku | +| Base64 řetězec je oříznutý | Neshoda kódování výstupního souboru | Uložte Markdown pomocí UTF‑8 (výchozí pro Aspose) | +| Neočekávané názvy souborů | `setKeepResourceOriginalName(true)` | Nechte ho `false`, aby se vynutila vlastní logika pojmenování | + +## Krok 5: Pokročilé varianty (volitelné) + +### Převést pouze vybrané obrázky + +Pokud chcete vložit jen určité obrázky (např. ty větší než 100 KB), přidejte kontrolu velikosti: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Použít jiný formát obrázku + +`ResourceSavingArgs` vám poskytuje surové bajty, takže můžete před vložením pře‑enkódovat JPEGy na PNG – užitečné, když cílový Markdown spotřebič preferuje PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Tyto úpravy ukazují, jak flexibilní je přístup **embed images as base64**, když **convert docx to markdown**. + +## Závěr + +Právě jste se naučili, jak **embed images as base64** při **convert docx to markdown** pomocí Aspose.Words for Java. Připojením jednoduchého `IResourceSavingCallback` knihovna udělá veškerou těžkou práci: **convert word to markdown**, **convert images to base64** a nakonec **save word as markdown** jediným voláním `save`. + +Klidně experimentujte – vyzkoušejte různá pravidla filtrování obrázků, přepněte na HTML výstup nebo tento krok zkombinujte se statickým generátorem stránek. Stejný vzor funguje i pro jiné formáty (HTML, EPUB), takže můžete callback znovu použít kdekoliv potřebujete vložené zdroje. + +**Další kroky:** +- Prozkoumejte `HtmlSaveOptions` pro HTML s Base64 obrázky. +- Kombinujte to s CI pipeline pro automatizaci generování dokumentace. +- Ponořte se do Aspose `DocumentVisitor`, pokud potřebujete ještě jemnější kontrolu nad procesem převodu. + +Šťastné programování a užívejte si čisté, samostatné Markdown soubory! + +## Související tutoriály + +- [Jak vložit obrázky do Markdown při převodu DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Převod docx na markdown – Export matematických rovnic do LaTeXu s Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Uložení obrázků z Wordu – Průvodce Aspose.Words pro Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/czech/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..f71f31e51f --- /dev/null +++ b/words/czech/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-26 +description: Exportujte docx do txt pomocí Javy a Aspose.Words. Naučte se, jak převést + docx na text, zachovat Unicode a exportovat Word jako txt během několika kroků. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: cs +og_description: Export docx do txt v Javě. Tento tutoriál ukazuje, jak převést docx + na text, zachovat prostý text Unicode a efektivně exportovat Word jako txt. +og_title: Export docx do txt v Javě – Kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Export docx do txt v Javě – Kompletní programovací průvodce +url: /cs/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Export docx do txt pomocí Javy – Kompletní programovací průvodce + +Už jste někdy potřebovali **export docx to txt**, ale obávali se ztráty speciálních znaků? Nejste v tom sami. Když převádíte dokumenty Wordu na soubory plain‑text, mohou Unicode symboly, tabulky a dokonce i jednoduché formátování zmizet jako kouzlo. + +V tomto průvodci projdeme spolehlivý způsob, jak **export docx to txt** pomocí Aspose.Words for Java, zachovat každý Unicode znak a udržet rozvržení tabulek čitelné. Na konci také budete vědět, jak **convert docx to text**, **convert word to text**, a dokonce **export word as txt** bez problémů. + +## Co tento tutoriál pokrývá + +* Nastavení Aspose.Words v Java projektu +* Načtení souboru DOCX a příprava pro výstup plain‑text +* Konfigurace podpory **plain text unicode** pomocí `TxtSaveOptions` +* Volitelné triky pro zachování čitelnosti tabulek ve výsledném souboru `.txt` +* Uložení souboru a ověření výstupu + +Žádné externí skripty, žádné tajemné nástroje příkazové řádky – jen čistý Java kód, který můžete vložit do jakéhokoli Maven nebo Gradle projektu. + +> **Proč na tom záleží?** Plain‑text soubory jsou lehké, přátelské k verzovacím systémům a ideální pro vyhledávací indexování nebo downstream zpracovatelské pipeline. Pokud jste někdy zkusili `cat` Word soubor a dostali nesmysly, tento tutoriál řeší ten problém. + +## Export docx do txt – Přehled + +Než se ponoříme do kódu, vyjasněme terminologii. **Export docx to txt** znamená převzít balíček Microsoft Word `.docx` a zapsat jeho textový obsah do jednoduchého souboru `.txt`. Na rozdíl od konverze do PDF, export textu odstraní stylování, ale může zachovat zalomení řádků, značky odstavců a — pokud to správně nastavíte — Unicode znaky jako emoji, diakritické písmena nebo asijské skripty. + +Aspose.Words to usnadňuje, protože abstrahuje formát souboru Word a nabízí třídu `TxtSaveOptions`, kde můžete určit kódování, zacházení s tabulkami a další. + +### Požadavky + +* Java 11 nebo novější (API funguje s Java 8+, ale předpokládáme aktuální JDK) +* Aspose.Words for Java JAR (k dispozici v Maven Central) +* Ukázkový soubor `unicode.docx` obsahující různé Unicode znaky — např. “こんにちは”, “😊” a jednoduchou tabulku + +Pokud je máte, pojďme na to. + +## Krok 1: Načtení souboru DOCX (Convert docx to text) + +Prvním krokem je načíst zdrojový dokument do paměti. Zde oficiálně začíná proces **convert docx to text**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Proč je to důležité:* `Document` je reprezentace Word souboru v Aspose.Words. Načtením získáte přístup ke všem odstavcům, tabulkám a dokonce i skrytým prvkům. Pokud soubor není nalezen, Aspose vyhodí jasnou `FileNotFoundException`, takže okamžitě zjistíte, co se pokazilo. + +## Krok 2: Konfigurace TxtSaveOptions pro Unicode (Plain text unicode) + +Plain‑text soubory jsou jen proudy bajtů, takže musíte Jave říct, jakou znakovou sadu použít. UTF‑8 je de‑facto standard pro **plain text unicode**, protože dokáže zakódovat každý Unicode kódový bod. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Tip:** Pokud přeskočíte volání `setEncoding`, Aspose použije výchozí znakovou sadu platformy, která na mnoha Windows strojích je Windows‑1252. Toto výchozí nastavení tiše odstraní znaky jako “ß” nebo “—”. + +## Krok 3: Zachování rozvržení tabulky (Volitelné, ale užitečné pro čitelnost) + +Když **export word as txt**, tabulky se obvykle rozplývají do jedné řádky textu, což je nečitelný. Aspose.Words nabízí jednoduchý příznak pro zachování vizuální struktury. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Kdy to použít:* Pokud váš zdrojový DOCX obsahuje faktury, rozvrhy nebo jakákoli data ve formě mřížky, povolení `PreserveTableLayout` vloží tabulátory a zalomení řádků, takže výsledný soubor stále připomíná tabulku. Pokud to nepotřebujete, můžete řádek vynechat a získat kompaktnější výstup. + +## Krok 4: Uložení dokumentu jako plain‑text (Export word as txt) + +Nyní je těžká část hotová — stačí zapsat bajty na disk. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Spuštěním programu vznikne `plain.txt` ve stejné složce. Otevřete jej v libovolném textovém editoru (Notepad++, VS Code, dokonce `cat` v terminálu) a uvidíte: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Všimněte si, že japonské pozdravy a smajlík přežily a tabulka si zachovala sloupce díky `PreserveTableLayout`. To je podstata čistého **export docx to txt**. + +## Krok 5: Ověření výstupu (Convert word to text kontrola) + +Rychlá kontrola zabraňuje tichému ztrátě dat. Zde je několik způsobů, jak potvrdit, že skutečně **convert word to text** správně: + +1. **Porovnání kontrolního součtu** – vypočítejte SHA‑256 hash souboru `.txt` před a po konverzi tam‑zpět (txt → docx → txt), aby byla zajištěna stabilita. +2. **Vyhledání Unicode značek** – použijte `grep` nebo funkci hledání v IDE k nalezení znaků jako “😊”. +3. **Otevření v několika editorech** – některé staré verze Windows Notepadu stále špatně interpretují UTF‑8 bez BOM; otevření souboru ve VS Code potvrdí správné kódování. + +Pokud některá z těchto kontrol selže, dvojitě zkontrolujte, že je přítomno `saveOptions.setEncoding(StandardCharsets.UTF_8)` a že váš zdrojový DOCX skutečně obsahuje Unicode text. + +## Časté problémy a jak se jim vyhnout + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Chybějící znaky** | Výchozí systémová znaková sada (např. Windows‑1252) odstraňuje ne‑ASCII znaky. | Explicitně nastavte UTF‑8 pomocí `saveOptions.setEncoding`. | +| **Tabulky se stanou jednou řádkou** | `PreserveTableLayout` zůstane na výchozím `false`. | Zavolejte `saveOptions.setPreserveTableLayout(true)`. | +| **Soubor nenalezen** | Špatná cesta nebo chybějící oprávnění ke čtení. | Použijte absolutní cesty nebo `Paths.get(...)` s řádnou ošetřením výjimek. | +| **Zpomalení výkonu u velkých dokumentů** | Načítání celého dokumentu do paměti. | Streamujte dokument po částech pomocí `DocumentBuilder`, pokud potřebujete jen konkrétní sekce. | + +## Bonus: Export více DOCX souborů najednou + +Pokud potřebujete **convert docx to text** pro celou složku, zabalte logiku do smyčky: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Tento úryvek **export docx to txt** pro každý soubor v adresáři, ušetří vám hodiny ruční práce. + +## Závěr + +Právě jste se naučili, jak **export docx to txt** pomocí Javy, zajistit, že každý Unicode znak zůstane zachován, tabulky zůstanou čitelné a celý proces je opakovatelný. Konfigurací `TxtSaveOptions` pro UTF‑8 a volitelným zachováním rozvržení tabulek můžete spolehlivě **convert docx to text**, **convert word to text** a **export word as txt** pro jakýkoli downstream workflow. + +Jste připraveni na další výzvu? Zkuste export do jiných plain‑text formátů, jako je markdown (`.md`) nebo CSV, nebo prozkoumejte možnosti PDF konverze v Aspose.Words. Stejné principy — explicitní kódování, zachování rozvržení a důkladná verifikace — platí všude. + +Šťastné programování a ať vaše textové soubory vždy zůstávají bohaté na Unicode! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + +## Související tutoriály + +- [Převést Docx na Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Převést DOCX na PDF v Javě](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Převést docx na markdown – Export matematických rovnic do LaTeXu s Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/czech/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..8268ee447d --- /dev/null +++ b/words/czech/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Uložte dokument jako PDF pomocí Aspose.Words Java a přidejte přístupnost + do PDF. Naučte se převádět docx na PDF, označovat vodorovné čáry a zajistit soulad + s PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: cs +og_description: Uložte dokument jako PDF pomocí Aspose.Words Java a přidejte přístupnost + do PDF. Podrobný návod krok za krokem, jak převést docx na PDF a označit vodorovné + čáry pro soulad s PDF/UA‑2. +og_title: Uložte dokument jako PDF s Aspose.Words Java – Přístupnost snadno +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Uložte dokument jako PDF pomocí Aspose.Words Java – Kompletní průvodce přístupností +url: /cs/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< 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 Java – Kompletní průvodce přístupností + +Už jste se někdy zamýšleli, jak **uložit dokument jako PDF** a zároveň zachovat přístupnost pro čtečky obrazovky? Nejste v tom sami. Mnoho vývojářů potřebuje *convert docx to pdf* a zároveň splnit standardy PDF/UA‑2, zejména když zdroj obsahuje vodorovné čáry, které musí být správně označeny. V tomto tutoriálu vás provedeme přesné kroky k **uložení dokumentu jako PDF** pomocí Aspose.Words pro Java, automatickému **přidání přístupnosti do PDF** a zajištění, že každá vodorovná čára je **označena** jako artefakt. + +Začneme čistým projektem v Javě, načteme DOCX, který již obsahuje vodorovné čáry, nakonfigurujeme možnosti uložení PDF pro shodu s PDF/UA‑2 a nakonec vytvoříme plně přístupné PDF. Na konci budete schopni **uložit dokument jako pdf** s jistotou, že projde kontrolou přístupnosti. + +## Požadavky + +Než se pustíme do práce, ujistěte se, že máte: + +- Java 8 nebo novější (tutorial byl testován na JDK 17). +- Maven 3.6+ (nebo Gradle, pokud dáváte přednost) pro správu závislostí. +- Platnou licenci Aspose.Words pro Java (zkušební verze funguje, ale licence odstraňuje vodotisk hodnocení). +- Soubor DOCX (`input.docx`) obsahující alespoň jednu vodorovnou čáru – například jednoduchý oddělovač, který byste vložili ve Wordu. + +> **Pro tip:** Pokud nemáte DOCX po ruce, stačí vytvořit nový dokument Word, napsat několik odstavců, vložit *Insert → Horizontal Line*, uložit jako `input.docx` a umístit jej do libovolné složky. + +## Krok 1: Nastavení Maven projektu + +Nejprve vytvořte nový Maven projekt (nebo jej přidejte k existujícímu). `pom.xml` potřebuje závislost Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Proč je to důležité:** Přidání artefaktu `aspose-words` je první krok k *convert docx to pdf*. Bez něj kompilátor nepozná třídy `Document`, `PdfSaveOptions` a další klíčové třídy. + +## Krok 2: Načtení zdrojového DOCX obsahujícího vodorovné čáry + +Nyní napíšeme malou třídu v Javě, která načte DOCX. Zde začíná část **tag horizontal rules** – Aspose.Words automaticky zachází s vodorovnou čárou jako s odstavcem s okrajem, ale necháme engine PDF/UA provést označování. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Všimněte si, že zatím nic neukládáme – jen **načítáme** DOCX, což je první polovina *convert docx to pdf*. Objekt `Document` nyní obsahuje veškerý obsah Wordu, včetně všech vložených vodorovných čar. + +## Krok 3: Konfigurace možností uložení PDF pro shodu s PDF/UA‑2 + +Magie **adding accessibility to PDF** spočívá v `PdfSaveOptions`. Nastavením úrovně shody na `PDF_UA_2` Aspose.Words provede: + +1. Označení strukturálních prvků (nadpisy, tabulky atd.). +2. Označení dekorativních prvků – jako jsou vodorovné čáry – jako *artefakty*, takže je čtečky obrazovky ignorují. +3. Vložení potřebných metadat PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Proč nastavit shodu?** Bez `PDF_UA_2` může být výsledné PDF čitelné, ale neprojde automatickými validátory přístupnosti. Požadavek **tag horizontal rules** je automaticky splněn, protože PDF/UA je při zapnutém příznaku považuje za *artefakty*. + +## Krok 4: Uložení dokumentu jako PDF + +Nyní konečně **uložíme dokument jako pdf**. Tento jediný řádek provede těžkou práci – konverzi DOCX, aplikaci značek přístupnosti a zápis souboru na disk. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Spusťte třídu (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) a uvidíte potvrzovací zprávu. Otevřete vzniklý `ua_compliant.pdf` v Adobe Acrobat a zkontrolujte **File → Properties → Description → PDF/A, PDF/UA** – mělo by se zobrazit “PDF/UA‑2”. + +### Očekávaný výstup + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Otevřete PDF a všimnete si: + +- Text dokumentu je možné vybrat a vyhledávat. +- Vodorovná čára je neviditelná pro čtečky obrazovky (označena jako artefakt). +- PDF projde základními nástroji pro validaci PDF/UA (např. PAC 3). + +## Krok 5: Ověření přístupnosti – Rychlý kontrolní seznam + +I když Aspose.Words udělá většinu práce, je dobré výstup ověřit. + +| Kontrola | Jak ověřit | +|----------|------------| +| **Název dokumentu** | Otevřete Acrobat → File → Properties → Title (mělo by odpovídat `pdfOptions.setTitle`). | +| **Označení artefaktu** | Použijte nástroj “Reading Order” v Acrobat. Vodorovné čáry by se měly zobrazit jako *Artifact* (šedě). | +| **Logický pořadí čtení** | Spusťte “Accessibility Checker” v Acrobat; ujistěte se, že neexistují strukturální chyby. | +| **Označené PDF** | V Acrobat podívejte se do panelu “Tags” – měla by být hierarchie (Document → Section → Paragraph atd.). | +| **Shoda s PDF/UA** | Acrobat zobrazí “PDF/UA‑2” na kartě “Standards”. | + +Pokud některá z těchto kontrol selže, zkontrolujte, že používáte nejnovější verzi Aspose.Words a že `setCompliance(PdfCompliance.PDF_UA_2)` je správně nastaveno. + +## Časté problémy a jak se jim vyhnout + +1. **Chybějící licence** – Zkušební verze přidává vodotisk, který může narušit validaci PDF/UA. Licenci aplikujte hned v `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Nesprávná cesta k vstupu** – `FileNotFoundException` zastaví konverzi. Používejte absolutní cesty nebo umístěte DOCX do kořene projektu a odkažte na něj pomocí `new File("input.docx").getAbsolutePath()`. +3. **Starší verze Aspose** – Podpora PDF/UA byla přidána ve verzi 22.9. Aktualizujte na nejnovější vydání, abyste předešli chybějícím funkcím. +4. **Vodorovná čára jako obrázek** – Pokud jste čáru vložili jako obrázek místo nativní vodorovné čáry Wordu, Aspose ji bude považovat za běžný obrázek, nikoli artefakt. Nahraďte obrázek vestavěnou funkcí *Horizontal Line* pro správné označení. + +## Rozšíření řešení – Co když potřebujete více? + +- **Vlastní značky**: Pokud máte další dekorativní prvky (např. ikony), můžete je ručně označit jako artefakty pomocí `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Více dokumentů**: Procházejte složku s DOCX soubory a hromadně je převádějte, přičemž pro výkon znovu použijte stejnou instanci `PdfSaveOptions`. +- **Přidání jazykové značky**: Pro vícejazyčná PDF nastavte `pdfOptions.setLanguage("en-US")`, aby asistivní technologie věděly, jaký hlas použít. + +## Kompletní funkční příklad (všechen kód dohromady) + +Níže je kompletní, spustitelný program v Javě. Zkopírujte jej do svého IDE, upravte cesty a spusťte. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Spusťte jej, otevřete vygenerované PDF a získáte čistý, přístupný soubor připravený k distribuci. + +## Závěr + +Ukázali jsme, jak **uložit dokument jako pdf** pomocí Aspose.Words pro Java a zároveň automaticky **add accessibility to pdf** a **tag horizontal rules** jako artefakty. Klíčové poznatky: + +- Použijte `PdfSaveOptions` s úrovní shody `PDF_UA_2` pro splnění standardů přístupnosti. +- Načtení DOCX a volání `doc.save(..., pdfOptions)` je vše, co potřebujete k **convert docx to pdf**. +- Vodorovné čáry jsou zpracovány automaticky – není potřeba další kód, čímž se splňuje požadavek **tag horizontal rules**. +- Přístupnost je plně **aspose convert docx pdf** kompatibilní, funguje s nejnovější verzí knihovny a produkuje PDF připravené k validaci. + +Jste připraveni na další výzvu? Zkuste přidat vlastní metadata, vložit fonty nebo hromadně zpracovat celou složku DOCX souborů. Každé z těchto rozšíření staví na stejném základu, který jsme zde vytvořili. + +Máte otázky ohledně shody s PDF/UA, licencování nebo zpracování dalších Word elementů? Zanechte komentář nebo se podívejte do oficiální dokumentace Aspose – najdete tam spoustu příkladů. Šťastné programování a užívejte si tvorbu přístupných PDF! + +![save document as pdf using Aspose.Words Java – accessible PDF example](placeholder-image.png "save document as pdf using Aspose.Words Java") + +## Související tutoriály + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/czech/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..fe352d0f9f --- /dev/null +++ b/words/czech/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Uložte Word jako markdown a objevte, jak exportovat matematické rovnice + do LaTeXu pomocí Aspose.Words pro Javu. Převádějte rovnice Wordu do LaTeXu během + několika řádků. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: cs +og_description: Uložte soubor Word jako markdown a naučte se, jak exportovat matematické + rovnice do LaTeXu pomocí Aspose.Words pro Javu. Kompletní, spustitelný návod. +og_title: Uložit Word jako markdown – Exportovat matematiku do LaTeXu pomocí Javy +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Uložit Word jako markdown – Exportovat matematiku do LaTeXu pomocí Javy +url: /cs/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Uložte Word jako markdown – Exportujte matematiku do LaTeXu pomocí Javy + +Už jste někdy potřebovali **uložit Word jako markdown**, ale obávali jste se, že se vaše rovnice změní v nečitelný chaos? Nejste v tom sami. V tomto průvodci si ukážeme **jak exportovat matematiku** z `.docx` souboru přímo do LaTeXu, zatímco zbytek dokumentu se stane čistým Markdownem. + +Probereme vše od nastavení knihovny Aspose.Words až po ověření výsledného souboru `out.md`. Na konci budete schopni **převést rovnice z Wordu do LaTeXu** jedním voláním metody a pochopíte drobné nuance, které dělají převod spolehlivým. + +--- + +## Co budete potřebovat + +- **Java 8+** – kód běží na jakémkoli aktuálním JDK. +- **Aspose.Words for Java** – buď jako Maven/Gradle závislost, nebo JAR, pokud dáváte přednost ručnímu nastavení. +- Wordový dokument (`math.docx`) obsahující alespoň jednu rovnici Office Math. +- IDE nebo čistý příkazový řádek `javac`/`java` – jakýkoliv vám vyhovuje. + +Pokud je už máte, skvělé. Pokud ne, následující sekce ukáže přesně, jak získat knihovnu do vašeho projektu. + +--- + +## Uložte Word jako markdown – Krok 1: Přidejte Aspose.Words do svého projektu + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Tip:** Aspose nabízí zdarma dočasnou licenci pro testování. Umístěte soubor `license.xml` do složky resources a zavolejte `License license = new License(); license.setLicense("license.xml");` před načtením jakéhokoli dokumentu. + +Jakmile je závislost vyřešena, můžete psát kód pro převod. + +--- + +## Jak exportovat rovnice do LaTeXu + +Těžkou práci provádí `MarkdownSaveOptions`. Přepnutím jeho `OfficeMathExportMode` na `LATEX` se každý objekt Office Math vykreslí jako LaTeX fragment v Markdown výstupu. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Proč to funguje + +- **`Document`** je vstupní bod Aspose; abstrahuje soubor `.docx` a poskytuje přístup ke všem uzlům, včetně rovnic. +- **`MarkdownSaveOptions`** říká knihovně *jak* chcete výstup. Výchozí chování je vykreslovat rovnice jako obrázky, což odporuje smyslu textového formátu. +- **`OfficeMathExportMode.LATEX`** nutí engine přeložit každý uzel `OfficeMath` do jeho LaTeX ekvivalentu, který mohou Markdown parsery (jako GitHub nebo Jekyll) vykreslit v kombinaci s pluginem MathJax. + +--- + +## Převod rovnic z Wordu do LaTeXu – Krok 2: Ověřte Markdown výstup + +Po spuštění programu otevřete `out.md`. Měli byste vidět něco jako toto: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Poznámka:** LaTeX fragmenty jsou obaleny v `$…$` pro inline matematiku a `$$…$$` pro blokovou matematiku. Toto je standardní syntax, kterou většina generátorů statických stránek rozumí, pokud je povolen MathJax. + +Pokud chcete, aby rovnice zůstaly pouze inline, můžete dále upravit `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx do markdown latex – Krok 3: Okrajové případy a běžné úskalí + +| Situace | Na co si dát pozor | Oprava | +|-----------|-------------------|-----| +| **Komplexní vnořené rovnice** | Aspose může vygenerovat nadbytečné závorky `{}`, které některé parsers interpretují doslovně. | Po‑zpracujte Markdown jednoduchým regexem, který sloučí `{{` → `{`. | +| **Chybějící MathJax na cílovém webu** | Rovnice se zobrazí jako surový LaTeX kód. | Přidejte `` do vaší HTML šablony. | +| **Velké dokumenty** | Spotřeba paměti stoupá, protože celý dokument se načítá najednou. | Použijte `LoadOptions.setLoadFormat(LoadFormat.DOCX)` a zvažte zpracování stránek po dávkách, pokud narazíte na `OutOfMemoryError`. | +| **Licence není nastavena** | Obdržíte varování a výstup může být vodoznakem. | Načtěte licenci brzy v `main`, jak je uvedeno v Maven tipu výše. | + +--- + +## Uložte Word jako markdown – Kompletní funkční příklad + +Níže je samostatná třída, kterou můžete zkopírovat a vložit do libovolného Java projektu. Stačí nahradit `YOUR_DIRECTORY` cestou k vašim souborům. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Spusťte program (`java MathToLatexMarkdown`) a uvidíte zprávu v konzoli potvrzující úspěch. Otevřete `out.md` v libovolném editoru – rovnice by měly být čisté LaTeX úryvky připravené k vykreslení. + +--- + +## Očekávaný výstup – náhled + +![výstup uložení Wordu jako markdown s LaTeX rovnicemi](https://example.com/images/markdown-latex-output.png "výstup uložení Wordu jako markdown s LaTeX rovnicemi") + +*Obrázek ukazuje úryvek vygenerovaného Markdownu, kde je rovnice `\int_{a}^{b} f(x)\,dx` obalena v `$$`.* + +--- + +## Závěr + +Právě jsme ukázali, jak **uložit Word jako markdown**, přičemž zachováme každou rovnici Office Math jako nativní LaTeX. Klíčovým krokem bylo nastavení `MarkdownSaveOptions` s `OfficeMathExportMode.LATEX`, což promění typický pipeline Word‑to‑Markdown na plně matematicky‑schopný konverzní nástroj. + +Nyní můžete: + +1. **Jak exportovat matematiku** z libovolného `.docx` bez ztráty věrnosti. +2. **Převést rovnice z Wordu do LaTeXu** pro generátory statických stránek, dokumentaci nebo akademické blogy. +3. Rozšířit přístup pro dávkové zpracování mnoha souborů, integraci s CI pipeline nebo dokonce vytvořit malou webovou službu. + +Pokud vás zajímá další hranice, zkuste kombinovat toto s **docx to markdown latex** pro dokumenty s mnoha obrázky, nebo prozkoumejte `HtmlSaveOptions` od Aspose pro web‑připravenou HTML verzi. Možnosti jsou neomezené – experimentujte, rozbíjejte věci a poté sdílejte své poznatky s komunitou. + +Máte otázky nebo obtížnou rovnici, která se nevypsala podle očekávání? Zanechte komentář níže a šťastné programování! + +## Související tutoriály + +- [Jak exportovat LaTeX z Wordu: převod DOCX do Markdown a uložení jako PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Převod docx do markdown – Export rovnic do LaTeXu s Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Jak převést Word do PDF pomocí Aspose.Words pro Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/czech/java/document-loading-and-saving/_index.md index a1fe0647a6..c6fe2e3f0a 100644 --- a/words/czech/java/document-loading-and-saving/_index.md +++ b/words/czech/java/document-loading-and-saving/_index.md @@ -132,6 +132,9 @@ Naučte se detekovat formáty dokumentů v Javě pomocí Aspose.Words. Identifik ### [Obnovení poškozeného docx – Kompletní průvodce opravou a zpracováním dokumentů](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [Otevření poškozeného dokumentu Word – nastavení režimu obnovy v Javě](./open-corrupted-word-document-set-recovery-mode-in-java/) +Naučte se, jak otevřít poškozený soubor Word a nastavit režim obnovy pomocí Aspose.Words for Java. + ### [Zachycení varování o nahrazení fontů v Javě pomocí Aspose.Words – Kompletní průvodce](./capture-font-substitution-warnings-in-java-with-aspose-words/) Naučte se, jak zachytit a zpracovat varování o nahrazení fontů při načítání dokumentů v Javě pomocí Aspose.Words. diff --git a/words/czech/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/czech/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..7eea61769d --- /dev/null +++ b/words/czech/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Otevřete poškozený dokument Word v Javě pomocí Aspose.Words. Naučte se + nastavit režim obnovy a spolehlivě obnovit poškozené soubory Word. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: cs +og_description: Otevřete poškozený dokument Word v Javě pomocí Aspose.Words. Tento + průvodce ukazuje, jak nastavit režim obnovy a efektivně obnovit poškozené soubory + Word. +og_title: Otevřít poškozený dokument Word – nastavit režim obnovy v Javě +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Otevřít poškozený dokument Word – nastavit režim obnovy v Javě +url: /cs/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Otevření poškozeného dokumentu Word – Nastavení režimu obnovy v Javě + +Už jste někdy zkoušeli otevřít poškozený dokument Word a sledovali, jak se program zadrhne na výjimce? Nejste sami – tyto poškozené soubory .docx mohou být skutečnou hlavolam. Dobrou zprávou je, že Aspose.Words for Java vám poskytuje detailní kontrolu, takže můžete **otevřít poškozený dokument Word** bez zhroucení aplikace a dokonce si můžete zvolit, zda chcete varování, tichou obnovu nebo tvrdé odmítnutí. + +V tomto tutoriálu projdeme kompletním procesem: od vytvoření správných `LoadOptions`, přes výběr vhodné hodnoty **set recovery mode**, až po potvrzení, že dokument byl skutečně načten. Na konci budete vědět **jak programově obnovit poškozený soubor Word**, bez nutnosti ručního kopírování a vkládání. + +> **Co budete potřebovat** +> * Java 8 nebo novější (API funguje také s Java 11) +> * Aspose.Words for Java 23.9 (nebo nejnovější verze) +> * Ukázkový poškozený .docx soubor – stačí přejmenovat libovolný platný soubor, aby se simulovalo poškození, pokud žádný po ruce nemáte + +Pojďme na to. + +## Otevření poškozeného dokumentu Word – Přehled krok za krokem + +Níže je vysokou úrovní tok, který implementujeme: + +1. **Vytvořte `LoadOptions`** – tento objekt říká Aspose.Words, jak se má chovat, když narazí na potíže. +2. **Nastavte režim obnovy** – vyberte `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` nebo `REJECT_CORRUPTED`. +3. **Načtěte dokument** pomocí nakonfigurovaných možností. +4. **Ověřte**, že načtení bylo úspěšné (např. vytiskněte počet stránek). + +Každý krok je podrobně vysvětlen, s úryvky kódu, které můžete zkopírovat přímo do svého IDE. + +## Nastavení režimu obnovy pro různé scénáře + +Aspose.Words definuje tři strategie obnovy uvnitř `LoadOptions.RecoveryMode`: + +| Mode | Chování | Kdy použít | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | Pokusí se načíst dokument, ale všechny problémy zobrazí jako varování v konzoli. | Chcete vidět *co* se pokazilo, aniž byste přerušili proces. | +| `RECOVER_WITHOUT_WARNINGS` | Tichým způsobem opraví, co může, a potlačí varování. | Produkční prostředí, kde musí být logy čisté. | +| `REJECT_CORRUPTED` | Vyhodí výjimku okamžitě po zjištění poškození. | Přísné validační řetězce, které musí selhat co nejdříve. | + +Výběr správného režimu je podstatou správného **set recovery mode**. Ve většině ladicích sezení je `RECOVER_WITH_WARNINGS` ideální, protože vám přesně řekne, které části byly opraveny. + +## Jak obnovit poškozený soubor Word pomocí Aspose.Words + +Níže je **kompletní, spustitelný Java program**, který demonstruje celý proces. Klidně jej vložte do souboru `RecoveryModeDemo.java`, upravte cestu a spusťte. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Proč je každý řádek důležitý + +* **`LoadOptions loadOptions = new LoadOptions();`** – bez tohoto objektu Aspose.Words používá výchozí obnovu, která *odmítá* poškozené soubory. Vytvořením získáte háček pro změnu tohoto chování. +* **`setRecoveryMode(...)`** – toto je volání **set recovery mode**, které rozhoduje, zda se zobrazí varování, zůstanou skrytá, nebo vyvolá výjimku. +* **`new Document(path, loadOptions);`** – konstruktor přijímá `LoadOptions`, které jsme právě nakonfigurovali, takže knihovna ví, jak má od začátku zacházet s poškozeným souborem. +* **`doc.getPageCount()`** – rychlá kontrola. Pokud se dokument načte a vrátí počet stránek, úspěšně jste **jak obnovit poškozený soubor Word**. +* **`doc.save(...)`** – volitelné, ale užitečné; můžete zapsat opravenou verzi zpět na disk pro pozdější použití. + +## Řešení běžných okrajových případů + +### 1. Soubor nenalezen + +Pokud je cesta špatná, `Document` vyhodí `FileNotFoundException`. Zabalte načítání do bloku try‑catch a zaznamenejte přátelskou zprávu: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Neobnovitelné poškození + +I při `RECOVER_WITH_WARNINGS` jsou některé struktury neobnovitelné. V takovém případě Aspose.Words načte, co může, ale uvidíte varování jako „Cannot read paragraph properties“. Věnujte pozornost výstupu v konzoli; tato varování často ukazují na chybějící sekce, které možná budete muset ručně rekonstruovat. + +### 3. Velké soubory a výkon + +Obnova přidává malé zatížení, protože knihovna soubor parsuje dvakrát – jednou pro detekci problémů, podruhé pro opravu. U dokumentů o velikosti několika gigabajtů zvažte streamování souboru nebo zvýšení haldy JVM (`-Xmx2g`), aby nedošlo k `OutOfMemoryError`. + +## Profesionální tipy – Jak učinit obnovu robustní + +* **Zaznamenávejte varování do souboru** – přesměrujte `System.err` do loggeru, abyste měli auditní stopu toho, co bylo opraveno. +* **Validujte po obnově** – spusťte `doc.updatePageLayout();` a poté znovu zkontrolujte počet stránek; někdy se rozložení změní po opravě poškozených sekcí. +* **Automatizujte hromadnou obnovu** – obalte demo do smyčky, která zpracuje složku poškozených souborů, přičemž pokaždé použije stejné `LoadOptions`. + +## Závěr + +Nyní přesně víte **jak obnovit poškozený soubor Word** pomocí Aspose.Words pro Java. Vytvořením instance `LoadOptions`, nastavením **set recovery mode** na strategii, která vyhovuje vašemu scénáři, a načtením dokumentu s těmito možnostmi můžete bezpečně **otevřít poškozený dokument Word** bez zhroucení aplikace. Ukázkový kód výše je kompletní, připravené řešení, které vytiskne počet stránek a dokonce uloží vyčištěnou kopii. + +Co dál? Zkuste přepnout režim obnovy na `RECOVER_WITHOUT_WARNINGS` a porovnat výstup v konzoli, nebo experimentujte s načítáním šifrovaných dokumentů (budete muset zadat heslo přes + +## Související tutoriály + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/czech/java/document-styling/_index.md index 08fb396057..31adf64b05 100644 --- a/words/czech/java/document-styling/_index.md +++ b/words/czech/java/document-styling/_index.md @@ -43,6 +43,8 @@ Naučte se, jak si přizpůsobit motivy dokumentů pomocí Aspose.Words pro Javu Naučte se, jak aplikovat vodoznaky a nastavit konfigurace stránek pomocí Aspose.Words pro Javu. Komplexní průvodce se zdrojovým kódem. ### [Styl záhlaví a zápatí dokumentu](./document-header-footer-styling/) Naučte se v tomto podrobném průvodci, jak upravovat styly záhlaví a zápatí dokumentů pomocí Aspose.Words pro Javu. Součástí je podrobný návod a zdrojový kód. +### [Nastavení výchozího písma v Aspose.Words pro Javu – Kompletní průvodce](./set-default-font-settings-in-aspose-words-for-java-complete/) +Naučte se, jak nastavit výchozí písmo pro všechny dokumenty pomocí Aspose.Words pro Javu s praktickými ukázkami kódu. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/czech/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..28b60bdf76 --- /dev/null +++ b/words/czech/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-05-26 +description: Nastavte výchozí nastavení písma v Aspose.Words pro Javu a naučte se, + jak nastavit nastavení písma a detekovat chybějící písma pomocí několika řádků kódu. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: cs +og_description: Nastavte výchozí nastavení písma v Aspose.Words pro Javu, naučte se + nastavit písmo a rychle a spolehlivě detekovat chybějící písma. +og_title: Nastavte výchozí nastavení písma v Aspose.Words pro Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Nastavte výchozí nastavení písma v Aspose.Words pro Javu – Kompletní průvodce +url: /cs/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nastavení výchozích nastavení písma v Aspose.Words pro Java – Kompletní průvodce + +Už jste se někdy zamysleli, jak **nastavit výchozí nastavení písma** při načítání dokumentu Word pomocí Aspose.Words pro Java? Nejste v tom sami. Chybějící glyfy mohou proměnit vyladěnou zprávu v nečitelný chaos a zachycení varování o nahrazení písma včas ušetří hodiny ladění. + +V tomto tutoriálu projdeme stručný, kompletní příklad, který **nastavuje výchozí nastavení písma**, ukáže vám, jak **nastavit nastavení písma** programově, a předvede spolehlivý způsob, jak **detekovat chybějící písma** dříve, než naruší vaše rozvržení. + +--- + +## Co se naučíte + +- Jak vytvořit objekt `LoadOptions` s novou instancí `FontSettings`. +- Jak připojit posluchač varování, který bude **detekovat chybějící písma** během načítání dokumentu. +- Jak načíst soubor DOCX, zatímco posluchač tiše hlásí jakékoli nahrazení. +- Tipy pro přizpůsobení náhradních písem a řešení okrajových případů v produkci. + +Žádné další knihovny, žádné nejasné konfigurační soubory – jen čistá Java a Aspose.Words. + +## Požadavky + +Než se ponoříme, ujistěte se, že máte: + +1. **Aspose.Words for Java** (verze 23.10 nebo novější) na vašem classpathu. +2. Vývojový kit Java 17 (nebo novější) – funguje jakýkoli moderní JDK. +3. Soubor DOCX, který úmyslně používá písmo, které nemáte nainstalované (např. *“MissingFont.ttf”*). + +Pokud vám chybí JAR Aspose, stáhněte jej z oficiálního Maven repozitáře: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +A to je vše – pro tuto ukázku není potřeba instalovat žádná další písma. + +## Krok 1: Vytvořte LoadOptions a **nastavte výchozí nastavení písma** + +První věc, kterou potřebujeme, je čistý objekt `LoadOptions`, který Aspose říká, jak se má chovat při setkání s neznámými typy písma. Voláním `setFontSettings(new FontSettings())` **nastavíme výchozí nastavení písma**, které začíná prázdným seznamem náhrad. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Proč je to důležité:** +> Když explicitně nenakonfigurujete písma, Aspose se vrátí k výchozí kolekci systému, což může skrýt problémy s chybějícími písmy. Začínáním s novou instancí `FontSettings` získáte plnou kontrolu nad tím, která písma jsou považována za platná. + +## Krok 2: Připojte posluchač varování k **detekci chybějících písem** + +Aspose vyvolá objekt `WarningInfo` pro každé provedené nahrazení. Posloucháním `WarningType.FONT_SUBSTITUTION` můžeme **detekovat chybějící písma** hned při parsování dokumentu. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Tip:** Posluchač běží ve stejném vlákně, které načítá dokument, takže prakticky neexistuje žádný výkonový dopad. Pokud potřebujete sbírat varování pro pozdější analýzu, vložte je do `List` místo přímého výpisu. + +## Krok 3: Načtěte dokument pomocí nakonfigurovaných možností + +Nyní, když jsme **nastavili nastavení písma** a připravili posluchače, jednoduše načteme soubor. Jakékoli chybějící písmo okamžitě spustí náš zpětný volání. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Pokud zdrojový soubor odkazuje na písmo, které není nainstalováno, uvidíte výstup podobný: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Tento řádek vám přesně řekne, které písmo chybělo a která náhrada byla použita – ideální pro logování nebo zpětnou vazbu uživateli. + +## Krok 4: Pokračujte v běžném zpracování (volitelné) + +V tomto okamžiku je dokument plně načtený a můžete pokračovat s libovolnou manipulací – úpravou, konverzí do PDF nebo extrakcí textu. Posluchač varování již odvedl svou práci, takže další kontroly nejsou potřeba. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Co když chcete vlastní náhradu?** +> Místo ponechání `FontSettings` prázdného můžete přidat konkrétní písma: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Nyní bude jakékoli chybějící písmo nahrazeno *Times New Roman* – spolehlivá volba pro většinu západních dokumentů. + +## Vizualizace + +![Diagram ukazující, jak nastavit výchozí nastavení písma v Aspose.Words pro Java](image.png "Diagram toku nastavení výchozího písma") + +*Alt text: nastavení výchozího písma v Aspose.Words pro Java diagram.* + +Diagram ilustruje tok od inicializace `LoadOptions` (kde **nastavujeme výchozí nastavení písma**) po připojení posluchače varování (k **detekci chybějících písem**) a nakonec načtení dokumentu. + +## Časté úskalí a jak se jim vyhnout + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **Zapomněli zavolat `setFontSettings`** | Aspose používá výchozí nastavení systému, což skrývá chybějící písma. | Vždy vytvořte novou instanci `FontSettings` a přiřaďte ji do `LoadOptions`. | +| **Posluchač není spuštěn** | Posluchač byl přidán po načtení dokumentu. | Přidejte posluchač varování *před* voláním `new Document(...)`. | +| **Chybná cesta vede k `FileNotFoundException`** | Pevně zakódovaná cesta neodpovídá citlivosti na velikost písmen OS. | Použijte `Paths.get("...").toAbsolutePath()` nebo nastavte relativní cestu od kořene projektu. | +| **Více chybějících písem zahlcuje logy** | Velké dokumenty mohou generovat desítky varování. | Filtrujte duplicitní zprávy nebo je agregujte v `Set` před výpisem. | + +## Rozšíření řešení + +Pokud potřebujete **nastavit nastavení písma** pro celou aplikaci, zvažte vytvoření singletonu `FontSettings` a jeho opakované používání ve všech `LoadOptions`. Tím zajistíte konzistentní strategii náhrad a vyhnete se opakovanému vytváření objektů. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Nyní může jakákoli část vašeho kódu jednoduše zavolat `FontConfig.getLoadOptions()` a okamžitě využít stejnou logiku **nastavení výchozího nastavení písma**. + +## Závěr + +Právě jsme probrali vše, co potřebujete k **nastavení výchozího nastavení písma** v Aspose.Words pro Java, **nastavení písma** programově a **detekci chybějících písem** dříve, než zničí váš výstup. Kompletní, spustitelný příklad je v kódech výše a můžete jej vložit přímo do svého IDE a vidět varování v akci. + +Další kroky? Zkuste vyměnit náhradní písmo, experimentujte s různými formáty dokumentů (DOC, RTF, HTML) nebo integrujte sběrač varování do monitorovacího dashboardu. Čím více si pohráváte s `FontSettings`, tím jistější budete, že vaše generované dokumenty vypadají přesně tak, jak mají – žádná překvapení, žádné poškozené glyfy. + +Máte otázky nebo složitý scénář nahrazení písma? Zanechte komentář níže a šťastné programování! + +## Související tutoriály + +- [Nastavit nastavení náhradních písem](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Nastavit nastavení náhradních písem](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Nastavit nastavení náhradních písem](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/java/images-shapes/_index.md b/words/czech/java/images-shapes/_index.md index f09c93c28b..0c36aac393 100644 --- a/words/czech/java/images-shapes/_index.md +++ b/words/czech/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Naučte se, jak generovat vysoce kvalitní miniatury a rastrové obrázky vlastn ### [Vytvořit Word dokument v Javě – Přidat obdélníkový tvar se stínovým efektem](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Naučte se, jak přidat obdélníkový tvar se stínem do Word dokumentu pomocí Aspose.Words pro Javu. +### [Vytvořit obdélníkový tvar v dokumentu Word v Javě – Kompletní průvodce krok za krokem](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Kompletní návod, jak v Javě pomocí Aspose.Words vytvořit obdélníkový tvar v dokumentu Word. + ## Další zdroje - [Dokumentace k Aspose.Words pro Javu](https://reference.aspose.com/words/java/) diff --git a/words/czech/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/czech/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..4de3cd93a5 --- /dev/null +++ b/words/czech/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-26 +description: Vytvořte obdélníkový tvar v dokumentu Word pomocí Javy a aplikujte efekt + stínu. Naučte se, jak přidat stín tvaru, nastavit vzdálenost stínu a soubor uložit. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: cs +og_description: Vytvořte obdélníkový tvar v dokumentu Word v Javě, použijte efekt + stínu, přidejte stín tvaru a nastavte vzdálenost stínu pomocí Aspose.Words. +og_title: Vytvořte obdélníkový tvar v dokumentu Word v Javě – kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Vytvořte obdélníkový tvar v Java Word dokumentu – Kompletní krok‑za‑krokem + průvodce +url: /cs/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření obdélníkového tvaru v Java Word dokumentu – Kompletní průvodce krok za krokem + +Už jste někdy potřebovali **create rectangle shape** v Java Word dokumentu, ale nevedeli jste, kde začít? Nejste v tom sami – mnoho vývojářů narazí na tento problém při programovém generování reportů nebo faktur. V tomto tutoriálu vás provedeme přesně tím, jak **create rectangle shape**, aplikovat vylepšený stín a doladit vzdálenost stínu, aby výsledek vypadal profesionálně. + +Použijeme Aspose.Words for Java, robustní knihovnu, která vám umožní manipulovat se soubory Word bez nutnosti instalace Microsoft Office. Na konci tohoto průvodce budete schopni vytvářet projekty **create word document java**, které **add shape shadow**, **apply shadow effect** a **set shadow distance** pomocí jen několika řádků kódu. + +--- + +## Co vytvoříte + +- Čerstvý soubor `.docx` obsahující azurový obdélník. +- Realistický vržený stín, který je rozostřený, nakloněný a částečně průhledný. +- Plná kontrola nad vzdáleností stínu od tvaru. +- Připravená Java třída, kterou můžete vložit do jakéhokoli Maven nebo Gradle projektu. + +Žádné externí nástroje, žádné ruční UI kroky – jen čistý kód. + +## Požadavky + +- Java 8 nebo novější (kód funguje na Java 11, Java 17 atd.). +- Knihovna Aspose.Words for Java (k dispozici přes Maven Central). +- IDE nebo textový editor podle vašeho výběru (IntelliJ IDEA, Eclipse, VS Code…). +- Základní znalost syntaxe Java. + +Pokud jste ještě nikdy nepřidali Maven závislost, zde je rychlý úryvek: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Pojďme na to. + +## Krok 1: Vytvoření obdélníkového tvaru v Word dokumentu + +První věc, kterou potřebujeme, je prázdný dokument a `DocumentBuilder`. Představte si builder jako pero, které zapisuje do dokumentu. Jakmile ho máme, můžeme **create rectangle shape** jedním voláním metody. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Proč je to důležité:** Metoda `insertShape` nejen vytváří geometrii, ale také přidává tvar do interní kolekce dokumentu, takže můžete okamžitě začít stylovat. + +## Krok 2: Aplikace stínového efektu na tvar + +Nyní, když obdélník leží na stránce, **apply shadow effect**. Stíny dodávají hloubku, díky čemuž se tvar zdá být nadzvednutý od stránky – jemné UI vylepšení, které může zvýšit čitelnost v reportech. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Tip:** Rozostření `5.0` vypadá přirozeně pro většinu dokumentů zobrazovaných na obrazovce. Pokud tisknete, možná budete chtít mírně nižší hodnotu, aby se předešlo rozmazanému vzhledu. + +## Krok 3: Nastavení vzdálenosti stínu – jemné doladění umístění + +Stíny nejsou jen o rozostření; potřebují také správný posun. Zde **set shadow distance**. Vzdálenost `7.0` bodů vytváří mírný posun, který je patrný, ale ne přehnaný. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Co když potřebujete větší posun?** Zvyšte hodnotu; snižte ji pro těsnější vzhled. Pamatujte, že vzdálenost spolupracuje s úhlem pro správné umístění stínu. + +## Krok 4: Uložení dokumentu – uložení vaší práce + +Nakonec zapíšeme dokument na disk. Změňte cestu na místo, kde chcete, aby soubor byl uložen. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Spuštěním třídy se vytvoří soubor `shadow.docx`, který po otevření v Microsoft Word nebo LibreOffice zobrazí azurový obdélník s jemným šedým stínem nakloněným pod úhlem 45° a posunutým o 7 bodů. + +## Kompletní funkční příklad + +Níže je kompletní kód připravený ke zkopírování a vložení. Obsahuje všechny importy, komentáře a závěrečné volání `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Očekávaný výstup:** Otevřete `shadow.docx` → uvidíte azurový obdélník uprostřed první stránky, vrhající jemný šedý stín, který je mírně posunutý dolů a doprava. Rozostření a průhlednost stínu mu dodávají vzhled přirozeného osvětlení. + +## Časté otázky a okrajové případy + +### „Mohu použít jiný tvar?“ + +Určitě. Nahraďte `ShapeType.RECTANGLE` za `ShapeType.OVAL`, `ShapeType.LINE` nebo jakýkoli jiný podporovaný enum. Zbytek kódu pro stín zůstane stejný. + +### „Co když potřebuji více stínů?“ + +Aspose.Words podporuje pouze jeden stín na tvar. Pro simulaci více stínů duplikujte tvar, posuňte každou kopii a upravte průhlednost. + +### „Je stín viditelný v LibreOffice?“ + +Ano – Aspose.Words zapisuje standardní OOXML, který LibreOffice správně interpretuje. Stín může vypadat mírně odlišně kvůli renderovacím enginům, ale efekt zůstává. + +### „Jak změním barvu stínu, aby odpovídala mé značce?“ + +Jednoduše vyměňte `java.awt.Color.GRAY` za libovolnou `java.awt.Color`, kterou preferujete, například `new java.awt.Color(0, 120, 215)` pro firemnou modrou. + +## Ilustrace + +![vytvoření obdélníkového tvaru v Java Word dokumentu](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** ilustrace zobrazující azurový obdélník se šedým vrženým stínem ve Word dokumentu. + +## Shrnutí a další kroky + +Probrali jsme, jak **create rectangle shape**, **apply shadow effect**, **add shape shadow** a **set shadow distance** pomocí Aspose.Words for Java. Kód je samostatný, běží na jakémkoli moderním JDK a vytváří vylepšený soubor `.docx` připravený k distribuci. + +Chcete jít dál? Vyzkoušejte: + +- Přidání textu uvnitř obdélníku pomocí `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Vytvoření tabulky tvarů pro vytvoření diagramu. +- Export dokumentu do PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Každý z těchto kroků staví na stejných základech, které jsme právě probrali, takže se budete cítit jistě při rozšiřování příkladu. + +## Závěrečné myšlenky + +Ovládnutí úkolů **create word document java**, jako je tvorba tvarů a stínování, vám poskytne velkou výhodu při automatizaci reportů, smluv nebo marketingových materiálů. Přístup zde předvedený je čistý, udržovatelný a – co je nejdůležitější – snadno upravitelný pro jakýkoli vizuální styl, který potřebujete. + +Vyzkoušejte kód, upravte rozostření, úhel a vzdálenost a sledujte, jak se vaše dokumenty promění z nudných na vylepšené. Pokud narazíte na problém, zanechte komentář níže; rád pomohu. + +Šťastné programování! + +## Související tutoriály + +- [Vytvořit Word dokument Java – Přidat obdélníkový tvar se stínovým efektem](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Jak vytvořit formulářová pole a přidat obsah pomocí DocumentBuilder v Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Vytvořit PDF z Wordu s generováním čárových kódů – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/dutch/java/document-conversion-and-export/_index.md index f5cad79ee9..9f92db46f3 100644 --- a/words/dutch/java/document-conversion-and-export/_index.md +++ b/words/dutch/java/document-conversion-and-export/_index.md @@ -43,7 +43,7 @@ Een watermark is een vage afbeelding of tekst die achter de hoofdinhoud van een - Een geldige Aspose‑licentie voor productiegebruik (gratis proefversie beschikbaar). ## Aan de Slag met Aspose.Words for Java -Ben je nieuw met Aspose.Words for Java? Geen zorgen! Deze tutorial leidt je door de eerste installatie en biedt je een solide basis om met deze API te werken. Je bent in een mum van tijd operationeel. +Ben je nieuw met Aspose.Words for Java? Geen zorgen! deze tutorial leidt je door de eerste installatie en biedt je een solide basis om met deze API te werken. Je bent in een mum van tijd operationeel. ## Documenten Converteren naar Verschillende Formaten Een van de belangrijkste functies van Aspose.Words for Java is het vermogen om **convert docx to pdf** en vele andere formaten naadloos te converteren. Of je nu een DOCX‑bestand naar PDF moet converteren of omgekeerd, deze tutorial leidt je stap voor stap door het proces. Je krijgt een diepgaand begrip van de conversie‑opties en aanpassingsmogelijkheden. @@ -92,18 +92,33 @@ Leer hoe je DOCX-bestanden eenvoudig naar PDF converteert met Aspose.Words for J ### [Maak Toegankelijke PDF van DOCX – Complete Gids](./create-accessible-pdf-from-docx-complete-guide/) Leer hoe je met Aspose.Words for Java een toegankelijke PDF maakt van een DOCX, inclusief tags, structuur en leesbaarheid voor schermlezers. +### [Document opslaan als PDF met Aspose.Words Java – Volledige toegankelijkheidsgids](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Leer hoe je een document volledig toegankelijk maakt bij het opslaan als PDF met Aspose.Words for Java, inclusief tags, structuur en schermlezerondersteuning. + ### [Formatting Tables and Table Styles in Aspose.Words for Java](./formatting-tables-and-table-styles/) Leer hoe je tabellen opmaakt en tabelstijlen toepast in Aspose.Words for Java. Verken stap‑voor‑stap gidsen met broncode voor effectieve tabelopmaak. Verbeter je documentlay-out met Aspose.Words. ### [DOCX naar Markdown converteren – Wiskundige vergelijkingen exporteren naar LaTeX met Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Leer hoe je DOCX-bestanden omzet naar Markdown en wiskundige vergelijkingen exporteert naar LaTeX met Aspose.Words. +### [Word opslaan als markdown – Exporteer wiskunde naar LaTeX met Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Leer hoe je een Word‑document opslaat als Markdown en wiskundige vergelijkingen exporteert naar LaTeX met Aspose.Words for Java. + ### [Hoe afbeeldingen inbedden in Markdown bij het converteren van DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Leer hoe je afbeeldingen in Markdown kunt inbedden tijdens het converteren van DOCX met Aspose.Words for Java. +### [Afbeeldingen insluiten als Base64 bij het converteren van DOCX naar Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Leer hoe je afbeeldingen omzet naar Base64 en insluit in Markdown tijdens DOCX-conversie met Aspose.Words for Java. + ### [Document opslaan als TXT – Snelle gids voor het exporteren van Word-wiskunde](./save-document-as-txt-quick-guide-to-exporting-word-math/) Leer hoe je een Word‑document als TXT opslaat en wiskundige vergelijkingen exporteert met Aspose.Words for Java. +### [Export docx naar txt met Java – Complete Programmeergids](./export-docx-to-txt-with-java-complete-programming-guide/) +Leer hoe je een DOCX‑bestand naar TXT exporteert met Aspose.Words for Java in een volledige stap‑voor‑stap programmeergids. + +### [Maak Toegankelijke PDF in Java – Volledige Tagginggids](./create-accessible-pdf-in-java-full-tagging-guide/) +Leer hoe je met Aspose.Words for Java een volledig getagde toegankelijke PDF maakt. + ## Veelgestelde Vragen **Q: Hoe voeg ik een watermark toe aan een bestaande PDF met Aspose.Words?** diff --git a/words/dutch/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/dutch/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..3d728c403b --- /dev/null +++ b/words/dutch/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-26 +description: Maak een toegankelijke PDF in Java met stapsgewijze code. Leer hoe je + PDF kunt taggen voor toegankelijkheid en PDF‑tagging kunt inschakelen met PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: nl +og_description: Maak een toegankelijke PDF in Java met stapsgewijze code. Leer hoe + je PDF tagt voor toegankelijkheid en PDF‑tagging inschakelt met PdfSaveOptions. +og_title: Maak een toegankelijke PDF in Java – Complete gids voor tagging +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Maak een toegankelijke PDF in Java – Volledige gids voor taggen +url: /nl/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak Toegankelijke PDF in Java – Volledige Tagginggids + +Heb je je ooit afgevraagd hoe je **toegankelijke PDF**‑bestanden rechtstreeks vanuit Java‑code kunt **maken**? Je bent niet de enige. Veel ontwikkelaars moeten gebruikers bedienen die afhankelijk zijn van schermlezers, en het verschil tussen een gewone PDF en een toegankelijke kan enorm zijn. In deze tutorial lopen we **uit hoe je PDF tagt voor toegankelijkheid**, laten we je **zien hoe je een getagde PDF maakt** met Aspose PDF for Java, en onthullen we de exacte stappen om **toegankelijkheidstags aan PDF toe te voegen** zodat elke lezer dezelfde informatie krijgt. + +We behandelen ook **beste praktijken voor het inschakelen van PDF‑tagging**, veelvoorkomende valkuilen en een compleet, uitvoerbaar voorbeeld dat je vandaag nog in je project kunt plaatsen. Geen vage verwijzingen—alleen concrete code, uitleg en een eindbestand dat je in Adobe Acrobat kunt openen om de tags te verifiëren. + +## Wat je zult leren + +- Het waarom achter PDF‑tagging en toegankelijkheids‑compliance. +- Voorvereisten en bibliotheek‑setup (Aspose PDF for Java 23.10 of later). +- Hoe je **toegankelijke PDF** vanaf nul maakt, stap voor stap. +- Manieren om **toegankelijkheidstags aan PDF toe te voegen** naast de basisaanroep `setTagDocumentStructure`. +- Tips voor het testen van de output en het oplossen van veelvoorkomende problemen. + +Aan het einde van deze gids kun je PDFs genereren die voldoen aan WCAG 2.1 AA‑controles en er tegelijkertijd professioneel uitzien. + +--- + +## Voorvereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +| Vereiste | Reden | +|----------|-------| +| **Java 8+** | Moderne taalfeatures en betere Unicode‑afhandeling. | +| **Aspose PDF for Java** (v23.10 of nieuwer) | Biedt de `PdfSaveOptions`‑klasse en tagging‑ondersteuning. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Voor eenvoudige compilatie en debugging. | +| **Schrijfrechten** voor een map waar de PDF wordt opgeslagen | De `doc.save`‑aanroep heeft een schrijfbare pad nodig. | + +Als je Aspose PDF nog niet aan je project hebt toegevoegd, plaats dan de volgende Maven‑dependency in je `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** Gebruik de nieuwste versie; nieuwere releases verbeteren de tagging‑nauwkeurigheid en voegen taalspecifieke toegankelijkheidsfuncties toe. + +--- + +## Stap 1: Zet de Document‑skelet op + +Eerst maken we een nieuw `Document`‑object. Beschouw het als een leeg canvas dat later de tags zal bevatten die we nodig hebben voor toegankelijkheid. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Waarom dit belangrijk is:** Zonder inhoud is er niets om te taggen. Het toevoegen van zelfs een eenvoudige `TextFragment` geeft de tagging‑engine iets om mee te werken, en het maakt automatisch een `

` (paragraaf)‑tag aan wanneer we later structuur‑tagging inschakelen. + +--- + +## Stap 2: Maak PDF‑Opslagopties (de kern van tagging) + +Nu bereiden we de opties voor die Aspose PDF vertellen een logische structuurboom in het bestand te embedden. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +De aanroep `setTagDocumentStructure(true)` is de **enable PDF tagging**‑schakelaar. Wanneer deze op `true` staat, bouwt de bibliotheek een tagboom die de visuele lay-out weerspiegelt, waardoor de PDF leesbaar wordt voor assistieve technologieën. + +> **Opmerking:** Dit is de eenvoudigste manier om **how to create tagged pdf** te doen. Voor meer gedetailleerde controle (bijv. het instellen van taal of aangepaste tags) kun je `pdfOptions.setTagLanguage("en-US")` en `pdfOptions.setTagStructureTreeRoot(...)` verkennen. + +--- + +## Stap 3: Sla de Toegankelijke PDF op + +Tot slot schrijven we het document naar schijf met de opties die we zojuist hebben geconfigureerd. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Wanneer `doc.save` voltooid is, vind je `accessible.pdf` in de `output`‑map. Open het in Adobe Acrobat en kijk onder **File → Properties → Description → Tags** – je zou een gevulde tagboom moeten zien. + +--- + +## Hoe PDF te taggen voor toegankelijkheid – Voorbij de basis + +Het drie‑stappen‑fragment hierboven **voegt al toegankelijkheidstags toe aan PDF**, maar documenten uit de praktijk hebben vaak wat extra verfijning nodig. Hier zijn een paar verbeteringen die je kunt toevoegen: + +### 1. Stel Documenttaal in + +Schermlezers gebruiken het taal‑attribuut om tekst correct uit te spreken. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Voeg een Titel en Onderwerp toe + +Metadata helpt assistieve tools context te geven voordat de gebruiker het bestand zelfs opent. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Tag Afbeeldingen met Alternatieve Tekst + +Als je afbeeldingen insluit, hebben ze `alt`‑beschrijvingen nodig. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Markeer Tabelkoppen + +Tabellen verwarren lezers vaak, tenzij je header‑rijen markeert. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Deze extra stappen maken je PDF niet alleen *technisch* getagd, maar echt **toegankelijk** voor een divers publiek. + +--- + +## Veelvoorkomende valkuilen bij het inschakelen van PDF‑tagging + +| Symptom | Waarschijnlijke oorzaak | Oplossing | +|---------|--------------------------|-----------| +| Tags ontbreken in Acrobat | `setTagDocumentStructure` staat op `false` | Zorg dat je `pdfOptions.setTagDocumentStructure(true)` aanroept. | +| Verkeerde leesvolgorde | Complexe lay-out zonder expliciete tags | Gebruik `pdfOptions.setTagStructureTreeRoot(...)` om een aangepaste volgorde te definiëren. | +| Afbeeldingen worden gelezen als “image” zonder beschrijving | Geen alternatieve tekst ingesteld | Roep `image.getAlternativeText().setValue("...")` aan. | +| Taal wordt niet herkend | `setTagLanguage` weggelaten of verkeerde locale | Geef een BCP‑47 taalcodes op (`en-US`, `fr-FR`). | + +Bewustzijn van deze issues bespaart je uren debugging later. + +--- + +## Verifieer het resultaat – Wat je kunt verwachten + +Na het uitvoeren van het programma, open `output/accessible.pdf` in Adobe Acrobat Reader: + +1. **Tags‑paneel** (`View → Show/Hide → Navigation Panes → Tags`) moet een hiërarchie tonen zoals `/Document → /Part → /Sect → /Para`. +2. **Leesvolgorde** moet de visuele stroom volgen (tekst eerst, daarna afbeeldingen). +3. **Schermlezer** (NVDA, VoiceOver) zal “Hello, accessible PDF!” uitspreken in plaats van alleen “Page 1”. + +Als een van deze items ontbreekt, controleer dan de bovenstaande stappen nogmaals—vooral de `setTagDocumentStructure`‑aanroep. + +--- + +## Volledig werkend voorbeeld (Kopieer‑en‑Plak klaar) + + + +## Gerelateerde tutorials + +- [Create Accessible PDF from Word – Convert to PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Create Accessible PDF from DOCX – Complete Guide](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/dutch/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/dutch/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..ab82654c4d --- /dev/null +++ b/words/dutch/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Voeg afbeeldingen in als base64 terwijl je docx naar markdown converteert + met Aspose.Words voor Java. Leer hoe je Word naar markdown converteert, Word als + markdown opslaat en afbeeldingen verwerkt. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: nl +og_description: Afbeeldingen insluiten als base64 tijdens het converteren van docx + naar markdown met Aspose.Words voor Java. Complete gids om Word naar markdown te + converteren en Word op te slaan als markdown. +og_title: Afbeeldingen insluiten als Base64 bij het converteren van DOCX naar Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Afbeeldingen insluiten als Base64 bij het converteren van DOCX naar Markdown +url: /nl/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Afbeeldingen insluiten als Base64 bij het converteren van DOCX naar Markdown + +Heb je je ooit afgevraagd hoe je **afbeeldingen als base64** kunt **insluiten terwijl je docx naar markdown converteert**? Je bent niet de enige—ontwikkelaars vragen voortdurend hoe ze afbeeldingen inline kunnen houden zonder aparte bestanden te beheren. Het goede nieuws is dat Aspose.Words for Java het een fluitje van een cent maakt: je kunt een Word‑document naar Markdown converteren en automatisch elke afbeelding als een Base64‑string insluiten. + +In deze tutorial lopen we het volledige proces door—van het laden van een `.docx` met afbeeldingen, tot het configureren van een `MarkdownSaveOptions`‑callback die het zware werk doet, en uiteindelijk het opslaan van het resultaat als een nette `.md`‑file. Aan het einde weet je precies hoe je **word naar markdown converteert**, **afbeeldingen naar base64 converteert**, en **word als markdown opslaat** zonder achtergebleven afbeeldingsmappen. Geen externe tools, geen handmatige nabewerking—alleen pure Java‑code die je in elk project kunt gebruiken. + +## Wat je nodig hebt + +- **Java 17** (of een recente JDK) – de code maakt gebruik van lambda‑syntaxis, maar je kunt het aanpassen voor oudere versies. +- **Aspose.Words for Java**‑bibliotheek (nieuwste versie per 2026). Voeg de Maven‑dependency toe of plaats de JAR in je classpath. +- Een voorbeeld **DOCX**‑bestand dat minstens één afbeelding bevat. +- Een IDE of een eenvoudige teksteditor—Visual Studio Code, IntelliJ IDEA, of zelfs `vim` volstaat. + +Als je dit al hebt, prima—laten we meteen beginnen. + +## Stap 1: Laad het Word‑document + +Eerst maken we een `Document`‑instance die naar het bronbestand wijst. Dit is dezelfde stap of je nu **docx naar markdown converteert** of het bestand alleen voor andere doeleinden leest. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Waarom dit belangrijk is:** Het `Document`‑object is het toegangspunt voor elke Aspose‑bewerking. Het bevat de volledige Word‑structuur—including afbeeldingen, tabellen en stijlen—zodat de callback later elke bron kan inspecteren. + +## Stap 2: Maak MarkdownSaveOptions en registreer een Resource‑Saving‑callback + +De magie zit in `MarkdownSaveOptions`. Door een `IResourceSavingCallback` toe te voegen, krijg je controle over hoe elke externe bron (zoals een afbeelding) wordt weggeschreven. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Waarom `setSaveToMemory(true)` gebruiken? + +Wanneer `saveToMemory` true is, schrijft Aspose de afbeeldingsbytes naar een geheugen‑stream in plaats van naar een bestand. De Markdown‑exporteur zet die stream vervolgens om in een Base64‑string en plaatst die direct in de Markdown‑afbeeldingstag: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Dat is de kern van **afbeeldingen insluiten als base64**. + +## Stap 3: Sla het document op als Markdown + +Nu de callback is ingesteld, is de laatste stap simpelweg het aanroepen van `save`. Hier converteer je daadwerkelijk **word naar markdown** en, dankzij de callback, ook **afbeeldingen naar base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Resultaat:** `out.md` bevat Markdown‑tekst met elke afbeelding weergegeven als een `data:`‑URI. Er worden geen extra afbeeldingsbestanden op schijf aangemaakt, zodat de map netjes blijft. + +## Stap 4: Controleer de output en veelvoorkomende valkuilen + +Open het gegenereerde `out.md` in een Markdown‑viewer (VS Code, GitHub, of een static site generator). Je zou iets moeten zien als: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Checklist voor probleemoplossing + +| Probleem | Waarschijnlijke oorzaak | Oplossing | +|----------|--------------------------|-----------| +| Afbeelding verschijnt als kapotte link | `setSaveToMemory` ontbrak | Zorg dat `args.setSaveToMemory(true);` in de callback staat | +| Base64‑string is afgekapt | Codering van output‑bestand komt niet overeen | Sla de Markdown op met UTF‑8 (standaard voor Aspose) | +| Onverwachte bestandsnamen | `setKeepResourceOriginalName(true)` | Houd het `false` om de aangepaste naamgevingslogica af te dwingen | + +## Stap 5: Geavanceerde variaties (optioneel) + +### Alleen geselecteerde afbeeldingen converteren + +Als je alleen bepaalde afbeeldingen wilt insluiten (bijv. die groter zijn dan 100 KB), voeg dan een grootte‑check toe: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Een ander afbeeldingsformaat gebruiken + +`ResourceSavingArgs` levert de ruwe bytes, zodat je JPEG’s kunt hercoderen naar PNG’s vóór het insluiten—handig wanneer de doel‑Markdown‑consumer PNG prefereert. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Deze aanpassingen laten zien hoe flexibel de **afbeeldingen insluiten als base64**‑aanpak is wanneer je **docx naar markdown converteert**. + +## Conclusie + +Je hebt zojuist geleerd hoe je **afbeeldingen als base64** kunt **insluiten terwijl je docx naar markdown converteert** met Aspose.Words for Java. Door een eenvoudige `IResourceSavingCallback` te verbinden, doet de bibliotheek al het zware werk: het **converteert word naar markdown**, **converteert afbeeldingen naar base64**, en slaat tenslotte **word als markdown** op met één enkele `save`‑aanroep. + +Voel je vrij om te experimenteren—probeer verschillende afbeeldings‑filterregels, schakel over naar HTML‑output, of koppel deze stap aan een static‑site generator. Hetzelfde patroon werkt ook voor andere formaten (HTML, EPUB), zodat je de callback overal kunt hergebruiken waar je inline resources nodig hebt. + +**Volgende stappen:** +- Verken `HtmlSaveOptions` voor HTML‑met‑Base64‑afbeeldingen. +- Combineer dit met een CI‑pipeline om documentatie‑generatie te automatiseren. +- Duik in Aspose’s `DocumentVisitor` als je nog fijnmazigere controle over het conversieproces nodig hebt. + +Happy coding, en geniet van je nette, zelf‑behorende Markdown‑bestanden! + +## Gerelateerde tutorials + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/dutch/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..cbf9ac90c6 --- /dev/null +++ b/words/dutch/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-26 +description: Export docx naar txt met Java en Aspose.Words. Leer hoe je docx naar + tekst converteert, Unicode behoudt en Word exporteert als txt in een paar stappen. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: nl +og_description: Exporteer docx naar txt in Java. Deze tutorial laat zien hoe je docx + naar tekst converteert, platte Unicode-tekst behoudt en Word efficiënt als txt exporteert. +og_title: Export docx naar txt met Java – Complete gids +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Export docx naar txt met Java – Complete programmeergids +url: /nl/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Export docx naar txt met Java – Complete programmeergids + +Heb je ooit **export docx to txt** moeten doen maar maak je je zorgen over het verlies van speciale tekens? Je bent niet de enige. Wanneer je Word‑documenten converteert naar platte‑tekstbestanden, kunnen Unicode‑symbolen, tabellen en zelfs eenvoudige opmaak als magie verdwijnen. + +In deze gids lopen we stap voor stap een betrouwbare manier door om **export docx to txt** te gebruiken met Aspose.Words voor Java, waarbij elk Unicode‑teken behouden blijft en de tabelindelingen leesbaar blijven. Aan het einde weet je ook hoe je **convert docx to text**, **convert word to text**, en zelfs **export word as txt** kunt uitvoeren zonder problemen. + +## Wat deze tutorial behandelt + +* Instellen van Aspose.Words in een Java‑project +* Een DOCX‑bestand laden en voorbereiden voor platte‑tekstoutput +* Configureren van **plain text unicode**‑ondersteuning via `TxtSaveOptions` +* Optionele trucjes om tabellen leesbaar te houden in het resulterende `.txt`‑bestand +* Het bestand opslaan en de output verifiëren + +Geen externe scripts, geen mysterieuze command‑line‑tools—alleen pure Java‑code die je in elk Maven‑ of Gradle‑project kunt plaatsen. + +> **Waarom zou je het doen?** Platte‑tekstbestanden zijn lichtgewicht, versie‑controlevriendelijk en perfect voor zoek‑indexering of downstream verwerkings‑pijplijnen. Als je ooit hebt geprobeerd een Word‑bestand te `cat`en en alleen onzin kreeg, lost deze tutorial dat probleem op. + +## Export docx naar txt – Overzicht + +Voordat we in de code duiken, laten we de terminologie verduidelijken. **Export docx to txt** betekent het nemen van een Microsoft Word `.docx`‑pakket en het schrijven van de tekstuele inhoud naar een simpel `.txt`‑bestand. In tegenstelling tot een PDF‑conversie verwijdert een tekst‑export de opmaak, maar kan wel regeleinden, alinea‑markeringen en—als je het goed configureert—Unicode‑tekens zoals emoji’s, accenten of Aziatische scripts behouden. + +Aspose.Words maakt dit moeiteloos omdat het het Word‑bestandsformaat abstraheert en een `TxtSaveOptions`‑klasse biedt waarin je de codering, tabelverwerking en meer kunt bepalen. + +### Vereisten + +* Java 11 of nieuwer (de API werkt met Java 8+, maar we gaan uit van een recente JDK) +* Aspose.Words for Java JAR (beschikbaar via Maven Central) +* Een voorbeeld `unicode.docx`‑bestand met diverse Unicode‑tekens—bijvoorbeeld “こんにちは”, “😊”, en een eenvoudige tabel + +Als je die hebt, laten we beginnen. + +## Stap 1: Laad het DOCX‑bestand (Convert docx to text) + +Het eerste wat je moet doen is het bron‑document in het geheugen lezen. Hier begint het **convert docx to text**‑proces officieel. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Waarom dit belangrijk is:* `Document` is de weergave van een Word‑bestand in Aspose.Words. Door het te laden krijg je toegang tot al zijn alinea’s, tabellen en zelfs verborgen elementen. Als het bestand niet wordt gevonden, gooit Aspose een duidelijke `FileNotFoundException`, zodat je meteen weet wat er mis ging. + +## Stap 2: Configureer TxtSaveOptions voor Unicode (Plain text unicode) + +Platte‑tekstbestanden zijn alleen maar byte‑stromen, dus moet je Java vertellen welke tekenset te gebruiken. UTF‑8 is de de‑facto standaard voor **plain text unicode** omdat het elk Unicode‑codepunt kan coderen. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro tip:** Als je de `setEncoding`‑aanroep overslaat, gebruikt Aspose de standaard‑charset van het platform, die op veel Windows‑machines Windows‑1252 is. Die standaard zal stilletjes tekens zoals “ß” of “—” weglaten. + +## Stap 3: Behoud tabelindeling (Optioneel, maar handig voor leesbaarheid) + +Wanneer je **export word as txt** uitvoert, worden tabellen meestal afgevlakt tot één regel tekst, waardoor ze onleesbaar worden. Aspose.Words biedt een eenvoudige vlag om de visuele structuur te behouden. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Wanneer te gebruiken:* Als je bron‑DOCX facturen, roosters of andere raster‑achtige gegevens bevat, zal het inschakelen van `PreserveTableLayout` tabs en regeleinden invoegen zodat het resulterende bestand nog steeds op een tabel lijkt. Als je dit niet nodig hebt, kun je de regel weglaten en een compactere output krijgen. + +## Stap 4: Sla het document op als platte‑tekst (Export word as txt) + +Nu is het zware werk gedaan—schrijf gewoon de bytes naar schijf. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Het uitvoeren van het programma genereert `plain.txt` in dezelfde map. Open het met elke teksteditor (Notepad++, VS Code, zelfs `cat` in een terminal) en je ziet: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Let op hoe de Japanse groet en de smiley behouden bleven, en de tabel zijn kolommen behield dankzij `PreserveTableLayout`. Dat is de essentie van een nette **export docx to txt**. + +## Stap 5: Verifieer de output (Convert word to text sanity check) + +Een snelle sanity‑check voorkomt stilzwijgende gegevensverlies. Hier zijn een paar manieren om te bevestigen dat je echt **convert word to text** correct uitvoert: + +1. **Checksum‑vergelijking** – bereken een SHA‑256‑hash van het `.txt`‑bestand vóór en na een round‑trip‑conversie (txt → docx → txt) om stabiliteit te waarborgen. +2. **Zoek naar Unicode‑markeringen** – gebruik `grep` of de IDE‑zoek‑in‑bestand om tekens zoals “😊” te vinden. +3. **Openen in meerdere editors** – sommige oude Windows‑Notepad‑versies interpreteren UTF‑8 zonder BOM nog steeds verkeerd; het openen van het bestand in VS Code bevestigt de juiste codering. + +Als een van deze controles faalt, controleer dan dubbel of `saveOptions.setEncoding(StandardCharsets.UTF_8)` aanwezig is en dat je bron‑DOCX daadwerkelijk Unicode‑tekst bevat. + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Ontbrekende tekens** | Standaard systeem‑charset (bijv. Windows‑1252) laat niet‑ASCII‑tekens vallen. | Stel expliciet UTF‑8 in via `saveOptions.setEncoding`. | +| **Tabellen worden één regel** | `PreserveTableLayout` staat standaard op `false`. | Roep `saveOptions.setPreserveTableLayout(true)` aan. | +| **Bestand niet gevonden** | Verkeerd pad of ontbrekende leesrechten. | Gebruik absolute paden of `Paths.get(...)` met juiste foutafhandeling. | +| **Prestatie‑vertraging bij grote documenten** | Het volledige document in het geheugen laden. | Stream het document in delen met `DocumentBuilder` als je alleen specifieke secties nodig hebt. | + +## Bonus: Meerdere DOCX‑bestanden in één batch exporteren + +Als je **convert docx to text** voor een hele map moet uitvoeren, wikkel de logica dan in een lus: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Dit fragment **export docx to txt** voor elk bestand in de map, waardoor je uren handmatig werk bespaart. + +## Conclusie + +Je hebt zojuist geleerd hoe je **export docx to txt** met Java kunt uitvoeren, waarbij elk Unicode‑teken intact blijft, tabellen leesbaar blijven en het hele proces herhaalbaar is. Door `TxtSaveOptions` voor UTF‑8 te configureren en eventueel tabelindelingen te behouden, kun je betrouwbaar **convert docx to text**, **convert word to text**, en **export word as txt** uitvoeren voor elke downstream‑workflow. + +Klaar voor de volgende uitdaging? Probeer te exporteren naar andere platte‑tekstformaten zoals markdown (`.md`) of CSV, of verken de PDF‑conversiemogelijkheden van Aspose.Words. Dezelfde principes—expliciete codering, behoud van lay-out en grondige verificatie—gelden overal. + +Veel plezier met coderen, en moge je tekstbestanden altijd Unicode‑rijk blijven! + +--- + +![Diagram dat de export docx naar txt pipeline toont](/images/export-docx-to-txt-pipeline.png){alt="export docx naar txt pipeline diagram"} + +## Gerelateerde tutorials + +- [Docx naar Txt converteren](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – DOCX naar PDF converteren in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Docx naar markdown converteren – Wiskundige vergelijkingen exporteren naar LaTeX met Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/dutch/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..d4fcd325aa --- /dev/null +++ b/words/dutch/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-05-26 +description: Sla document op als PDF met Aspose.Words Java en voeg toegankelijkheid + toe aan de PDF. Leer hoe je docx naar PDF converteert, horizontale regels tagt en + zorgt voor PDF/UA‑2‑naleving. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: nl +og_description: Document opslaan als PDF met Aspose.Words Java en toegankelijkheid + aan de PDF toevoegen. Stap‑voor‑stap gids om docx naar PDF te converteren en horizontale + regels te taggen voor PDF/UA‑2‑conformiteit. +og_title: Document opslaan als PDF met Aspose.Words Java – Toegankelijkheid eenvoudig + gemaakt +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Document opslaan als PDF met Aspose.Words Java – Volledige toegankelijkheidsgids +url: /nl/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Document opslaan als PDF met Aspose.Words Java – Volledige Toegankelijkheidsgids + +Heb je je ooit afgevraagd hoe je **document opslaan als PDF** kunt doen terwijl het toegankelijk blijft voor schermlezers? Je bent niet de enige. Veel ontwikkelaars moeten *docx naar pdf converteren* en toch voldoen aan de PDF/UA‑2-standaarden, vooral wanneer de bron horizontale regels bevat die correct getagd moeten worden. In deze tutorial lopen we de exacte stappen door om **document opslaan als PDF** te doen met Aspose.Words voor Java, automatisch **toegankelijkheid aan PDF toevoegen**, en ervoor te zorgen dat elke horizontale regel **getagd** wordt als een artefact. + +We beginnen met een schoon Java‑project, laden een DOCX die al horizontale regels bevat, configureren de PDF‑opslaan‑opties voor PDF/UA‑2‑naleving, en schrijven uiteindelijk een volledig toegankelijke PDF weg. Aan het einde kun je **document opslaan als pdf** met het vertrouwen dat het voldoet aan toegankelijkheidscontroles. + +## Vereisten + +Voordat we beginnen, zorg ervoor dat je het volgende hebt: + +- Java 8 of nieuwer geïnstalleerd (de tutorial is getest op JDK 17). +- Maven 3.6+ (of Gradle als je dat verkiest) om afhankelijkheden te beheren. +- Een geldige Aspose.Words voor Java‑licentie (de gratis proefversie werkt, maar een licentie verwijdert evaluatiewatermerken). +- Een DOCX‑bestand (`input.docx`) dat minstens één horizontale regel bevat — denk aan een eenvoudige scheidingslijn die je in Word zou toevoegen. + +> **Pro tip:** Als je geen DOCX bij de hand hebt, maak dan gewoon een nieuw Word‑document, typ een paar alinea's, voeg *Insert → Horizontal Line* toe, sla op als `input.docx` en plaats het in een map naar keuze. + +## Stap 1: Maven‑project opzetten + +Eerst maak je een nieuw Maven‑project (of voeg toe aan een bestaand project). De `pom.xml` heeft de Aspose.Words‑dependency nodig: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Waarom dit belangrijk is:** Het toevoegen van het `aspose-words`‑artifact is de eerste stap om *docx naar pdf te converteren*. Zonder dit herkent de compiler `Document`, `PdfSaveOptions` en andere cruciale klassen niet. + +## Stap 2: Laad de bron‑DOCX met horizontale regels + +Nu schrijven we een kleine Java‑klasse die de DOCX laadt. Hier begint het **tag horizontale regels**‑gedeelte — Aspose.Words behandelt een horizontale regel automatisch als een alinea met een rand, maar we laten de PDF/UA‑engine het taggen afhandelen. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Merk op dat we nog niets hebben opgeslagen — we **laden** alleen de DOCX, wat de eerste helft is van *docx naar pdf converteren*. Het `Document`‑object bevat nu alle Word‑inhoud, inclusief eventuele horizontale regels die je hebt ingevoegd. + +## Stap 3: PDF‑opslaan‑opties configureren voor PDF/UA‑2‑naleving + +De magie van **toegankelijkheid aan PDF toevoegen** zit in `PdfSaveOptions`. Door het nalevingsniveau in te stellen op `PDF_UA_2`, zal Aspose.Words: + +1. Structurele elementen taggen (koppen, tabellen, enz.). +2. Decoratieve elementen — zoals horizontale regels — markeren als *artefacten*, zodat schermlezers ze negeren. +3. De benodigde PDF/UA‑metadata invoegen. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Waarom naleving instellen?** Zonder `PDF_UA_2` kan de resulterende PDF nog leesbaar zijn, maar zal deze niet slagen voor geautomatiseerde toegankelijkheidsvalidaties. De **tag horizontale regels**‑vereiste wordt automatisch voldaan omdat PDF/UA ze als *artefacten* behandelt wanneer de nalevingsvlag aanstaat. + +## Stap 4: Document opslaan als PDF + +Nu slaan we eindelijk **document op als pdf** op. Deze ene regel doet het zware werk — het converteren van de DOCX, het toepassen van de toegankelijkheidstags, en het wegschrijven van het bestand naar schijf. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Voer de klasse uit (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) en je ziet een bevestigingsbericht. Open de resulterende `ua_compliant.pdf` in Adobe Acrobat en controleer **Bestand → Eigenschappen → Beschrijving → PDF/A, PDF/UA** — je zou “PDF/UA‑2” moeten zien staan. + +### Verwachte output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Open de PDF en je zult merken: + +- De documenttekst is selecteerbaar en doorzoekbaar. +- De horizontale lijn is onzichtbaar voor schermlezers (behandeld als een artefact). +- De PDF slaagt voor basis PDF/UA‑validatietools (bijv. PAC 3). + +## Stap 5: Toegankelijkheid verifiëren – Snelle checklist + +Hoewel Aspose.Words het grootste deel van het werk doet, is het goede praktijk om de output te verifiëren. + +| Controle | Hoe te verifiëren | +|----------|-------------------| +| **Documenttitel** | Open Acrobat → Bestand → Eigenschappen → Titelveld (moet overeenkomen met `pdfOptions.setTitle`). | +| **Artefact-tagging** | Gebruik de “Reading Order”‑tool van Acrobat. Horizontale regels moeten verschijnen als *Artefact* (grijs). | +| **Logische leesvolgorde** | Voer de “Accessibility Checker” uit in Acrobat; zorg dat er geen structurele fouten zijn. | +| **Getagde PDF** | In Acrobat, kijk onder het “Tags”‑paneel – je zou een hiërarchie moeten zien (Document → Sectie → Paragraaf, enz.). | +| **PDF/UA‑naleving** | Acrobat toont “PDF/UA‑2” onder het tabblad “Standards”. | + +Als een van deze controles faalt, controleer dan nogmaals of je de nieuwste Aspose.Words‑versie gebruikt en dat `setCompliance(PdfCompliance.PDF_UA_2)` correct is toegepast. + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +1. **Missing License** – De proefversie voegt een watermerk toe dat PDF/UA‑validatie kan breken. Pas je licentie vroeg toe in `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – Een `FileNotFoundException` stopt de conversie. Gebruik absolute paden of plaats de DOCX in de project‑root en verwijs ernaar met `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – PDF/UA‑ondersteuning werd toegevoegd in versie 22.9. Upgrade naar de nieuwste release om ontbrekende functies te vermijden. +4. **Horizontal Rule as Image** – Als je de lijn als afbeelding hebt ingevoegd in plaats van als een native Word‑horizontale regel, behandelt Aspose het als een gewone afbeelding, niet als een artefact. Vervang de afbeelding door Word’s ingebouwde *Horizontal Line* voor correcte tagging. + +## De oplossing uitbreiden – Wat als je meer nodig hebt? + +- **Aangepaste tags**: Als je andere decoratieve elementen hebt (bijv. decoratieve iconen), kun je ze handmatig markeren als artefacten met `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Meerdere documenten**: Loop over een map met DOCX‑bestanden en batch‑converteer ze, waarbij je dezelfde `PdfSaveOptions`‑instantie hergebruikt voor prestaties. +- **Een taaltag toevoegen**: Voor meertalige PDF‑s, stel `pdfOptions.setLanguage("en-US")` in om assistieve technologieën te helpen de juiste stem te kiezen. + +## Volledig werkend voorbeeld (Alle code samen) + +Hieronder staat het volledige, uitvoerbare Java‑programma. Kopieer‑en‑plak het in je IDE, pas de paden aan, en start het. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Voer het uit, open de gegenereerde PDF, en je hebt een schoon, toegankelijk bestand klaar voor distributie. + +## Conclusie + +We hebben zojuist laten zien hoe je **document opslaan als pdf** kunt doen met Aspose.Words voor Java terwijl je automatisch **toegankelijkheid aan pdf toevoegt** en **horizontale regels tagt** als artefacten. De belangrijkste punten: + +- Gebruik `PdfSaveOptions` met `PDF_UA_2`‑naleving om te voldoen aan toegankelijkheidsnormen. +- Het laden van een DOCX en het aanroepen van `doc.save(..., pdfOptions)` is alles wat je nodig hebt om **docx naar pdf te converteren**. +- Horizontale regels worden voor je afgehandeld — geen extra code nodig, waardoor de **tag horizontale regels**‑vereiste wordt vervuld. +- De aanpak is volledig **aspose convert docx pdf**‑compliant, werkt met de nieuwste bibliotheekversie, en produceert een validatie‑klare PDF. + +Klaar voor de volgende uitdaging? Probeer aangepaste metadata toe te voegen, lettertypen in te sluiten, of batch‑verwerking van een hele map met DOCX‑bestanden. Elk van die uitbreidingen bouwt voort op dezelfde basis die we hier hebben gelegd. + +Heb je vragen over PDF/UA‑naleving, licenties, of het omgaan met andere Word‑elementen? Laat een reactie achter of raadpleeg de officiële documentatie van Aspose — er is een schat aan voorbeelden om te verkennen. Veel programmeerplezier, en geniet van het maken van toegankelijke PDF's! + +![document opslaan als pdf met Aspose.Words Java – toegankelijk PDF‑voorbeeld](placeholder-image.png "document opslaan als pdf met Aspose.Words Java – toegankelijk PDF‑voorbeeld") + + +## Gerelateerde tutorials + +- [Hoe document opslaan als pdf met Aspose.Words voor Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Hoe Word naar PDF converteren met Aspose.Words voor Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – DOCX naar PDF converteren in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/dutch/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..6358846b34 --- /dev/null +++ b/words/dutch/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Sla Word op als markdown en ontdek hoe je wiskundige vergelijkingen kunt + exporteren naar LaTeX met Aspose.Words voor Java. Converteer Word‑vergelijkingen + naar LaTeX in slechts een paar regels. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: nl +og_description: Sla Word op als markdown en leer hoe je wiskundige vergelijkingen + kunt exporteren naar LaTeX met Aspose.Words voor Java. Een volledige, uitvoerbare + gids. +og_title: Sla woord op als markdown – Exporteer wiskunde naar LaTeX met Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Word opslaan als markdown – Exporteer wiskunde naar LaTeX met Java +url: /nl/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Opslaan van Word als markdown – Export Math to LaTeX with Java + +Heb je ooit **word als markdown opslaan** moeten, maar was je bang dat je vergelijkingen een warboel zouden worden? Je bent niet de enige. In deze gids lopen we stap voor stap door **hoe je wiskunde exporteert** vanuit een `.docx`‑bestand direct naar LaTeX, terwijl de rest van het document schone Markdown wordt. + +We behandelen alles, van het instellen van de Aspose.Words‑bibliotheek tot het verifiëren van het uiteindelijke `out.md`‑bestand. Aan het einde kun je **word‑vergelijkingen naar LaTeX converteren** met één enkele methode‑aanroep, en begrijp je de kleine nuances die de conversie betrouwbaar maken. + +--- + +## Wat je nodig hebt + +- **Java 8+** – de code draait op elke recente JDK. +- **Aspose.Words for Java** – de Maven/Gradle‑dependency of de JAR als je handmatige installatie verkiest. +- Een Word‑document (`math.docx`) dat minstens één Office‑Math‑vergelijking bevat. +- Een IDE of de gewone `javac`/`java`‑commandoregel – wat je ook prettig vindt. + +Als je die al hebt, prima. Zo niet, dan laat de volgende sectie precies zien hoe je de bibliotheek in je project krijgt. + +--- + +## Opslaan van Word als markdown – Stap 1: Voeg Aspose.Words toe aan je project + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose biedt een gratis tijdelijke licentie voor testen. Plaats het `license.xml`‑bestand in je resources‑map en roep `License license = new License(); license.setLicense("license.xml");` aan voordat je een document laadt. + +Zodra de afhankelijkheid is opgelost, ben je klaar om de conversiecode te schrijven. + +--- + +## Hoe wiskundige vergelijkingen exporteren naar LaTeX + +Het zware werk wordt gedaan door `MarkdownSaveOptions`. Door zijn `OfficeMathExportMode` te wijzigen naar `LATEX`, wordt elk Office‑Math‑object gerenderd als een LaTeX‑fragment in de Markdown‑output. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Waarom dit werkt + +- **`Document`** is het toegangspunt van Aspose; het abstraheert het `.docx`‑bestand en geeft je toegang tot elke node, inclusief vergelijkingen. +- **`MarkdownSaveOptions`** vertelt de bibliotheek *hoe* je de output wilt. Het standaardgedrag is om vergelijkingen als afbeeldingen te renderen, wat het doel van een tekst‑gebaseerd formaat ondermijnt. +- **`OfficeMathExportMode.LATEX`** dwingt de engine om elke `OfficeMath`‑node te vertalen naar het LaTeX‑equivalent, dat Markdown‑parsers (zoals GitHub of Jekyll) kunnen weergeven wanneer gecombineerd met een MathJax‑plugin. + +--- + +## Word‑vergelijkingen naar LaTeX converteren – Stap 2: Verifieer de Markdown‑output + +Na het uitvoeren van het programma, open `out.md`. Je zou iets moeten zien zoals dit: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Opmerking:** De LaTeX‑fragmenten worden omgeven door `$…$` voor inline‑wiskunde en `$$…$$` voor blok‑wiskunde. Dit is de standaardsyntaxis die de meeste statische site‑generators begrijpen wanneer MathJax is ingeschakeld. + +Als je de vergelijkingen alleen inline wilt houden, kun je de `MarkdownSaveOptions` verder aanpassen: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx naar markdown latex – Stap 3: Randgevallen & Veelvoorkomende valkuilen + +| Situatie | Waar op te letten | Oplossing | +|-----------|-------------------|-----| +| **Complexe geneste vergelijkingen** | Aspose kan extra accolades `{}` outputten die sommige parsers letterlijk behandelen. | Verwerk de Markdown na afloop met een eenvoudige regex om `{{` → `{` samen te voegen. | +| **Ontbrekende MathJax op de doelsite** | Vergelijkingen verschijnen als ruwe LaTeX‑code. | Voeg `` toe aan je HTML‑template. | +| **Grote documenten** | Het geheugenverbruik stijgt omdat het volledige document in één keer wordt geladen. | Gebruik `LoadOptions.setLoadFormat(LoadFormat.DOCX)` en overweeg om pagina's in batches te verwerken als je een `OutOfMemoryError` krijgt. | +| **Licentie niet ingesteld** | Je krijgt een waarschuwing en de output kan een watermerk bevatten. | Laad de licentie vroeg in `main` zoals getoond in de Maven‑tip hierboven. | + +--- + +## Opslaan van Word als markdown – Volledig werkend voorbeeld + +Hieronder staat een zelfstandige klasse die je kunt kopiëren‑plakken in elk Java‑project. Vervang gewoon `YOUR_DIRECTORY` door het pad naar je bestanden. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Voer het programma uit (`java MathToLatexMarkdown`) en je ziet het console‑bericht dat succes bevestigt. Open `out.md` in een editor – de vergelijkingen moeten schone LaTeX‑fragmenten zijn, klaar om te renderen. + +--- + +## Verwachte output‑snapshot + +![output van word opslaan als markdown met LaTeX‑vergelijkingen](https://example.com/images/markdown-latex-output.png "output van word opslaan als markdown met LaTeX‑vergelijkingen") + +*De afbeelding toont een fragment van de gegenereerde Markdown waarin de vergelijking `\int_{a}^{b} f(x)\,dx` is omgeven door `$$`.* + +--- + +## Conclusie + +We hebben zojuist laten zien hoe je **word als markdown opslaat** terwijl je elke Office‑Math‑vergelijking behoudt als native LaTeX. De cruciale stap was het configureren van `MarkdownSaveOptions` met `OfficeMathExportMode.LATEX`, waardoor een typische Word‑naar‑Markdown‑pipeline verandert in een volledig wiskunde‑bewust conversiegereedschap. + +Nu kun je: + +1. **Hoe je wiskunde exporteert** vanuit elk `.docx` zonder verlies van nauwkeurigheid. +2. **Word‑vergelijkingen naar LaTeX converteren** voor statische site‑generators, documentatie of academische blogs. +3. Breid de aanpak uit om veel bestanden in batch te verwerken, te integreren met CI‑pipelines, of zelfs een kleine webservice te bouwen. + +Als je nieuwsgierig bent naar de volgende stap, probeer dit dan te combineren met **docx naar markdown latex** voor document met veel afbeeldingen, of verken Aspose’s `HtmlSaveOptions` voor een web‑klare HTML‑versie. De mogelijkheden zijn eindeloos—experimenteer, breek dingen, en deel vervolgens je bevindingen met de community. + +Heb je vragen of een lastige vergelijking die niet naar verwachting renderde? Laat een reactie achter hieronder, en happy coding! + +## Gerelateerde tutorials + +- [Hoe LaTeX exporteren vanuit Word: DOCX naar Markdown converteren & opslaan als PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Docx naar markdown converteren – Math‑vergelijkingen exporteren naar LaTeX met Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Hoe Word naar PDF converteren met Aspose.Words voor Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/dutch/java/document-loading-and-saving/_index.md index 16d844aa73..e7248b68e2 100644 --- a/words/dutch/java/document-loading-and-saving/_index.md +++ b/words/dutch/java/document-loading-and-saving/_index.md @@ -134,6 +134,10 @@ Leer hoe je documenten opslaat als tekstbestanden in Aspose.Words for Java. Volg Leer hoe je documentformaten detecteert in Java met Aspose.Words. Identificeer DOC, DOCX en meer. Organiseer bestanden efficiënt. ### [Beschadigde docx herstellen – Complete gids voor reparatie en verwerking van documenten](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +Leer hoe je een beschadigd DOCX‑bestand herstelt en veilig verwerkt met Aspose.Words for Java. + +### [Open beschadigd Word‑document – herstelmodus instellen in Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Leer hoe je een beschadigd Word‑document opent en de herstelmodus configureert met Aspose.Words for Java. ## Veelgestelde vragen diff --git a/words/dutch/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/dutch/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..6271b3f048 --- /dev/null +++ b/words/dutch/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: Open een beschadigd Word‑document in Java met Aspose.Words. Leer hoe + je de herstelmodus instelt en beschadigde Word‑bestanden betrouwbaar herstelt. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: nl +og_description: Open een beschadigd Word‑document in Java met Aspose.Words. Deze gids + laat zien hoe je herstelmodus instelt en beschadigde Word‑bestanden efficiënt herstelt. +og_title: Open beschadigd Word‑document – Stel herstelmodus in Java in +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Open beschadigd Word‑document – Stel herstelmodus in Java +url: /nl/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Open Beschadigd Word-document – Stel Herstelmodus in Java + +Heb je ooit geprobeerd een beschadigd Word-document te openen en zag je het programma vastlopen door een uitzondering? Je bent niet de enige—die kapotte .docx‑bestanden kunnen een echte hoofdpijn zijn. Het goede nieuws is dat Aspose.Words for Java je fijnmazige controle geeft zodat je **open corrupted word document** kunt openen zonder dat de app crasht, en zelfs kunt bepalen of je waarschuwingen, stille herstel of een harde afwijzing wilt. + +In deze tutorial lopen we het volledige proces door: van het maken van de juiste `LoadOptions`, tot het kiezen van de juiste **set recovery mode**‑waarde, en uiteindelijk bevestigen dat het document inderdaad is geladen. Aan het einde weet je **how to recover corrupted word file** programmatically, zonder handmatig copy‑paste. + +> **Wat je nodig hebt** +> * Java 8 of nieuwer (de API werkt ook met Java 11) +> * Aspose.Words for Java 23.9 (of de nieuwste versie) +> * Een voorbeeld van een beschadigd .docx‑bestand—hernoem gewoon een geldig bestand om corruptie te simuleren als je er geen bij de hand hebt + +Laten we beginnen. + +## Open Beschadigd Word-document – Stapsgewijs Overzicht + +Hieronder staat de high‑level flow die we gaan implementeren: + +1. **Create `LoadOptions`** – dit object vertelt Aspose.Words hoe te handelen wanneer het problemen tegenkomt. +2. **Set recovery mode** – kies `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` of `REJECT_CORRUPTED`. +3. **Load the document** – laad het document met de geconfigureerde opties. +4. **Verify** – controleer of het laden geslaagd is (bijv. print paginatelling). + +Elke stap wordt in detail uitgelegd, met code‑fragmenten die je direct kunt copy‑paste in je IDE. + +## Stel Herstelmodus in voor Verschillende Scenario's + +Aspose.Words definieert drie herstelstrategieën binnen `LoadOptions.RecoveryMode`: + +| Modus | Gedrag | Wanneer te gebruiken | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | Probeert het document te laden, maar geeft eventuele problemen weer als waarschuwingen in de console. | Je wilt zien *wat* er mis ging zonder af te breken. | +| `RECOVER_WITHOUT_WARNINGS` | Repareert stilzwijgend wat mogelijk is en onderdrukt waarschuwingen. | Productieomgevingen waar logs schoon moeten blijven. | +| `REJECT_CORRUPTED` | Gooit een uitzondering op het moment dat corruptie wordt gedetecteerd. | Strikte validatie‑pipelines die snel moeten falen. | + +Het kiezen van de juiste modus is de essentie van **set recovery mode** correct. In de meeste debug‑sessies is `RECOVER_WITH_WARNINGS` de ideale keuze omdat het je precies vertelt welke delen zijn gerepareerd. + +## Hoe een Beschadigd Word‑bestand Herstellen met Aspose.Words + +Hieronder staat een **volledig, uitvoerbaar Java‑programma** dat het hele proces demonstreert. Voel je vrij om het in een `RecoveryModeDemo.java`‑bestand te plaatsen, het pad aan te passen en uit te voeren. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Waarom elke regel belangrijk is + +* **`LoadOptions loadOptions = new LoadOptions();`** – zonder dit object gebruikt Aspose.Words de standaard herstelmodus, die *corrupt* bestanden *afwijst*. Het aanmaken geeft je de mogelijkheid om dat gedrag te wijzigen. +* **`setRecoveryMode(...)`** – dit is de **set recovery mode**‑aanroep die bepaalt of waarschuwingen verschijnen, verborgen blijven, of een uitzondering veroorzaken. +* **`new Document(path, loadOptions);`** – de constructor accepteert de `LoadOptions` die we zojuist hebben geconfigureerd, zodat de bibliotheek vanaf het begin weet hoe het het kapotte bestand moet behandelen. +* **`doc.getPageCount()`** – een snelle sanity‑check. Als het document laadt en een paginatelling teruggeeft, heb je succesvol **how to recover corrupted word file**. +* **`doc.save(...)`** – optioneel maar handig; je kunt de gerepareerde versie terug naar schijf schrijven voor later gebruik. + +## Veelvoorkomende Randgevallen Afhandelen + +### 1. Bestand Niet Gevonden + +Als het pad onjuist is, gooit `Document` een `FileNotFoundException`. Plaats het laden in een try‑catch‑blok en log een vriendelijke boodschap: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Onherstelbare Corruptie + +Zelfs met `RECOVER_WITH_WARNINGS` zijn sommige structuren onherstelbaar. In dat geval laadt Aspose.Words nog steeds wat het kan, maar zie je waarschuwingen zoals “Cannot read paragraph properties”. Let op de console‑output; die waarschuwingen wijzen vaak op ontbrekende secties die je handmatig moet reconstrueren. + +### 3. Grote Bestanden en Prestaties + +Herstel voegt een kleine overhead toe omdat de bibliotheek het bestand twee keer parseert—eenmaal om problemen te detecteren, nogmaals om te herbouwen. Voor documenten van meerdere gigabytes, overweeg het bestand te streamen of de JVM‑heap te vergroten (`-Xmx2g`) om `OutOfMemoryError` te voorkomen. + +## Pro‑tips – Herstel Robuust Maken + +* **Log warnings to a file** – redirect `System.err` naar een logger zodat je een audit‑trail hebt van wat is gerepareerd. +* **Validate after recovery** – voer `doc.updatePageLayout();` uit en controleer vervolgens opnieuw de paginatelling; soms verandert de lay-out na het repareren van kapotte secties. +* **Automate batch recovery** – plaats de demo in een lus die een map met corrupte bestanden verwerkt, met telkens dezelfde `LoadOptions`. + +## Conclusie + +Je weet nu precies **how to recover corrupted word file** met Aspose.Words for Java. Door een `LoadOptions`‑instantie te maken, **set recovery mode** in te stellen op de strategie die bij jouw scenario past, en het document met die opties te laden, kun je veilig **open corrupted word document** zonder je applicatie te laten crashen. De voorbeeldcode hierboven is een volledige, kant‑klaar‑te‑run oplossing die de paginatelling print en zelfs een opgeschoonde kopie opslaat. + +Wat is het volgende? Probeer de herstelmodus te wisselen naar `RECOVER_WITHOUT_WARNINGS` en vergelijk de console‑output, of experimenteer met het laden van versleutelde documenten (je moet een wachtwoord opgeven via + +## Gerelateerde Tutorials + +- [Aspose.Words Java: Uitgebreide Gids voor Word Documentverwerking](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Hoe Word naar PDF Converteren met Aspose.Words voor Java](/words/english/java/document-converting/using-document-converting/) +- [Hoe Twee Word-bestanden Vergelijken met Aspose.Words voor Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/dutch/java/document-styling/_index.md index 9f15351d08..e9467c17bf 100644 --- a/words/dutch/java/document-styling/_index.md +++ b/words/dutch/java/document-styling/_index.md @@ -43,6 +43,8 @@ Leer hoe u documentthema's kunt aanpassen met Aspose.Words voor Java. Deze uitge Leer hoe u watermerken kunt toepassen en paginaconfiguraties kunt instellen met Aspose.Words voor Java. Een uitgebreide handleiding met broncode. ### [Stijl van documentkoptekst en -voettekst](./document-header-footer-styling/) Leer hoe je documentkopteksten en -voetteksten kunt stylen met Aspose.Words voor Java in deze gedetailleerde handleiding. Inclusief stapsgewijze instructies en broncode. +### [Standaardlettertype-instellingen instellen in Aspose.Words voor Java – Complete gids](./set-default-font-settings-in-aspose-words-for-java-complete/) +Leer hoe u standaardlettertype-instellingen configureert in Aspose.Words voor Java met voorbeeldcode. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/dutch/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..d314db635d --- /dev/null +++ b/words/dutch/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Stel standaard lettertype‑instellingen in Aspose.Words voor Java in en + leer hoe je lettertype‑instellingen kunt configureren en ontbrekende lettertypen + kunt detecteren in slechts een paar regels code. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: nl +og_description: Stel standaard lettertype‑instellingen in Aspose.Words voor Java in, + leer hoe je lettertype‑instellingen kunt configureren en ontbrekende lettertypen + snel en betrouwbaar kunt detecteren. +og_title: Standaardlettertype‑instellingen instellen in Aspose.Words voor Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Standaardlettertype‑instellingen instellen in Aspose.Words voor Java – Complete + gids +url: /nl/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Standaard lettertype‑instellingen instellen in Aspose.Words voor Java – Complete gids + +Heb je je ooit afgevraagd hoe je **standaard lettertype‑instellingen** kunt **instellen** bij het laden van een Word‑document met Aspose.Words voor Java? Je bent niet de enige. Ontbrekende glyphs kunnen een verzorgde rapportage veranderen in een onleesbare rommel, en het vroegtijdig opvangen van die lettertype‑substitutie‑waarschuwingen bespaart uren aan debuggen. + +In deze tutorial lopen we een beknopt, end‑to‑end voorbeeld door dat **standaard lettertype‑instellingen** **instelt**, je laat zien hoe je **lettertype‑instellingen** programmatisch **instelt**, en een betrouwbare manier demonstreert om **ontbrekende lettertypen** te **detecteren** voordat ze je lay‑out breken. + +--- + +## Wat je zult leren + +- Hoe je een `LoadOptions`‑object maakt met een verse `FontSettings`‑instantie. +- Hoe je een waarschuwingslistener toevoegt die **ontbrekende lettertypen** **detecteert** tijdens het laden van het document. +- Hoe je een DOCX‑bestand laadt terwijl de listener stilletjes alle substituties rapporteert. +- Tips voor het aanpassen van fallback‑lettertypen en het afhandelen van randgevallen in productie. + +Geen extra bibliotheken, geen obscure configuratiebestanden—alleen plain Java en Aspose.Words. + +--- + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +1. **Aspose.Words for Java** (versie 23.10 of nieuwer) op je classpath. +2. Een Java 17 (of later) ontwikkel‑kit – elke moderne JDK werkt. +3. Een DOCX‑bestand dat opzettelijk een lettertype gebruikt dat je niet geïnstalleerd hebt (bijv. *“MissingFont.ttf”*). + +Als je de Aspose‑JAR mist, haal deze dan op uit de officiële Maven‑repository: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Dat is alles—er hoeven geen extra lettertypen geïnstalleerd te worden voor deze demo. + +--- + +## Stap 1: Maak LoadOptions en **Standaard lettertype‑instellingen instellen** + +Het eerste wat we nodig hebben is een schoon `LoadOptions`‑object dat Aspose vertelt hoe te handelen wanneer het onbekende lettertypen tegenkomt. Door `setFontSettings(new FontSettings())` aan te roepen, **stellen we standaard lettertype‑instellingen** in die beginnen met een lege fallback‑lijst. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Waarom dit belangrijk is:** +> Wanneer je geen lettertypen expliciet configureert, valt Aspose terug op de standaardcollectie van het systeem, wat ontbrekende‑lettertype‑problemen kan verbergen. Door te beginnen met een verse `FontSettings`‑instantie krijg je volledige controle over welke lettertypen als geldig worden beschouwd. + +--- + +## Stap 2: Voeg een waarschuwingslistener toe om **ontbrekende lettertypen te detecteren** + +Aspose genereert een `WarningInfo`‑object voor elke substitutie die het uitvoert. Door te luisteren naar `WarningType.FONT_SUBSTITUTION` kunnen we **ontbrekende lettertypen** detecteren zodra het document wordt geparseerd. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro tip:** De listener draait op dezelfde thread die het document laadt, dus er is praktisch geen prestatie‑penalty. Als je waarschuwingen later wilt analyseren, plaats ze dan in een `List` in plaats van direct af te drukken. + +--- + +## Stap 3: Laad het document met de geconfigureerde opties + +Nu we **lettertype‑instellingen** hebben **ingesteld** en een listener hebben voorbereid, laden we simpelweg het bestand. Elk ontbrekend lettertype activeert onze callback onmiddellijk. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Als het bronbestand een lettertype verwijst dat niet geïnstalleerd is, zie je een output vergelijkbaar met: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Die regel vertelt je precies welk lettertype ontbrak en welke fallback werd gebruikt—perfect voor logging of gebruikersfeedback. + +--- + +## Stap 4: Ga door met normale verwerking (optioneel) + +Op dit punt is het document volledig geladen, en kun je doorgaan met elke bewerking die je wilt—bewerken, converteren naar PDF, of tekst extraheren. De waarschuwingslistener heeft zijn taak al voltooid, dus extra controles zijn niet nodig. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Wat als je een aangepaste fallback wilt?** +> In plaats van de `FontSettings` leeg te laten, kun je specifieke lettertypen toevoegen: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Nu wordt elk ontbrekend lettertype vervangen door *Times New Roman*—een betrouwbare keuze voor de meeste westerse documenten. + +--- + +## Visueel overzicht + +![Diagram dat laat zien hoe je standaard lettertype‑instellingen instelt in Aspose.Words voor Java](image.png "Diagram van de stroom voor het instellen van standaard lettertype‑instellingen") + +*Alt‑tekst: stroomdiagram voor het instellen van standaard lettertype‑instellingen in Aspose.Words voor Java.* + +--- + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Valkuil | Waarom het gebeurt | Oplossing | +|---------|--------------------|-----------| +| **Vergeten `setFontSettings` aan te roepen** | Aspose gebruikt de systeem‑standaarden, waardoor ontbrekende lettertypen verborgen blijven. | Maak altijd een nieuwe `FontSettings`‑instantie aan en wijs deze toe aan `LoadOptions`. | +| **Listener niet geactiveerd** | Listener toegevoegd na het laden van het document. | Voeg de waarschuwingslistener *toe* vóór het aanroepen van `new Document(...)`. | +| **Pad‑typefout leidt tot `FileNotFoundException`** | Hard‑gecodeerd pad komt niet overeen met de hoofdlettergevoeligheid van het OS. | Gebruik `Paths.get("...").toAbsolutePath()` of configureer een relatief pad vanaf de project‑root. | +| **Meerdere ontbrekende lettertypen overspoelen logs** | Grote documenten kunnen tientallen waarschuwingen genereren. | Filter duplicaten of aggregeer berichten in een `Set` voordat je ze afdrukt. | + +--- + +## De oplossing uitbreiden + +Als je **lettertype‑instellingen** voor een hele applicatie moet **instellen**, overweeg dan een singleton `FontSettings` te maken en deze te hergebruiken in alle `LoadOptions`. Op die manier behoud je een consistente fallback‑strategie en vermijd je herhaaldelijke objectcreatie. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Nu kan elk deel van je codebase eenvoudig `FontConfig.getLoadOptions()` aanroepen en direct profiteren van dezelfde **standaard lettertype‑instellingen**‑logica. + +--- + +## Conclusie + +We hebben zojuist alles behandeld wat je nodig hebt om **standaard lettertype‑instellingen** in Aspose.Words voor Java **in te stellen**, **lettertype‑instellingen** programmatisch **in te stellen**, en **ontbrekende lettertypen** te **detecteren** voordat ze je output corrumperen. Het volledige, uitvoerbare voorbeeld staat in de code‑fragmenten hierboven, en je kunt het direct in je IDE plakken om de waarschuwingen in actie te zien. + +Volgende stappen? Probeer het fallback‑lettertype te wisselen, experimenteer met verschillende documentformaten (DOC, RTF, HTML), of integreer de waarschuwing‑collector in een monitoring‑dashboard. Hoe meer je met `FontSettings` speelt, hoe meer vertrouwen je krijgt dat je gegenereerde documenten er precies uitzien zoals bedoeld—geen verrassingen, geen kapotte glyphs. + +Heb je vragen of een lastig lettertype‑substitutie‑scenario? Laat een reactie achter hieronder, en happy coding! + +## Gerelateerde tutorials + +- [Lettertype fallback‑instellingen instellen](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Lettertype fallback‑instellingen instellen](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Lettertype fallback‑instellingen instellen](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/java/images-shapes/_index.md b/words/dutch/java/images-shapes/_index.md index 865f7bcf11..90b78dda6b 100644 --- a/words/dutch/java/images-shapes/_index.md +++ b/words/dutch/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Leer hoe u hoogwaardige miniaturen en bitmaps op maat van Word-documenten kunt g ### [Word-document maken in Java – Rechthoekvorm toevoegen met schaduweffect](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Leer hoe u een rechthoekige vorm met schaduweffect toevoegt aan een Word-document met Aspose.Words voor Java. +### [Rechthoekvorm maken in Java Word-document – Volledige stapsgewijze handleiding](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Leer hoe u een rechthoekige vorm toevoegt aan een Word-document met Aspose.Words voor Java. + ## Aanvullende bronnen - [Aspose.Words voor Java-documentatie](https://reference.aspose.com/words/java/) diff --git a/words/dutch/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/dutch/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..8e2cddb4e4 --- /dev/null +++ b/words/dutch/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Maak een rechthoekvorm in een Java Word‑document en pas een schaduweffect + toe. Leer hoe je een vormschaduw toevoegt, de schaduwafstand instelt en het bestand + opslaat. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: nl +og_description: Maak een rechthoekvorm in een Java‑Word‑document, pas een schaduweffect + toe, voeg een vormschaduw toe en stel de schaduwafstand in met Aspose.Words. +og_title: Rechthoekvorm maken in Java Word‑document – Complete gids +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Rechthoekvorm maken in Java Word‑document – Volledige stapsgewijze handleiding +url: /nl/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rechthoekvorm maken in Java Word-document – Volledige stapsgewijze handleiding + +Heb je ooit moeten **create rectangle shape** in een Java Word-document, maar wist je niet waar te beginnen? Je bent niet de enige—veel ontwikkelaars lopen tegen dit probleem aan bij het programmatisch genereren van rapporten of facturen. In deze tutorial lopen we stap voor stap door hoe je **create rectangle shape**, een gepolijste schaduw toepast, en de schaduwafstand fijn afstemt zodat het resultaat er professioneel uitziet. + +We gebruiken Aspose.Words for Java, een robuuste bibliotheek die je in staat stelt Word‑bestanden te manipuleren zonder Microsoft Office geïnstalleerd te hebben. Aan het einde van deze gids kun je **create word document java**‑projecten maken die **add shape shadow**, **apply shadow effect**, en **set shadow distance** met slechts een paar regels code. + +--- + +## Wat je gaat bouwen + +- Een nieuw `.docx`‑bestand met een cyaan rechthoek. +- Een realistische slagschaduw die vervaagd, gekanteld en gedeeltelijk transparant is. +- Volledige controle over de afstand van de schaduw tot de vorm. +- Een kant‑klaar Java‑klasse die je in elk Maven‑ of Gradle‑project kunt plaatsen. + +Geen externe tools, geen handmatige UI‑stappen—alleen pure code. + +--- + +## Vereisten + +- Java 8 of nieuwer (de code werkt op Java 11, Java 17, enz.). +- Aspose.Words for Java‑bibliotheek (beschikbaar via Maven Central). +- Een IDE of teksteditor naar keuze (IntelliJ IDEA, Eclipse, VS Code…). +- Basiskennis van Java‑syntaxis. + +Als je nog nooit een Maven‑dependency hebt toegevoegd, hier is het snelle fragment: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Laten we nu duiken. + +--- + +## Stap 1: Rechthoekvorm maken in een Word‑document + +Het eerste wat we nodig hebben is een leeg document en een `DocumentBuilder`. Beschouw de builder als een pen die in het document schrijft. Zodra we dat hebben, kunnen we **create rectangle shape** met één methode‑aanroep. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Waarom dit belangrijk is:** De `insertShape`‑methode maakt niet alleen de geometrie aan, maar voegt de vorm ook toe aan de interne collectie van het document, zodat je meteen kunt beginnen met het stijlen ervan. + +--- + +## Stap 2: Schaduweffect toepassen op de vorm + +Nu de rechthoek op de pagina staat, gaan we **apply shadow effect**. Schaduwen geven diepte, waardoor de vorm lijkt te zweven boven de pagina—een subtiele UI‑verbetering die de leesbaarheid in rapporten kan verhogen. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro‑tip:** Een vervaging van `5.0` ziet er natuurlijk uit voor de meeste op scherm weergegeven documenten. Als je afdrukt, wil je misschien een iets lagere waarde om een wazig uiterlijk te voorkomen. + +--- + +## Stap 3: Schaduwafstand instellen – Plaatsing fijn afstemmen + +Schaduwen gaan niet alleen over vervaging; ze hebben ook de juiste offset nodig. Hier komen we **set shadow distance** gebruiken. Een afstand van `7.0` punten creëert een bescheiden offset die merkbaar is maar niet overweldigend. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Wat als je een grotere offset nodig hebt?** Verhoog de waarde; verlaag deze voor een strakkere uitstraling. Onthoud dat de afstand samenwerkt met de hoek om de schaduw correct te positioneren. + +--- + +## Stap 4: Document opslaan – Werk bewaren + +Tot slot schrijven we het document naar schijf. Pas het pad aan naar waar je het bestand wilt opslaan. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Het uitvoeren van de klasse maakt een `shadow.docx`‑bestand dat, wanneer geopend in Microsoft Word of LibreOffice, een cyaan rechthoek toont met een zachte grijze schaduw onder een hoek van 45° en een offset van 7 punten. + +--- + +## Volledig werkend voorbeeld + +Hieronder staat de volledige, kant‑en‑klaar te kopiëren code. Het bevat alle imports, commentaren en de uiteindelijke `save`‑aanroep. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Verwachte output:** Open `shadow.docx` → je ziet een cyaan rechthoek gecentreerd op de eerste pagina, die een subtiele grijze schaduw werpt die iets naar rechtsonder is verschoven. De vervaging en transparantie van de schaduw geven het een natuurlijk licht effect. + +--- + +## Veelgestelde vragen & randgevallen + +### “Kan ik een andere vorm gebruiken?” + +Zeker. Vervang `ShapeType.RECTANGLE` door `ShapeType.OVAL`, `ShapeType.LINE`, of een andere ondersteunde enum. De rest van de schaduwcodel blijft gelijk. + +### “Wat als ik meerdere schaduwen nodig heb?” + +Aspose.Words ondersteunt slechts één schaduw per vorm. Om meerdere schaduwen te simuleren, dupliceer je de vorm, verschuif je elke kopie en pas je de transparantie aan. + +### “Is de schaduw zichtbaar in LibreOffice?” + +Ja—Aspose.Words schrijft standaard OOXML, dat LibreOffice correct interpreteert. De schaduw kan er iets anders uitzien door verschillende render‑engines, maar het effect blijft behouden. + +### “Hoe wijzig ik de schaduwkleur zodat deze bij mijn merk past?” + +Vervang simpelweg `java.awt.Color.GRAY` door een `java.awt.Color` naar keuze, bijvoorbeeld `new java.awt.Color(0, 120, 215)` voor een bedrijfsblauw. + +--- + +## Illustratie + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt‑tekst:* **create rectangle shape** illustratie die een cyaan rechthoek met een grijze slagschaduw in een Word‑document toont. + +--- + +## Samenvatting & volgende stappen + +We hebben behandeld hoe je **create rectangle shape**, **apply shadow effect**, **add shape shadow**, en **set shadow distance** kunt gebruiken met Aspose.Words for Java. De code is zelfstandig, draait op elke moderne JDK, en produceert een gepolijste `.docx`‑file klaar voor distributie. + +Wil je verder gaan? Probeer: + +- Tekst toevoegen binnen de rechthoek met `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Een tabel van vormen maken om een diagram te bouwen. +- Het document exporteren naar PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Elk van deze bouwt voort op dezelfde basisprincipes die we net hebben verkend, zodat je je comfortabel voelt bij het uitbreiden van het voorbeeld. + +--- + +## Slotgedachten + +Het beheersen van **create word document java**‑taken zoals vormen en schaduwen geeft je een enorm voordeel bij het automatiseren van rapporten, contracten of marketingmateriaal. De hier getoonde aanpak is helder, onderhoudbaar, en—het belangrijkste—gemakkelijk aan te passen voor elke gewenste visuele stijl. + +Probeer de code, pas de vervaging, hoek en afstand aan, en zie hoe je documenten van saai naar gepolijst veranderen. Als je tegen een probleem aanloopt, laat dan een reactie achter; ik help graag. + +Veel programmeerplezier! + +## Gerelateerde tutorials + +- [Word-document maken Java – Rechthoekvorm toevoegen met schaduweffect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Hoe formuliervelden maken en inhoud toevoegen met DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [PDF maken vanuit Word met barcode‑generatie – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/english/java/document-conversion-and-export/_index.md index 4226ad8934..5ad58c37ba 100644 --- a/words/english/java/document-conversion-and-export/_index.md +++ b/words/english/java/document-conversion-and-export/_index.md @@ -90,6 +90,9 @@ Learn how to format tables and apply table styles in Aspose.Words for Java. Expl ### [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Learn how to convert DOCX files to Markdown and export embedded Math equations as LaTeX using Aspose.Words for Java. +### [Save word as markdown – Export Math to LaTeX with Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Learn how to save a Word document as Markdown and export embedded Math equations to LaTeX using Aspose.Words for Java. + ### [Save Document as TXT – Quick Guide to Exporting Word Math](./save-document-as-txt-quick-guide-to-exporting-word-math/) Learn how to export Word documents as plain text files while preserving Math equations using Aspose.Words for Java. @@ -99,9 +102,21 @@ Learn how to convert DOCX files to PDF using Aspose.Words for Java with simple c ### [How to Embed Images in Markdown When Converting DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Learn how to embed images from DOCX files into Markdown during conversion using Aspose.Words for Java. +### [Embed Images as Base64 When Converting DOCX to Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Learn how to embed images as Base64 strings during DOCX to Markdown conversion using Aspose.Words for Java. + ### [Create Accessible PDF from DOCX – Complete Guide](./create-accessible-pdf-from-docx-complete-guide/) Learn how to generate accessible PDFs from DOCX files using Aspose.Words for Java, ensuring compliance with accessibility standards. +### [Save Document as PDF with Aspose.Words Java – Full Accessibility Guide](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Learn how to save a Word document as a fully accessible PDF using Aspose.Words for Java, covering tags, structure, and compliance. + +### [Create Accessible PDF in Java – Full Tagging Guide](./create-accessible-pdf-in-java-full-tagging-guide/) +Learn how to generate fully tagged, accessible PDFs in Java with Aspose.Words, covering tags, structure, and compliance. + +### [Export docx to txt with Java – Complete Programming Guide](./export-docx-to-txt-with-java-complete-programming-guide/) +Learn how to export DOCX files to plain text using Aspose.Words for Java with a step‑by‑step programming guide. + ## Frequently Asked Questions **Q: How do I add a watermark to an existing PDF using Aspose.Words?** diff --git a/words/english/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/english/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..ccdc8f6d46 --- /dev/null +++ b/words/english/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-05-26 +description: Create accessible PDF in Java with step‑by‑step code. Learn how to tag + PDF for accessibility and enable PDF tagging using PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: en +og_description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. +og_title: Create Accessible PDF in Java – Full Tagging Guide +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Create Accessible PDF in Java – Full Tagging Guide +url: /java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create Accessible PDF in Java – Full Tagging Guide + +Ever wondered how to **create accessible PDF** files directly from Java code? You're not alone. Many developers need to serve users who rely on screen readers, and the difference between a plain PDF and an accessible one can be huge. In this tutorial we’ll walk through **how to tag PDF for accessibility**, show you **how to create tagged PDF** with Aspose PDF for Java, and reveal the exact steps to **add accessibility tags to PDF** so every reader can get the same information. + +We'll also cover **enable PDF tagging** best practices, common pitfalls, and a complete, runnable example you can drop into your project today. No vague references—just concrete code, explanations, and a final file you can open in Adobe Acrobat to verify the tags. + +## What You’ll Learn + +- The why behind PDF tagging and accessibility compliance. +- Prerequisites and library setup (Aspose PDF for Java 23.10 or later). +- How to **create accessible PDF** from scratch, step by step. +- Ways to **add accessibility tags to PDF** beyond the basic `setTagDocumentStructure` call. +- Tips for testing the output and troubleshooting common issues. + +By the end of this guide you’ll be able to generate PDFs that pass WCAG 2.1 AA checks and look professional at the same time. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Modern language features and better Unicode handling. | +| **Aspose PDF for Java** (v23.10 or newer) | Provides the `PdfSaveOptions` class and tagging support. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | For easy compilation and debugging. | +| **Write permission** to a folder where the PDF will be saved | The `doc.save` call needs a writable path. | + +If you haven’t added Aspose PDF to your project yet, drop the following Maven dependency into your `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** Use the latest version; newer releases improve tagging accuracy and add language‑specific accessibility features. + +--- + +## Step 1: Set Up the Document Skeleton + +First, we create a fresh `Document` object. Think of it as a blank canvas that will later hold the tags we need for accessibility. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Why this matters:** Without any content, there’s nothing to tag. Adding even a simple `TextFragment` gives the tagging engine something to work with, and it automatically creates a `

` (paragraph) tag when we later enable structure tagging. + +--- + +## Step 2: Create PDF Save Options (the Core of Tagging) + +Now we prepare the options that tell Aspose PDF to embed a logical structure tree inside the file. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +The call to `setTagDocumentStructure(true)` is the **enable PDF tagging** switch. When true, the library builds a tag tree that mirrors the visual layout, making the PDF readable by assistive technologies. + +> **Note:** This is the simplest way to **how to create tagged pdf**. For more granular control (e.g., setting language or custom tags), you can explore `pdfOptions.setTagLanguage("en-US")` and `pdfOptions.setTagStructureTreeRoot(...)`. + +--- + +## Step 3: Save the Accessible PDF + +Finally, we write the document to disk using the options we just configured. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +When `doc.save` finishes, you’ll find `accessible.pdf` in the `output` folder. Open it in Adobe Acrobat and look at **File → Properties → Description → Tags** – you should see a populated tag tree. + +--- + +## How to Tag PDF for Accessibility – Beyond the Basics + +The three‑step snippet above already **adds accessibility tags to PDF**, but real‑world documents often need a bit more polish. Here are a few enhancements you can sprinkle in: + +### 1. Set Document Language + +Screen readers use the language attribute to pronounce text correctly. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Provide a Title and Subject + +Metadata helps assistive tools give context before the user even opens the file. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Tag Images with Alternative Text + +If you embed pictures, they need `alt` descriptions. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Mark Table Headers + +Tables are notorious for confusing readers unless you flag header rows. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +These extra steps make your PDF not just *technically* tagged, but truly **accessible** for a diverse audience. + +--- + +## Common Pitfalls When You Enable PDF Tagging + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Tags missing in Acrobat | `setTagDocumentStructure` left as `false` | Ensure you call `pdfOptions.setTagDocumentStructure(true)`. | +| Wrong reading order | Complex layout without explicit tags | Use `pdfOptions.setTagStructureTreeRoot(...)` to define a custom order. | +| Images read as “image” without description | No alternative text set | Call `image.getAlternativeText().setValue("...")`. | +| Language not recognized | `setTagLanguage` omitted or wrong locale | Provide a BCP‑47 language code (`en-US`, `fr-FR`). | + +Being aware of these issues saves you hours of debugging later. + +--- + +## Verify the Result – What to Expect + +After running the program, open `output/accessible.pdf` in Adobe Acrobat Reader: + +1. **Tags panel** (`View → Show/Hide → Navigation Panes → Tags`) should list a hierarchy like `/Document → /Part → /Sect → /Para`. +2. **Reading order** should follow the visual flow (text first, then images). +3. **Screen reader** (NVDA, VoiceOver) will read “Hello, accessible PDF!” instead of just “Page 1”. + +If any of those items are missing, double‑check the steps above—especially the `setTagDocumentStructure` call. + +--- + +## Full Working Example (Copy‑Paste Ready) + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // 1️⃣ Create a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // 2️⃣ Add a page and some content + Page page = doc.getPages().add(); + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); + + // Optional: set metadata for better accessibility + + +## Related Tutorials + +- [Create Accessible PDF from Word – Convert to PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Create Accessible PDF from DOCX – Complete Guide](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/english/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/english/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..2ba0077c8d --- /dev/null +++ b/words/english/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-26 +description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle images. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: en +og_description: Embed images as base64 while converting docx to markdown with Aspose.Words + for Java. Complete guide to convert word to markdown and save word as markdown. +og_title: Embed Images as Base64 When Converting DOCX to Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Embed Images as Base64 When Converting DOCX to Markdown +url: /java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Embed Images as Base64 When Converting DOCX to Markdown + +Ever wondered how to **embed images as base64** while you **convert docx to markdown**? You’re not the only one—developers constantly ask how to keep images inline without juggling separate files. The good news is that Aspose.Words for Java makes it a breeze: you can convert a Word document to Markdown and automatically embed every picture as a Base64 string. + +In this tutorial we’ll walk through the entire process—from loading a `.docx` that contains pictures, to configuring a `MarkdownSaveOptions` callback that does the heavy lifting, and finally saving the result as a clean `.md` file. By the end you’ll know exactly how to **convert word to markdown**, **convert images to base64**, and **save word as markdown** without leaving stray image folders behind. No external tools, no manual post‑processing—just pure Java code that you can drop into any project. + +## What You’ll Need + +- **Java 17** (or any recent JDK) – the code uses lambda syntax, but you can adapt it to older versions. +- **Aspose.Words for Java** library (latest version as of 2026). Add the Maven dependency or the JAR to your classpath. +- A sample **DOCX** file that contains at least one image. +- An IDE or a simple text editor—Visual Studio Code, IntelliJ IDEA, or even `vim` will do. + +If you already have these, great—let’s dive straight in. + +## Step 1: Load the Word Document + +First we create a `Document` instance that points to the source file. This is the same step whether you’re **convert docx to markdown** or just reading the file for other purposes. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Why this matters:** The `Document` object is the entry point for every Aspose operation. It holds the whole Word structure—including images, tables, and styles—so the later callback can inspect each resource. + +## Step 2: Create MarkdownSaveOptions and Register a Resource‑Saving Callback + +The magic lives in `MarkdownSaveOptions`. By attaching an `IResourceSavingCallback` we gain control over how each external resource (like an image) is written. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Why Use `setSaveToMemory(true)`? + +When `saveToMemory` is true, Aspose writes the image bytes to a memory stream instead of a file. The Markdown exporter then converts that stream to a Base64 string and inserts it directly into the Markdown image tag: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +That’s the core of **embed images as base64**. + +## Step 3: Save the Document as Markdown + +Now that the callback is in place, the final step is simply calling `save`. This is where we actually **convert word to markdown** and, because of the callback, also **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Result:** `out.md` contains Markdown text with every image represented as a `data:` URI. No extra image files are created on disk, so the folder stays tidy. + +## Step 4: Verify the Output and Common Pitfalls + +Open the generated `out.md` in any Markdown viewer (VS Code, GitHub, or a static site generator). You should see something like: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Troubleshooting Checklist + +| Issue | Likely Cause | Fix | +|-------|--------------|-----| +| Image appears as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` is inside the callback | +| Base64 string is truncated | Output file encoding mismatch | Save the Markdown using UTF‑8 (default for Aspose) | +| Unexpected file names | `setKeepResourceOriginalName(true)` | Keep it `false` to force the custom naming logic | + +## Step 5: Advanced Variations (Optional) + +### Convert Only Selected Images + +If you only want to embed certain images (e.g., those larger than 100 KB), add a size check: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Use a Different Image Format + +The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +These tweaks illustrate how flexible the **embed images as base64** approach is when you **convert docx to markdown**. + +## Conclusion + +You’ve just learned how to **embed images as base64** while you **convert docx to markdown** using Aspose.Words for Java. By wiring a simple `IResourceSavingCallback`, the library does all the heavy lifting: it **convert word to markdown**, **convert images to base64**, and finally **save word as markdown** with a single `save` call. + +Feel free to experiment—try different image‑filtering rules, switch to HTML output, or chain this step with a static‑site generator. The same pattern works for other formats (HTML, EPUB) as well, so you can reuse the callback wherever you need inline resources. + +**Next steps:** +- Explore `HtmlSaveOptions` for HTML‑with‑Base64 images. +- Combine this with a CI pipeline to automate documentation generation. +- Dive into Aspose’s `DocumentVisitor` if you need even finer control over the conversion process. + +Happy coding, and enjoy your clean, self‑contained Markdown files! + + +## Related Tutorials + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/english/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..ec13dcf03a --- /dev/null +++ b/words/english/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: en +og_description: Export docx to txt in Java. This tutorial shows how to convert docx + to text, keep plain text unicode, and export word as txt efficiently. +og_title: Export docx to txt with Java – Complete Guide +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Export docx to txt with Java – Complete Programming Guide +url: /java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Export docx to txt with Java – Complete Programming Guide + +Ever needed to **export docx to txt** but worried about losing special characters? You're not the only one. When you convert Word documents to plain‑text files, Unicode symbols, tables, and even simple formatting can vanish like magic. + +In this guide we’ll walk through a reliable way to **export docx to txt** using Aspose.Words for Java, preserving every Unicode glyph and keeping table layouts readable. By the end you’ll also know how to **convert docx to text**, **convert word to text**, and even **export word as txt** without a hitch. + +## What This Tutorial Covers + +* Setting up Aspose.Words in a Java project +* Loading a DOCX file and preparing it for plain‑text output +* Configuring **plain text unicode** support via `TxtSaveOptions` +* Optional tricks to keep tables legible in the resulting `.txt` file +* Saving the file and verifying the output + +No external scripts, no mysterious command‑line tools—just pure Java code you can drop into any Maven or Gradle project. + +> **Why care?** Plain‑text files are lightweight, version‑control friendly, and perfect for search‑indexing or downstream processing pipelines. If you’ve ever tried to `cat` a Word file and got gibberish, this tutorial solves that problem. + +--- + +## Export docx to txt – Overview + +Before we dive into code, let’s clear up the terminology. **Export docx to txt** means taking a Microsoft Word `.docx` package and writing its textual content to a simple `.txt` file. Unlike a PDF conversion, a text export strips away styling but can keep line breaks, paragraph markers, and—if you configure it right—Unicode characters such as emojis, accented letters, or Asian scripts. + +Aspose.Words makes this painless because it abstracts the Word file format and offers a `TxtSaveOptions` class where you can dictate encoding, table handling, and more. + +### Prerequisites + +* Java 11 or newer (the API works with Java 8+, but we’ll assume a recent JDK) +* Aspose.Words for Java JAR (available from Maven Central) +* A sample `unicode.docx` file containing diverse Unicode characters—think “こんにちは”, “😊”, and a simple table + +If you’ve got those, let’s get started. + +--- + +## Step 1: Load the DOCX File (Convert docx to text) + +The first thing you need to do is read the source document into memory. This is where the **convert docx to text** process officially begins. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Why this matters:* `Document` is Aspose.Words’ representation of a Word file. By loading it, you gain access to all its paragraphs, tables, and even hidden elements. If the file isn’t found, Aspose throws a clear `FileNotFoundException`, so you’ll know immediately what went wrong. + +--- + +## Step 2: Configure TxtSaveOptions for Unicode (Plain text unicode) + +Plain‑text files are just streams of bytes, so you must tell Java which character set to use. UTF‑8 is the de‑facto standard for **plain text unicode** because it can encode every Unicode code point. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro tip:** If you skip the `setEncoding` call, Aspose defaults to the platform’s default charset, which on many Windows machines is Windows‑1252. That default will silently drop characters like “ß” or “—”. + +--- + +## Step 3: Preserve Table Layout (Optional, but handy for readability) + +When you **export word as txt**, tables usually flatten into a single line of text, making them unreadable. Aspose.Words offers a simple flag to keep the visual structure. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*When to use it:* If your source DOCX contains invoices, schedules, or any grid‑like data, enabling `PreserveTableLayout` will insert tabs and line breaks so the resulting file still resembles a table. If you don’t need this, you can omit the line and get a more compact output. + +--- + +## Step 4: Save the Document as Plain‑Text (Export word as txt) + +Now the heavy lifting is done—just write the bytes to disk. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Running the program produces `plain.txt` in the same folder. Open it with any text editor (Notepad++, VS Code, even `cat` in a terminal) and you’ll see: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Notice how the Japanese greeting and smiley survived, and the table kept its columns thanks to `PreserveTableLayout`. That’s the essence of a clean **export docx to txt**. + +--- + +## Step 5: Verify the Output (Convert word to text sanity check) + +A quick sanity check prevents silent data loss. Here are a few ways to confirm you truly **convert word to text** correctly: + +1. **Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before and after a round‑trip conversion (txt → docx → txt) to ensure stability. +2. **Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate characters like “😊”. +3. **Open in multiple editors** – some old Windows Notepad versions still misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper encoding. + +If any of these checks fail, double‑check that `saveOptions.setEncoding(StandardCharsets.UTF_8)` is present and that your source DOCX truly contains Unicode text. + +--- + +## Common Pitfalls & How to Avoid Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Missing characters** | Default system charset (e.g., Windows‑1252) drops non‑ASCII glyphs. | Explicitly set UTF‑8 via `saveOptions.setEncoding`. | +| **Tables become a single line** | `PreserveTableLayout` left at default `false`. | Call `saveOptions.setPreserveTableLayout(true)`. | +| **File not found** | Wrong path or missing read permissions. | Use absolute paths or `Paths.get(...)` with proper exception handling. | +| **Performance slowdown on huge docs** | Loading the entire document into memory. | Stream the document in chunks using `DocumentBuilder` if you only need specific sections. | + +--- + +## Bonus: Exporting Multiple DOCX Files in a Batch + +If you need to **convert docx to text** for a whole folder, wrap the logic in a loop: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +This snippet **export docx to txt** for every file in the directory, saving you hours of manual work. + +--- + +## Conclusion + +You’ve just learned how to **export docx to txt** with Java, ensuring that every Unicode character stays intact, tables stay readable, and the whole process is repeatable. By configuring `TxtSaveOptions` for UTF‑8 and optionally preserving table layouts, you can reliably **convert docx to text**, **convert word to text**, and **export word as txt** for any downstream workflow. + +Ready for the next challenge? Try exporting to other plain‑text formats like markdown (`.md`) or CSV, or explore Aspose.Words’ PDF conversion capabilities. The same principles—explicit encoding, layout preservation, and thorough verification—apply across the board. + +Happy coding, and may your text files always stay Unicode‑rich! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + + +## Related Tutorials + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/english/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..33a5fc98fd --- /dev/null +++ b/words/english/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Save document as PDF using Aspose.Words Java and add accessibility to + PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 compliance. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: en +og_description: Save document as PDF with Aspose.Words Java while adding accessibility + to PDF. Step‑by‑step guide to convert docx to PDF and tag horizontal rules for PDF/UA‑2 + compliance. +og_title: Save Document as PDF with Aspose.Words Java – Accessibility Made Easy +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide +url: /java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + +Ever wondered how to **save document as PDF** while keeping it accessible for screen readers? You're not alone. Many developers need to *convert docx to pdf* and still meet PDF/UA‑2 standards, especially when the source contains horizontal rules that must be correctly tagged. In this tutorial we’ll walk through the exact steps to **save document as PDF** using Aspose.Words for Java, automatically **add accessibility to PDF**, and ensure every horizontal rule is **tagged** as an artifact. + +We’ll start with a clean Java project, load a DOCX that already has horizontal rules, configure the PDF save options for PDF/UA‑2 compliance, and finally write out a fully accessible PDF. By the end, you’ll be able to **save document as pdf** with confidence that it passes accessibility checks. + +## Prerequisites + +Before we dive in, make sure you have: + +- Java 8 or newer installed (the tutorial was tested on JDK 17). +- Maven 3.6+ (or Gradle if you prefer) to manage dependencies. +- A valid Aspose.Words for Java license (the free trial works, but a license removes evaluation watermarks). +- A DOCX file (`input.docx`) that includes at least one horizontal rule—think of a simple line separator you’d add in Word. + +> **Pro tip:** If you don’t have a DOCX handy, just create a new Word document, type a few paragraphs, insert *Insert → Horizontal Line*, save as `input.docx`, and place it in a folder of your choice. + +## Step 1: Set Up the Maven Project + +First, create a new Maven project (or add to an existing one). The `pom.xml` needs the Aspose.Words dependency: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** Adding the `aspose-words` artifact is the first step to *convert docx to pdf*. Without it, the compiler won’t recognize `Document`, `PdfSaveOptions`, and other crucial classes. + +## Step 2: Load the Source DOCX Containing Horizontal Rules + +Now we’ll write a small Java class that loads the DOCX. This is where the **tag horizontal rules** part begins—Aspose.Words automatically treats a horizontal rule as a paragraph with a border, but we’ll let the PDF/UA engine handle the tagging. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Notice we haven’t saved anything yet—we’re just **loading** the DOCX, which is the first half of *convert docx to pdf*. The `Document` object now holds all the Word content, including any horizontal rules you inserted. + +## Step 3: Configure PDF Save Options for PDF/UA‑2 Compliance + +The magic of **adding accessibility to PDF** lives in `PdfSaveOptions`. By setting the compliance level to `PDF_UA_2`, Aspose.Words will: + +1. Tag structural elements (headings, tables, etc.). +2. Mark decorative elements—like horizontal rules—as *artifacts*, so screen readers ignore them. +3. Insert the necessary PDF/UA metadata. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** Without `PDF_UA_2`, the resulting PDF may still be readable but won’t pass automated accessibility validators. The **tag horizontal rules** requirement is satisfied automatically because PDF/UA treats them as *artifacts* when the compliance flag is on. + +## Step 4: Save the Document as a PDF + +Now we finally **save document as pdf**. This single line does the heavy lifting—converting the DOCX, applying the accessibility tags, and writing the file to disk. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Run the class (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) and you’ll see a confirmation message. Open the resulting `ua_compliant.pdf` in Adobe Acrobat and check **File → Properties → Description → PDF/A, PDF/UA**—you should see “PDF/UA‑2” listed. + +### Expected Output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Open the PDF, and you’ll notice: + +- The document text is selectable and searchable. +- The horizontal line is invisible to screen readers (treated as an artifact). +- The PDF passes basic PDF/UA validation tools (e.g., PAC 3). + +## Step 5: Verify Accessibility – Quick Checklist + +Even though Aspose.Words does most of the work, it’s good practice to verify the output. + +| Check | How to Verify | +|-------|----------------| +| **Document title** | Open Acrobat → File → Properties → Title field (should match `pdfOptions.setTitle`). | +| **Artifact tagging** | Use Acrobat’s “Reading Order” tool. Horizontal rules should appear as *Artifact* (gray). | +| **Logical reading order** | Run the “Accessibility Checker” in Acrobat; ensure no structural errors. | +| **Tagged PDF** | In Acrobat, look under “Tags” panel – you should see a hierarchy (Document → Section → Paragraph, etc.). | +| **PDF/UA compliance** | Acrobat will display “PDF/UA‑2” under the “Standards” tab. | + +If any of these checks fail, double‑check that you used the latest Aspose.Words version and that `setCompliance(PdfCompliance.PDF_UA_2)` is correctly applied. + +## Common Pitfalls & How to Avoid Them + +1. **Missing License** – The trial version adds a watermark that can break PDF/UA validation. Apply your license early in `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. Use absolute paths or place the DOCX in the project root and reference it with `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – PDF/UA support was added in version 22.9. Upgrade to the latest release to avoid missing features. +4. **Horizontal Rule as Image** – If you inserted the line as an image instead of a native Word horizontal rule, Aspose treats it as a regular image, not an artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper tagging. + +## Extending the Solution – What If You Need More? + +- **Custom Tags**: If you have other decorative elements (e.g., decorative icons), you can manually mark them as artifacts using `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Loop over a folder of DOCX files and batch‑convert them, reusing the same `PdfSaveOptions` instance for performance. +- **Adding a Language Tag**: For multilingual PDFs, set `pdfOptions.setLanguage("en-US")` to help assistive technologies choose the right voice. + +## Full Working Example (All Code Together) + +Below is the complete, runnable Java program. Copy‑paste it into your IDE, adjust the paths, and hit run. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Run it, open the generated PDF, and you’ll have a clean, accessible file ready for distribution. + +## Conclusion + +We’ve just demonstrated how to **save document as pdf** with Aspose.Words for Java while automatically **add accessibility to pdf** and **tag horizontal rules** as artifacts. The key takeaways: + +- Use `PdfSaveOptions` with `PDF_UA_2` compliance to meet accessibility standards. +- Loading a DOCX and calling `doc.save(..., pdfOptions)` is all you need to **convert docx to pdf**. +- Horizontal rules are handled for you—no extra code required, fulfilling the **tag horizontal rules** requirement. +- The approach is fully **aspose convert docx pdf** compliant, works with the latest library version, and produces a validation‑ready PDF. + +Ready for the next challenge? Try adding custom metadata, embedding fonts, or batch‑processing a whole folder of DOCX files. Each of those extensions builds on the same foundation we laid out here. + +Got questions about PDF/UA compliance, licensing, or handling other Word elements? Drop a comment or check Aspose’s official documentation—there’s a wealth of examples to explore. Happy coding, and enjoy creating accessible PDFs! + +![save document as pdf using Aspose.Words Java – accessible PDF example](placeholder-image.png "save document as pdf using Aspose.Words Java") + + +## Related Tutorials + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/english/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..2d9ea2de9c --- /dev/null +++ b/words/english/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Save word as markdown and discover how to export math equations to LaTeX + using Aspose.Words for Java. Convert Word equations LaTeX in just a few lines. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: en +og_description: Save word as markdown and learn how to export math equations to LaTeX + using Aspose.Words for Java. A complete, runnable guide. +og_title: Save word as markdown – Export Math to LaTeX with Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Save word as markdown – Export Math to LaTeX with Java +url: /java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save word as markdown – Export Math to LaTeX with Java + +Ever needed to **save word as markdown** but worried your equations would turn into a garbled mess? You're not alone. In this guide we’ll walk through **how to export math** from a `.docx` file straight into LaTeX while the rest of the document becomes clean Markdown. + +We’ll cover everything from setting up the Aspose.Words library to verifying the final `out.md` file. By the end you’ll be able to **convert word equations latex** in a single method call, and you’ll understand the little nuances that make the conversion reliable. + +--- + +## What you’ll need + +- **Java 8+** – the code runs on any recent JDK. +- **Aspose.Words for Java** – either the Maven/Gradle dependency or the JAR if you prefer manual setup. +- A Word document (`math.docx`) that contains at least one Office Math equation. +- An IDE or plain `javac`/`java` command line – whatever you’re comfortable with. + +If you already have those, great. If not, the next section shows exactly how to get the library into your project. + +--- + +## Save word as markdown – Step 1: Add Aspose.Words to Your Project + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose offers a free temporary license for testing. Drop the `license.xml` file in your resources folder and call `License license = new License(); license.setLicense("license.xml");` before loading any document. + +Once the dependency is resolved, you’re ready to write the conversion code. + +--- + +## How to export math equations to LaTeX + +The heavy lifting is done by `MarkdownSaveOptions`. By switching its `OfficeMathExportMode` to `LATEX`, every Office Math object is rendered as a LaTeX fragment inside the Markdown output. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Why this works + +- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file and gives you access to every node, including equations. +- **`MarkdownSaveOptions`** tells the library *how* you want the output. The default behavior is to render equations as images, which defeats the purpose of a text‑based format. +- **`OfficeMathExportMode.LATEX`** forces the engine to translate each `OfficeMath` node into its LaTeX equivalent, which Markdown parsers (like GitHub or Jekyll) can render when combined with a MathJax plugin. + +--- + +## Convert word equations LaTeX – Step 2: Verify the Markdown Output + +After running the program, open `out.md`. You should see something like this: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** The LaTeX fragments are wrapped in `$…$` for inline math and `$$…$$` for block math. This is the standard syntax that most static site generators understand when MathJax is enabled. + +If you prefer the equations to stay inline only, you can tweak the `MarkdownSaveOptions` further: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx to markdown latex – Step 3: Edge Cases & Common Pitfalls + +| Situation | What to watch for | Fix | +|-----------|-------------------|-----| +| **Complex nested equations** | Aspose may output extra braces `{}` that some parsers treat literally. | Post‑process the Markdown with a simple regex to collapse `{{` → `{`. | +| **Missing MathJax on the target site** | Equations appear as raw LaTeX code. | Add `` to your HTML template. | +| **Large documents** | Memory consumption spikes because the whole document is loaded at once. | Use `LoadOptions.setLoadFormat(LoadFormat.DOCX)` and consider processing pages in batches if you hit `OutOfMemoryError`. | +| **License not set** | You’ll get a warning and the output may be watermarked. | Load the license early in `main` as shown in the Maven tip above. | + +--- + +## Save word as markdown – Full Working Example + +Below is a self‑contained class you can copy‑paste into any Java project. Just replace `YOUR_DIRECTORY` with the path to your files. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Run the program (`java MathToLatexMarkdown`) and you’ll see the console message confirming success. Open `out.md` in any editor – the equations should be clean LaTeX snippets ready for rendering. + +--- + +## Expected Output Snapshot + +![save word as markdown output with LaTeX equations](https://example.com/images/markdown-latex-output.png "save word as markdown output with LaTeX equations") + +*The image shows a snippet of the generated Markdown where the equation `\int_{a}^{b} f(x)\,dx` is wrapped in `$$`.* + +--- + +## Conclusion + +We’ve just demonstrated how to **save word as markdown** while preserving every Office Math equation as native LaTeX. The key step was configuring `MarkdownSaveOptions` with `OfficeMathExportMode.LATEX`, which turns a typical Word‑to‑Markdown pipeline into a fully math‑aware conversion tool. + +Now you can: + +1. **How to export math** from any `.docx` without losing fidelity. +2. **Convert word equations latex** for static site generators, documentation, or academic blogs. +3. Extend the approach to batch‑process many files, integrate with CI pipelines, or even build a tiny web service. + +If you’re curious about the next frontier, try combining this with **docx to markdown latex** for image‑heavy documents, or explore Aspose’s `HtmlSaveOptions` for a web‑ready HTML version. The possibilities are endless—experiment, break things, and then share your findings with the community. + +Got questions or a tricky equation that didn’t render as expected? Drop a comment below, and happy coding! + + +## Related Tutorials + +- [How to Export LaTeX from Word: Convert DOCX to Markdown & Save as PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/english/java/document-loading-and-saving/_index.md index 28a25ecf5b..b8a50aaeda 100644 --- a/words/english/java/document-loading-and-saving/_index.md +++ b/words/english/java/document-loading-and-saving/_index.md @@ -134,6 +134,8 @@ Learn how to repair corrupted DOCX files and process them using Aspose.Words for ### [Capture Font Substitution Warnings in Java with Aspose.Words – Complete Guide](./capture-font-substitution-warnings-in-java-with-aspose-words/) Learn how to capture and handle font substitution warnings in Java using Aspose.Words, ensuring accurate document rendering. +### [Open Corrupted Word Document – Set Recovery Mode in Java](./open-corrupted-word-document-set-recovery-mode-in-java/) + ## Frequently Asked Questions **Q:** How do I programmatically **save images from word** documents? diff --git a/words/english/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/english/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..3919dcd091 --- /dev/null +++ b/words/english/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: en +og_description: Open corrupted word document in Java using Aspose.Words. This guide + shows how to set recovery mode and recover corrupted Word files efficiently. +og_title: Open Corrupted Word Document – Set Recovery Mode in Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Open Corrupted Word Document – Set Recovery Mode in Java +url: /java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Open Corrupted Word Document – Set Recovery Mode in Java + +Ever tried to open a corrupted Word document and watched the program choke on an exception? You're not alone—those broken .docx files can be a real headache. The good news is that Aspose.Words for Java gives you fine‑grained control so you can **open corrupted word document** without the app crashing, and even decide whether you want warnings, silent recovery, or a hard reject. + +In this tutorial we’ll walk through the complete process: from creating the right `LoadOptions`, to choosing the appropriate **set recovery mode** value, and finally confirming that the document was indeed loaded. By the end you’ll know **how to recover corrupted word file** programmatically, no manual copy‑paste required. + +> **What you’ll need** +> * Java 8 or newer (the API works with Java 11 as well) +> * Aspose.Words for Java 23.9 (or the latest version) +> * A sample corrupted .docx file—just rename any valid file to simulate corruption if you don’t have one handy + +Let’s dive in. + +## Open Corrupted Word Document – Step‑by‑Step Overview + +Below is the high‑level flow we’ll implement: + +1. **Create `LoadOptions`** – this object tells Aspose.Words how to behave when it meets trouble. +2. **Set recovery mode** – pick `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, or `REJECT_CORRUPTED`. +3. **Load the document** using the configured options. +4. **Verify** the load succeeded (e.g., print page count). + +Each step is explained in detail, with code snippets you can copy‑paste directly into your IDE. + +## Set Recovery Mode for Different Scenarios + +Aspose.Words defines three recovery strategies inside `LoadOptions.RecoveryMode`: + +| Mode | Behaviour | When to use | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | Tries to load the document, but surfaces any issues as warnings in the console. | You want to see *what* went wrong without aborting. | +| `RECOVER_WITHOUT_WARNINGS` | Silently fixes what it can and suppresses warnings. | Production environments where logs must stay clean. | +| `REJECT_CORRUPTED` | Throws an exception the moment corruption is detected. | Strict validation pipelines that must fail fast. | + +Choosing the right mode is the essence of **set recovery mode** correctly. In most debugging sessions `RECOVER_WITH_WARNINGS` is the sweet spot because it tells you exactly which parts were repaired. + +## How to Recover Corrupted Word File Using Aspose.Words + +Below is a **complete, runnable Java program** that demonstrates the whole process. Feel free to drop it into a `RecoveryModeDemo.java` file, adjust the path, and hit run. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Why each line matters + +* **`LoadOptions loadOptions = new LoadOptions();`** – without this object Aspose.Words uses default recovery, which *rejects* corrupted files. Creating it gives you the hook to change that behavior. +* **`setRecoveryMode(...)`** – this is the **set recovery mode** call that decides whether warnings appear, stay hidden, or cause an exception. +* **`new Document(path, loadOptions);`** – the constructor accepts the `LoadOptions` we just configured, so the library knows how to treat the broken file right from the start. +* **`doc.getPageCount()`** – a quick sanity check. If the document loads and returns a page count, you’ve successfully **how to recover corrupted word file**. +* **`doc.save(...)`** – optional but handy; you can write the repaired version back to disk for later use. + +## Handling Common Edge Cases + +### 1. File Not Found + +If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap the load in a try‑catch block and log a friendly message: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Irrecoverable Corruption + +Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In that case Aspose.Words still loads what it can, but you’ll see warnings like “Cannot read paragraph properties”. Pay attention to the console output; those warnings often point to missing sections that you may need to reconstruct manually. + +### 3. Large Files and Performance + +Recovery adds a small overhead because the library parses the file twice—once to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + +## Pro Tips – Making Recovery Robust + +* **Log warnings to a file** – redirect `System.err` to a logger so you have an audit trail of what was fixed. +* **Validate after recovery** – run `doc.updatePageLayout();` and then re‑check the page count; sometimes layout changes after fixing broken sections. +* **Automate batch recovery** – wrap the demo in a loop that processes a folder of corrupted files, using the same `LoadOptions` each time. + +## Conclusion + +You now know exactly **how to recover corrupted word file** using Aspose.Words for Java. By creating a `LoadOptions` instance, **set recovery mode** to the strategy that fits your scenario, and loading the document with those options, you can safely **open corrupted word document** without blowing up your application. The sample code above is a complete, ready‑to‑run solution that prints the page count and even saves a cleaned‑up copy. + +What’s next? Try swapping the recovery mode to `RECOVER_WITHOUT_WARNINGS` and compare the console output, or experiment with loading encrypted documents (you’ll need to supply a password via + + +## Related Tutorials + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/english/java/document-styling/_index.md index be3d32a482..e0629fe3f7 100644 --- a/words/english/java/document-styling/_index.md +++ b/words/english/java/document-styling/_index.md @@ -44,6 +44,8 @@ Learn how to customize document themes using Aspose.Words for Java. This compreh Learn how to apply watermarks and set up page configurations with Aspose.Words for Java. A comprehensive guide with source code. ### [Document Header and Footer Styling](./document-header-footer-styling/) Learn how to style document headers and footers using Aspose.Words for Java in this detailed guide. Step-by-step instructions and source code included. +### [Set Default Font Settings in Aspose.Words for Java – Complete Guide](./set-default-font-settings-in-aspose-words-for-java-complete/) +Learn how to configure default font settings globally in Aspose.Words for Java with code examples and step-by-step instructions. {{< /blocks/products/pf/tutorial-page-section >}} @@ -53,4 +55,4 @@ Learn how to style document headers and footers using Aspose.Words for Java in t {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/english/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..9d473763a9 --- /dev/null +++ b/words/english/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Set default font settings in Aspose.Words for Java and learn how to set + font settings and detect missing fonts in just a few lines of code. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: en +og_description: Set default font settings in Aspose.Words for Java, learn to set font + settings and detect missing fonts quickly and reliably. +og_title: Set Default Font Settings in Aspose.Words for Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Set Default Font Settings in Aspose.Words for Java – Complete Guide +url: /java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Set Default Font Settings in Aspose.Words for Java – Complete Guide + +Ever wondered how to **set default font settings** when loading a Word document with Aspose.Words for Java? You're not alone. Missing glyphs can turn a polished report into a garbled mess, and catching those font‑substitution warnings early saves hours of debugging. + +In this tutorial we'll walk through a concise, end‑to‑end example that **sets default font settings**, shows you how to **set font settings** programmatically, and demonstrates a reliable way to **detect missing fonts** before they break your layout. + +--- + +## What You’ll Learn + +- How to create a `LoadOptions` object with a fresh `FontSettings` instance. +- How to attach a warning listener that will **detect missing fonts** during document load. +- How to load a DOCX file while the listener silently reports any substitutions. +- Tips for customizing fallback fonts and handling edge cases in production. + +No extra libraries, no obscure configuration files—just plain Java and Aspose.Words. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +1. **Aspose.Words for Java** (version 23.10 or newer) on your classpath. +2. A Java 17 (or later) development kit – any modern JDK works. +3. A DOCX file that intentionally uses a font you don't have installed (e.g., *“MissingFont.ttf”*). + +If you’re missing the Aspose JAR, grab it from the official Maven repository: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +That’s it—no additional fonts need to be installed for this demo. + +--- + +## Step 1: Create LoadOptions and **Set Default Font Settings** + +The first thing we need is a clean `LoadOptions` object that tells Aspose how to behave when it encounters unknown typefaces. By calling `setFontSettings(new FontSettings())` we **set default font settings** that start with an empty fallback list. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Why this matters:** +> When you don’t explicitly configure fonts, Aspose falls back to the system’s default collection, which might mask missing‑font problems. By starting from a fresh `FontSettings` instance you gain full control over which fonts are considered valid. + +--- + +## Step 2: Attach a Warning Listener to **Detect Missing Fonts** + +Aspose raises a `WarningInfo` object for every substitution it performs. By listening for `WarningType.FONT_SUBSTITUTION` we can **detect missing fonts** as soon as the document is parsed. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro tip:** The listener runs on the same thread that loads the document, so there’s virtually no performance penalty. If you need to collect warnings for later analysis, push them into a `List` instead of printing directly. + +--- + +## Step 3: Load the Document Using the Configured Options + +Now that we’ve **set font settings** and prepared a listener, we simply load the file. Any missing font triggers our callback instantly. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +If the source file references a font that isn’t installed, you’ll see output similar to: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +That line tells you exactly which font was missing and which fallback was used—perfect for logging or user feedback. + +--- + +## Step 4: Continue Normal Processing (Optional) + +At this point the document is fully loaded, and you can proceed with any manipulation you like—editing, converting to PDF, or extracting text. The warning listener has already done its job, so you don’t need extra checks. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **What if you want a custom fallback?** +> Instead of leaving the `FontSettings` empty, you can add specific fonts: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Now any missing typeface will be replaced with *Times New Roman*—a reliable choice for most Western documents. + +--- + +## Visual Overview + +![Diagram showing how to set default font settings in Aspose.Words for Java](image.png "Diagram of set default font settings flow") + +*Alt text: set default font settings in Aspose.Words for Java flowchart.* + +The diagram illustrates the flow from initializing `LoadOptions` (where we **set default font settings**) to attaching the warning listener (to **detect missing fonts**) and finally loading the document. + +--- + +## Common Pitfalls & How to Avoid Them + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **Forgot to call `setFontSettings`** | Aspose uses system defaults, hiding missing fonts. | Always create a new `FontSettings` instance and assign it to `LoadOptions`. | +| **Listener not triggered** | Listener added after loading the document. | Add the warning listener *before* calling `new Document(...)`. | +| **Path typo leads to `FileNotFoundException`** | Hard‑coded path mismatches OS case‑sensitivity. | Use `Paths.get("...").toAbsolutePath()` or configure a relative path from the project root. | +| **Multiple missing fonts overwhelm logs** | Large documents may generate dozens of warnings. | Filter duplicates or aggregate messages in a `Set` before printing. | + +--- + +## Extending the Solution + +If you need to **set font settings** for a whole application, consider creating a singleton `FontSettings` and reusing it across all `LoadOptions`. That way you maintain a consistent fallback strategy and avoid repeated object creation. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Now any part of your codebase can simply call `FontConfig.getLoadOptions()` and instantly benefit from the same **set default font settings** logic. + +--- + +## Conclusion + +We’ve just covered everything you need to **set default font settings** in Aspose.Words for Java, **set font settings** programmatically, and **detect missing fonts** before they corrupt your output. The complete, runnable example lives in the code snippets above, and you can paste it straight into your IDE to see the warnings in action. + +Next steps? Try swapping the fallback font, experiment with different document formats (DOC, RTF, HTML), or integrate the warning collector into a monitoring dashboard. The more you play with `FontSettings`, the more confidence you’ll have that your generated documents look exactly as intended—no surprises, no broken glyphs. + +Got questions or a tricky font‑substitution scenario? Drop a comment below, and happy coding! + + +## Related Tutorials + +- [Set Font Fallback Settings](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/java/images-shapes/_index.md b/words/english/java/images-shapes/_index.md index dd6088aa5c..34642518c5 100644 --- a/words/english/java/images-shapes/_index.md +++ b/words/english/java/images-shapes/_index.md @@ -38,6 +38,9 @@ Learn how to generate high-quality thumbnails and custom-sized bitmaps of Word d ### [Create Word Document Java – Add Rectangle Shape with Shadow Effect](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Learn how to add a rectangle shape with a shadow effect to a Word document using Aspose.Words for Java. +### [Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Step-by-step guide to create and customize rectangle shapes in Word documents using Aspose.Words for Java. + ## Additional Resources - [Aspose.Words for Java Documentation](https://reference.aspose.com/words/java/) diff --git a/words/english/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/english/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..e02c10480e --- /dev/null +++ b/words/english/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: en +og_description: Create rectangle shape in a Java Word document, apply shadow effect, + add shape shadow, and set shadow distance with Aspose.Words. +og_title: Create Rectangle Shape in Java Word Document – Complete Guide +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide +url: /java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + +Ever needed to **create rectangle shape** in a Java Word document but weren’t sure where to start? You’re not alone—many developers hit this snag when generating reports or invoices programmatically. In this tutorial we’ll walk through exactly how to **create rectangle shape**, apply a polished shadow, and fine‑tune the shadow distance so the result looks professional. + +We’ll use Aspose.Words for Java, a robust library that lets you manipulate Word files without needing Microsoft Office installed. By the end of this guide you’ll be able to **create word document java** projects that **add shape shadow**, **apply shadow effect**, and **set shadow distance** with just a few lines of code. + +--- + +## What You’ll Build + +- A fresh `.docx` file containing a cyan rectangle. +- A realistic drop shadow that’s blurred, angled, and partially transparent. +- Full control over the shadow’s distance from the shape. +- A ready‑to‑run Java class you can drop into any Maven or Gradle project. + +No external tools, no manual UI steps—just pure code. + +--- + +## Prerequisites + +- Java 8 or newer (the code works on Java 11, Java 17, etc.). +- Aspose.Words for Java library (available via Maven Central). +- An IDE or text editor you like (IntelliJ IDEA, Eclipse, VS Code…). +- Basic familiarity with Java syntax. + +If you’ve never added a Maven dependency before, here’s the quick snippet: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Now, let’s dive in. + +--- + +## Step 1: Create Rectangle Shape in a Word Document + +The first thing we need is a blank document and a `DocumentBuilder`. Think of the builder as a pen that writes into the document. Once we have that, we can **create rectangle shape** with a single method call. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Why this matters:** The `insertShape` method not only creates the geometry but also adds the shape to the document’s internal collection, so you can immediately start styling it. + +--- + +## Step 2: Apply Shadow Effect to the Shape + +Now that the rectangle lives on the page, we’ll **apply shadow effect**. Shadows give depth, making the shape feel like it’s lifted off the page—a subtle UI improvement that can boost readability in reports. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro tip:** A blur of `5.0` looks natural for most screen‑displayed documents. If you’re printing, you might want a slightly lower value to avoid a fuzzy appearance. + +--- + +## Step 3: Set Shadow Distance – Fine‑Tuning Placement + +Shadows aren’t just about blur; they also need the right offset. This is where we **set shadow distance**. A distance of `7.0` points creates a modest offset that’s noticeable but not overbearing. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **What if you need a bigger offset?** Increase the value; decrease it for a tighter look. Remember, the distance works together with the angle to position the shadow correctly. + +--- + +## Step 4: Save the Document – Persist Your Work + +Finally, we write the document to disk. Change the path to wherever you’d like the file to live. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Running the class creates a `shadow.docx` file that, when opened in Microsoft Word or LibreOffice, shows a cyan rectangle with a soft gray shadow angled at 45° and offset by 7 points. + +--- + +## Full Working Example + +Below is the complete, copy‑and‑paste‑ready code. It includes all imports, comments, and the final `save` call. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Expected output:** Open `shadow.docx` → you’ll see a cyan rectangle centered on the first page, casting a subtle gray shadow that’s slightly offset to the bottom‑right. The shadow’s blur and transparency make it look like natural lighting. + +--- + +## Common Questions & Edge Cases + +### “Can I use a different shape?” + +Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, or any other supported enum. The rest of the shadow code stays the same. + +### “What if I need multiple shadows?” + +Aspose.Words only supports a single shadow per shape. To simulate multiple shadows, duplicate the shape, offset each copy, and adjust the transparency. + +### “Is the shadow visible in LibreOffice?” + +Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. The shadow may look slightly different due to rendering engines, but the effect persists. + +### “How do I change the shadow color to match my brand?” + +Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such as `new java.awt.Color(0, 120, 215)` for a corporate blue. + +--- + +## Image Illustration + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illustration showing a cyan rectangle with a gray drop shadow in a Word document. + +--- + +## Recap & Next Steps + +We’ve covered how to **create rectangle shape**, **apply shadow effect**, **add shape shadow**, and **set shadow distance** using Aspose.Words for Java. The code is self‑contained, runs on any modern JDK, and produces a polished `.docx` file ready for distribution. + +Want to go further? Try: + +- Adding text inside the rectangle with `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Creating a table of shapes to build a diagram. +- Exporting the document to PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Each of these builds on the same fundamentals we just explored, so you’ll feel comfortable extending the example. + +--- + +## Final Thoughts + +Mastering **create word document java** tasks like shaping and shading gives you a huge edge when automating reports, contracts, or marketing collateral. The approach shown here is clean, maintainable, and—most importantly—easy to tweak for any visual style you need. + +Give the code a spin, tweak the blur, angle, and distance, and watch your documents transform from bland to polished. If you stumble on a hiccup, drop a comment below; I’m happy to help. + +Happy coding! + + +## Related Tutorials + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/french/java/document-conversion-and-export/_index.md index f20d55838e..ef3e487d69 100644 --- a/words/french/java/document-conversion-and-export/_index.md +++ b/words/french/java/document-conversion-and-export/_index.md @@ -92,18 +92,33 @@ Apprenez à formmer des tableaux et à appliquer des styles dans Aspose.Words po ### [Convertir docx en markdown – Exporter les équations mathématiques en LaTeX avec Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Apprenez à convertir des fichiers DOCX en Markdown et à exporter les équations mathématiques au format LaTeX avec Aspose.Words. +### [Enregistrer un document Word au format markdown – Exporter les équations mathématiques en LaTeX avec Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Apprenez à enregistrer un document Word en Markdown tout en exportant les équations au format LaTeX avec Aspose.Words for Java. + ### [Enregistrer le document au format TXT – Guide rapide pour l'exportation des équations Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Apprenez à enregistrer un document Word en texte brut tout en conservant les équations mathématiques au format LaTeX. +### [Exporter docx en txt avec Java – Guide complet de programmation](./export-docx-to-txt-with-java-complete-programming-guide/) +Apprenez à exporter des fichiers DOCX en texte brut avec Aspose.Words for Java grâce à ce guide complet. + ### [Aspose Word to PDF – Convertir DOCX en PDF en Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Convertissez facilement des fichiers DOCX en PDF avec Aspose.Words for Java en une seule ligne de code. ### [Créer un PDF accessible à partir de DOCX – Guide complet](./create-accessible-pdf-from-docx-complete-guide/) Apprenez à générer des PDF accessibles depuis des fichiers DOCX en respectant les normes d'accessibilité. +### [Enregistrer un document au format PDF avec Aspose.Words Java – Guide complet d’accessibilité](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Apprenez à convertir un document Word en PDF accessible en respectant les normes d’accessibilité avec Aspose.Words for Java. + +### [Créer un PDF accessible en Java – Guide complet de balisage](./create-accessible-pdf-in-java-full-tagging-guide/) +Apprenez à générer des PDF accessibles avec Aspose.Words for Java en ajoutant des balises complètes pour répondre aux normes d’accessibilité. + ### [Comment intégrer des images en Markdown lors de la conversion de DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Apprenez à extraire et intégrer des images lors de la conversion de fichiers DOCX en Markdown avec Aspose.Words. +### [Intégrer des images en Base64 lors de la conversion de DOCX en Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Apprenez à extraire les images d'un DOCX et à les encoder en Base64 lors de la conversion vers Markdown avec Aspose.Words. + ## Questions fréquentes **Q : Comment ajouter un filigrane à un PDF existant avec Aspose.Words ?** diff --git a/words/french/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/french/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..63507f87df --- /dev/null +++ b/words/french/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Créer un PDF accessible en Java avec du code étape par étape. Apprenez + comment baliser un PDF pour l’accessibilité et activer le balisage PDF à l’aide + de PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: fr +og_description: Créez un PDF accessible en Java avec du code étape par étape. Apprenez + à baliser le PDF pour l'accessibilité et à activer le balisage PDF à l'aide de PdfSaveOptions. +og_title: Créer un PDF accessible en Java – Guide complet du balisage +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Créer un PDF accessible en Java – Guide complet du balisage +url: /fr/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un PDF accessible en Java – Guide complet du balisage + +Vous vous êtes déjà demandé comment **créer des PDF accessibles** directement à partir du code Java ? Vous n'êtes pas seul. De nombreux développeurs doivent servir des utilisateurs qui utilisent des lecteurs d'écran, et la différence entre un PDF ordinaire et un PDF accessible peut être énorme. Dans ce tutoriel, nous allons parcourir **comment baliser un PDF pour l'accessibilité**, vous montrer **comment créer un PDF balisé** avec Aspose PDF for Java, et révéler les étapes exactes pour **ajouter des balises d'accessibilité à un PDF** afin que chaque lecteur puisse obtenir les mêmes informations. + +Nous couvrirons également les meilleures pratiques pour **activer le balisage PDF**, les pièges courants, et un exemple complet et exécutable que vous pouvez intégrer à votre projet dès aujourd'hui. Pas de références vagues — seulement du code concret, des explications, et un fichier final que vous pouvez ouvrir dans Adobe Acrobat pour vérifier les balises. + +## Ce que vous apprendrez + +- Le pourquoi du balisage PDF et de la conformité en matière d'accessibilité. +- Pré-requis et configuration de la bibliothèque (Aspose PDF for Java 23.10 ou ultérieur). +- Comment **créer un PDF accessible** à partir de zéro, étape par étape. +- Méthodes pour **ajouter des balises d'accessibilité à un PDF** au-delà de l'appel de base `setTagDocumentStructure`. +- Conseils pour tester le résultat et dépanner les problèmes courants. + +À la fin de ce guide, vous serez capable de générer des PDF qui passent les contrôles WCAG 2.1 AA et qui ont un aspect professionnel en même temps. + +--- + +## Prérequis + +Avant de commencer, assurez-vous d'avoir : + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Fonctionnalités modernes du langage et meilleure prise en charge Unicode. | +| **Aspose PDF for Java** (v23.10 ou newer) | Fournit la classe `PdfSaveOptions` et la prise en charge du balisage. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Pour une compilation et un débogage faciles. | +| **Write permission** to a folder where the PDF will be saved | L'appel `doc.save` nécessite un chemin accessible en écriture. | + +Si vous n'avez pas encore ajouté Aspose PDF à votre projet, insérez la dépendance Maven suivante dans votre `pom.xml` : + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Astuce :** Utilisez la dernière version ; les versions plus récentes améliorent la précision du balisage et ajoutent des fonctionnalités d'accessibilité spécifiques à chaque langue. + +--- + +## Étape 1 : Configurer le squelette du document + +Tout d'abord, nous créons un nouvel objet `Document`. Considérez-le comme une toile vierge qui contiendra plus tard les balises nécessaires à l'accessibilité. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Pourquoi c'est important :** Sans aucun contenu, il n'y a rien à baliser. Ajouter même un simple `TextFragment` fournit à l'engin de balisage quelque chose avec quoi travailler, et il crée automatiquement une balise `

` (paragraphe) lorsque nous activons plus tard le balisage de structure. + +## Étape 2 : Créer les options d'enregistrement PDF (le cœur du balisage) + +Nous préparons maintenant les options qui indiquent à Aspose PDF d'intégrer un arbre de structure logique dans le fichier. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +L'appel à `setTagDocumentStructure(true)` est le commutateur **activer le balisage PDF**. Lorsqu'il est vrai, la bibliothèque construit un arbre de balises qui reflète la mise en page visuelle, rendant le PDF lisible par les technologies d'assistance. + +> **Note :** C'est la façon la plus simple de **comment créer un PDF balisé**. Pour un contrôle plus granulaire (par ex., définir la langue ou des balises personnalisées), vous pouvez explorer `pdfOptions.setTagLanguage("en-US")` et `pdfOptions.setTagStructureTreeRoot(...)`. + +## Étape 3 : Enregistrer le PDF accessible + +Enfin, nous écrivons le document sur le disque en utilisant les options que nous venons de configurer. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Lorsque `doc.save` se termine, vous trouverez `accessible.pdf` dans le dossier `output`. Ouvrez-le dans Adobe Acrobat et consultez **File → Properties → Description → Tags** – vous devriez voir un arbre de balises rempli. + +## Comment baliser un PDF pour l'accessibilité – Au‑delà des bases + +L'extrait en trois étapes ci‑dessus **ajoute déjà des balises d'accessibilité à un PDF**, mais les documents du monde réel nécessitent souvent un peu plus de finition. Voici quelques améliorations que vous pouvez ajouter : + +### 1. Définir la langue du document + +Les lecteurs d'écran utilisent l'attribut de langue pour prononcer le texte correctement. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Fournir un titre et un sujet + +Les métadonnées aident les outils d'assistance à fournir un contexte avant même que l'utilisateur n'ouvre le fichier. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Baliser les images avec du texte alternatif + +Si vous intégrez des images, elles ont besoin de descriptions `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Marquer les en‑têtes de tableau + +Les tableaux sont connus pour embrouiller les lecteurs à moins que vous ne signaliez les lignes d'en‑tête. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Ces étapes supplémentaires rendent votre PDF non seulement *techniquement* balisé, mais réellement **accessible** pour un public divers. + +--- + +## Pièges courants lors de l'activation du balisage PDF + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Balises manquantes dans Acrobat | `setTagDocumentStructure` laissé à `false` | Assurez‑vous d'appeler `pdfOptions.setTagDocumentStructure(true)`. | +| Ordre de lecture incorrect | Mise en page complexe sans balises explicites | Utilisez `pdfOptions.setTagStructureTreeRoot(...)` pour définir un ordre personnalisé. | +| Les images sont lues comme « image » sans description | Aucun texte alternatif défini | Appelez `image.getAlternativeText().setValue("...")`. | +| Langue non reconnue | `setTagLanguage` omis ou locale incorrecte | Fournissez un code de langue BCP‑47 (`en-US`, `fr-FR`). | + +Être conscient de ces problèmes vous fait gagner des heures de débogage plus tard. + +--- + +## Vérifier le résultat – À quoi s'attendre + +Après avoir exécuté le programme, ouvrez `output/accessible.pdf` dans Adobe Acrobat Reader : + +1. **Panneau des balises** (`View → Show/Hide → Navigation Panes → Tags`) doit afficher une hiérarchie comme `/Document → /Part → /Sect → /Para`. +2. **Ordre de lecture** doit suivre le flux visuel (texte d'abord, puis images). +3. **Lecteur d'écran** (NVDA, VoiceOver) lira « Hello, accessible PDF! » au lieu de simplement « Page 1 ». + +Si l'un de ces éléments est manquant, revérifiez les étapes ci‑dessus — en particulier l'appel `setTagDocumentStructure`. + +--- + +## Exemple complet fonctionnel (prêt à copier‑coller) + + + +## Tutoriels associés + +- [Créer un PDF accessible à partir de Word – Convertir en PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Créer un PDF accessible à partir de DOCX – Guide complet](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Comment enregistrer un document en PDF avec Aspose.Words pour Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/french/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/french/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..62ea1642eb --- /dev/null +++ b/words/french/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Intégrez les images en base64 lors de la conversion de docx en markdown + avec Aspose.Words for Java. Apprenez à convertir Word en markdown, à enregistrer + Word au format markdown et à gérer les images. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: fr +og_description: Intégrez les images en base64 lors de la conversion de docx en markdown + avec Aspose.Words pour Java. Guide complet pour convertir un document Word en markdown + et enregistrer le Word au format markdown. +og_title: Intégrer les images en Base64 lors de la conversion de DOCX en Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Intégrer les images en Base64 lors de la conversion de DOCX en Markdown +url: /fr/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Intégrer des images en Base64 lors de la conversion de DOCX en Markdown + +Vous vous êtes déjà demandé comment **intégrer des images en base64** pendant que vous **convertissez docx en markdown** ? Vous n'êtes pas le seul—les développeurs demandent constamment comment garder les images en ligne sans gérer des fichiers séparés. La bonne nouvelle, c'est qu'Aspose.Words for Java rend cela très simple : vous pouvez convertir un document Word en Markdown et intégrer automatiquement chaque image sous forme de chaîne Base64. + +Dans ce tutoriel, nous parcourrons l'ensemble du processus—du chargement d'un `.docx` contenant des images, à la configuration d'un rappel `MarkdownSaveOptions` qui fait le travail lourd, jusqu'à l'enregistrement du résultat dans un fichier `.md` propre. À la fin, vous saurez exactement comment **convertir word en markdown**, **convertir des images en base64**, et **enregistrer word en markdown** sans laisser de dossiers d'images parasites. Aucun outil externe, aucun post‑traitement manuel—juste du code Java pur que vous pouvez intégrer dans n'importe quel projet. + +## Ce dont vous avez besoin + +- **Java 17** (ou tout JDK récent) – le code utilise la syntaxe lambda, mais vous pouvez l'adapter aux versions antérieures. +- Bibliothèque **Aspose.Words for Java** (dernière version en 2026). Ajoutez la dépendance Maven ou le JAR à votre classpath. +- Un fichier **DOCX** d'exemple contenant au moins une image. +- Un IDE ou un éditeur de texte simple—Visual Studio Code, IntelliJ IDEA, ou même `vim` feront l'affaire. + +Si vous avez déjà tout cela, super—plongeons directement. + +## Étape 1 : Charger le document Word + +Tout d'abord, nous créons une instance `Document` qui pointe vers le fichier source. C'est la même étape que vous **convertissiez docx en markdown** ou que vous lisiez simplement le fichier à d'autres fins. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Pourquoi c'est important :** L'objet `Document` est le point d'entrée de chaque opération Aspose. Il contient toute la structure Word—y compris les images, les tableaux et les styles—de sorte que le rappel ultérieur puisse inspecter chaque ressource. + +## Étape 2 : Créer MarkdownSaveOptions et enregistrer un rappel d’enregistrement de ressources + +La magie réside dans `MarkdownSaveOptions`. En attachant un `IResourceSavingCallback`, nous obtenons le contrôle sur la façon dont chaque ressource externe (comme une image) est écrite. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3 : Pourquoi utiliser `setSaveToMemory(true)` ? + +Lorsque `saveToMemory` est vrai, Aspose écrit les octets de l'image dans un flux mémoire au lieu d'un fichier. L'exportateur Markdown convertit alors ce flux en une chaîne Base64 et l'insère directement dans la balise image Markdown : + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +C’est le cœur de **intégrer des images en base64**. + +## Étape 3 : Enregistrer le document en Markdown + +Maintenant que le rappel est en place, l'étape finale consiste simplement à appeler `save`. C'est ici que nous **convertissons word en markdown** et, grâce au rappel, également **convertissons les images en base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Résultat :** `out.md` contient du texte Markdown avec chaque image représentée sous forme d'URI `data:`. Aucun fichier image supplémentaire n'est créé sur le disque, ainsi le dossier reste propre. + +## Étape 4 : Vérifier la sortie et les pièges courants + +Ouvrez le `out.md` généré dans n'importe quel visualiseur Markdown (VS Code, GitHub, ou un générateur de site statique). Vous devriez voir quelque chose comme : + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Liste de vérification de dépannage + +| Problème | Cause probable | Solution | +|-------|--------------|-----| +| Image appears as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` is inside the callback | +| Base64 string is truncated | Output file encoding mismatch | Save the Markdown using UTF‑8 (default for Aspose) | +| Unexpected file names | `setKeepResourceOriginalName(true)` | Keep it `false` to force the custom naming logic | + +## Étape 5 : Variantes avancées (optionnel) + +### Convertir uniquement les images sélectionnées + +Si vous ne souhaitez intégrer que certaines images (par ex., celles de plus de 100 KB), ajoutez une vérification de taille : + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Utiliser un format d'image différent + +`ResourceSavingArgs` vous fournit les octets bruts, vous pouvez donc ré‑encoder les JPEG en PNG avant l'intégration—utile lorsque le consommateur Markdown cible préfère le PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Ces ajustements illustrent la flexibilité de l'approche **intégrer des images en base64** lorsque vous **convertissez docx en markdown**. + +## Conclusion + +Vous venez d'apprendre comment **intégrer des images en base64** pendant que vous **convertissez docx en markdown** avec Aspose.Words for Java. En branchant un simple `IResourceSavingCallback`, la bibliothèque fait tout le travail lourd : elle **convertit word en markdown**, **convertit les images en base64**, et enfin **enregistre word en markdown** avec un seul appel `save`. + +N'hésitez pas à expérimenter—essayez différentes règles de filtrage d'images, passez à la sortie HTML, ou enchaînez cette étape avec un générateur de site statique. Le même modèle fonctionne également pour d'autres formats (HTML, EPUB), vous pouvez donc réutiliser le rappel partout où vous avez besoin de ressources en ligne. + +**Étapes suivantes :** +- Explorez `HtmlSaveOptions` pour des images HTML‑avec‑Base64. +- Combinez cela avec un pipeline CI pour automatiser la génération de documentation. +- Plongez dans le `DocumentVisitor` d'Aspose si vous avez besoin d'un contrôle encore plus fin du processus de conversion. + +Bon codage, et profitez de vos fichiers Markdown propres et autonomes ! + +## Tutoriels associés + +- [Comment intégrer des images en Markdown lors de la conversion de DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convertir docx en markdown – Exporter les équations mathématiques en LaTeX avec Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Enregistrer les images depuis Word – Guide Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/french/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..6f49b00fe1 --- /dev/null +++ b/words/french/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Exporter un docx en txt avec Java et Aspose.Words. Apprenez à convertir + un docx en texte, à préserver l'Unicode et à exporter un document Word en txt en + quelques étapes. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: fr +og_description: Exporter un docx en txt en Java. Ce tutoriel montre comment convertir + un docx en texte, conserver le texte brut Unicode et exporter un document Word en + txt de manière efficace. +og_title: Exporter docx en txt avec Java – Guide complet +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Exporter un docx en txt avec Java – Guide complet de programmation +url: /fr/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exporter docx en txt avec Java – Guide de programmation complet + +Vous avez déjà eu besoin d'**exporter docx en txt** mais vous craigniez de perdre les caractères spéciaux ? Vous n'êtes pas seul. Lorsque vous convertissez des documents Word en fichiers texte brut, les symboles Unicode, les tableaux et même le formatage le plus simple peuvent disparaître comme par magie. + +Dans ce guide, nous allons parcourir une méthode fiable pour **exporter docx en txt** en utilisant Aspose.Words for Java, en préservant chaque glyphe Unicode et en gardant la mise en page des tableaux lisible. À la fin, vous saurez également comment **convertir docx en texte**, **convertir word en texte**, et même **exporter word en txt** sans encombre. + +## Ce que couvre ce tutoriel + +* Installation d'Aspose.Words dans un projet Java +* Chargement d'un fichier DOCX et préparation pour une sortie texte brut +* Configuration du support **plain text unicode** via `TxtSaveOptions` +* Astuces optionnelles pour garder les tableaux lisibles dans le fichier `.txt` résultant +* Enregistrement du fichier et vérification du résultat + +Aucun script externe, aucun outil en ligne de commande mystérieux — juste du code Java pur que vous pouvez intégrer à n'importe quel projet Maven ou Gradle. + +> **Pourquoi s'en soucier ?** Les fichiers texte brut sont légers, compatibles avec le contrôle de version et parfaits pour l'indexation de recherche ou les pipelines de traitement en aval. Si vous avez déjà essayé de `cat` un fichier Word et obtenu du charabia, ce tutoriel résout ce problème. + +--- + +## Exporter docx en txt – Vue d'ensemble + +Avant de plonger dans le code, clarifions la terminologie. **Exporter docx en txt** signifie prendre un package Microsoft Word `.docx` et écrire son contenu textuel dans un simple fichier `.txt`. Contrairement à une conversion PDF, une exportation texte supprime le style mais peut conserver les sauts de ligne, les marqueurs de paragraphe et—si vous le configurez correctement—les caractères Unicode tels que les emojis, les lettres accentuées ou les scripts asiatiques. + +Aspose.Words rend cela indolore car il abstrait le format de fichier Word et propose une classe `TxtSaveOptions` où vous pouvez définir l'encodage, la gestion des tableaux, etc. + +### Prérequis + +* Java 11 ou plus récent (l'API fonctionne avec Java 8+, mais nous supposerons un JDK récent) +* Aspose.Words for Java JAR (disponible sur Maven Central) +* Un fichier d'exemple `unicode.docx` contenant divers caractères Unicode — pensez à “こんにちは”, “😊”, et un tableau simple + +Si vous avez tout cela, commençons. + +--- + +## Étape 1 : Charger le fichier DOCX (Convertir docx en texte) + +La première chose à faire est de lire le document source en mémoire. C'est ici que le processus **convertir docx en texte** commence officiellement. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Pourquoi c'est important :* `Document` est la représentation Aspose.Words d'un fichier Word. En le chargeant, vous accédez à tous ses paragraphes, tableaux et même aux éléments cachés. Si le fichier n'est pas trouvé, Aspose lève une `FileNotFoundException` claire, vous indiquant immédiatement ce qui a échoué. + +--- + +## Étape 2 : Configurer TxtSaveOptions pour Unicode (Plain text unicode) + +Les fichiers texte brut ne sont que des flux d'octets, il faut donc indiquer à Java quel jeu de caractères utiliser. UTF‑8 est le standard de facto pour le **plain text unicode** car il peut encoder chaque point de code Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Astuce :** Si vous omettez l'appel `setEncoding`, Aspose utilise le jeu de caractères par défaut de la plateforme, qui sur de nombreuses machines Windows est Windows‑1252. Ce paramètre par défaut supprimera silencieusement des caractères comme “ß” ou “—”. + +--- + +## Étape 3 : Conserver la mise en page du tableau (Optionnel, mais pratique pour la lisibilité) + +Lorsque vous **exportez word en txt**, les tableaux sont généralement aplatis en une seule ligne de texte, les rendant illisibles. Aspose.Words propose un simple drapeau pour garder la structure visuelle. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Quand l'utiliser :* Si votre DOCX source contient des factures, des plannings ou toute donnée en forme de grille, activer `PreserveTableLayout` insérera des tabulations et des sauts de ligne afin que le fichier résultant ressemble toujours à un tableau. Si vous n'en avez pas besoin, vous pouvez omettre cette ligne et obtenir une sortie plus compacte. + +--- + +## Étape 4 : Enregistrer le document en texte brut (Export word as txt) + +Le travail lourd est maintenant terminé — il ne reste plus qu'à écrire les octets sur le disque. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +L'exécution du programme produit `plain.txt` dans le même dossier. Ouvrez-le avec n'importe quel éditeur de texte (Notepad++, VS Code, même `cat` dans un terminal) et vous verrez : + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Remarquez comment le salut japonais et le smiley ont survécu, et comment le tableau a conservé ses colonnes grâce à `PreserveTableLayout`. C’est l’essence d’un **export docx en txt** propre. + +--- + +## Étape 5 : Vérifier le résultat (Contrôle de conversion word en texte) + +Un rapide contrôle de cohérence évite les pertes de données silencieuses. Voici quelques méthodes pour confirmer que vous **convertissez word en texte** correctement : + +1. **Comparaison de checksum** – calculez un hash SHA‑256 du fichier `.txt` avant et après une conversion aller‑retour (txt → docx → txt) pour garantir la stabilité. +2. **Recherche de marqueurs Unicode** – utilisez `grep` ou la fonction de recherche de votre IDE pour repérer des caractères comme “😊”. +3. **Ouverture dans plusieurs éditeurs** – certaines anciennes versions de Notepad sous Windows interprètent encore mal UTF‑8 sans BOM ; ouvrir le fichier dans VS Code confirme le bon encodage. + +Si l’un de ces contrôles échoue, revérifiez que `saveOptions.setEncoding(StandardCharsets.UTF_8)` est présent et que votre DOCX source contient réellement du texte Unicode. + +--- + +## Problèmes courants & Comment les éviter + +| Problème | Pourquoi cela arrive | Solution | +|----------|----------------------|----------| +| **Caractères manquants** | Jeu de caractères système par défaut (ex. : Windows‑1252) supprime les glyphes non‑ASCII. | Définir explicitement UTF‑8 via `saveOptions.setEncoding`. | +| **Les tableaux deviennent une seule ligne** | `PreserveTableLayout` laissé à `false` par défaut. | Appeler `saveOptions.setPreserveTableLayout(true)`. | +| **Fichier introuvable** | Chemin incorrect ou permissions de lecture manquantes. | Utiliser des chemins absolus ou `Paths.get(...)` avec une gestion d'exception appropriée. | +| **Ralentissement sur de gros documents** | Chargement complet du document en mémoire. | Diffuser le document par morceaux avec `DocumentBuilder` si vous ne avez besoin que de sections spécifiques. | + +--- + +## Bonus : Exporter plusieurs fichiers DOCX en lot + +Si vous devez **convertir docx en texte** pour tout un dossier, encapsulez la logique dans une boucle : + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Ce fragment **exporte docx en txt** pour chaque fichier du répertoire, vous faisant gagner des heures de travail manuel. + +--- + +## Conclusion + +Vous venez d’apprendre comment **exporter docx en txt** avec Java, en veillant à ce que chaque caractère Unicode reste intact, que les tableaux restent lisibles, et que le processus soit reproductible. En configurant `TxtSaveOptions` pour UTF‑8 et en préservant éventuellement la mise en page des tableaux, vous pouvez convertir de façon fiable **docx en texte**, **word en texte**, et **exporter word en txt** pour tout flux de travail en aval. + +Prêt pour le prochain défi ? Essayez d’exporter vers d’autres formats texte comme markdown (`.md`) ou CSV, ou explorez les capacités de conversion PDF d’Aspose.Words. Les mêmes principes — encodage explicite, préservation de la mise en page, et vérification approfondie — s’appliquent partout. + +Bon codage, et que vos fichiers texte restent toujours riches en Unicode ! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="diagramme du pipeline d'exportation docx en txt"} + +## Tutoriels associés + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/french/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..e712449b4e --- /dev/null +++ b/words/french/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Enregistrez le document au format PDF avec Aspose.Words Java et ajoutez + l'accessibilité au PDF. Apprenez à convertir un docx en PDF, à baliser les règles + horizontales et à garantir la conformité PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: fr +og_description: Enregistrez le document au format PDF avec Aspose.Words Java tout + en ajoutant l’accessibilité au PDF. Guide étape par étape pour convertir un docx + en PDF et baliser les règles horizontales afin d’assurer la conformité PDF/UA‑2. +og_title: Enregistrer le document au format PDF avec Aspose.Words Java – Accessibilité + simplifiée +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Enregistrer le document au format PDF avec Aspose.Words Java – Guide complet + d'accessibilité +url: /fr/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enregistrer le document au format PDF avec Aspose.Words Java – Guide complet d'accessibilité + +Vous vous êtes déjà demandé comment **enregistrer le document au format PDF** tout en le rendant accessible aux lecteurs d'écran ? Vous n'êtes pas seul. De nombreux développeurs doivent *convertir docx en pdf* et respecter les normes PDF/UA‑2, surtout lorsque la source contient des règles horizontales qui doivent être correctement balisées. Dans ce tutoriel, nous parcourrons les étapes exactes pour **enregistrer le document au format PDF** avec Aspose.Words pour Java, **ajouter automatiquement l'accessibilité au PDF**, et garantir que chaque règle horizontale soit **balisée** comme un artefact. + +Nous commencerons avec un projet Java vierge, chargerons un DOCX contenant déjà des règles horizontales, configurerons les options d’enregistrement PDF pour la conformité PDF/UA‑2, puis générerons un PDF entièrement accessible. À la fin, vous pourrez **enregistrer le document au format pdf** en étant sûr qu’il passe les contrôles d’accessibilité. + +## Prérequis + +- Java 8 ou version plus récente installé (le tutoriel a été testé avec JDK 17). +- Maven 3.6+ (ou Gradle si vous préférez) pour gérer les dépendances. +- Une licence valide d’Aspose.Words pour Java (l’essai gratuit fonctionne, mais une licence supprime les filigranes d’évaluation). +- Un fichier DOCX (`input.docx`) qui comprend au moins une règle horizontale — pensez à une simple ligne de séparation que vous ajouteriez dans Word. + +> **Astuce :** Si vous n’avez pas de DOCX sous la main, créez simplement un nouveau document Word, tapez quelques paragraphes, insérez *Insertion → Ligne horizontale*, enregistrez sous `input.docx` et placez-le dans le dossier de votre choix. + +## Étape 1 : Configurer le projet Maven + +Tout d’abord, créez un nouveau projet Maven (ou ajoutez‑en un existant). Le `pom.xml` doit contenir la dépendance Aspose.Words : + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Pourquoi c’est important :** Ajouter l’artifact `aspose-words` est la première étape pour *convertir docx en pdf*. Sans cela, le compilateur ne reconnaîtra pas `Document`, `PdfSaveOptions` et d’autres classes essentielles. + +## Étape 2 : Charger le DOCX source contenant des règles horizontales + +Nous allons maintenant écrire une petite classe Java qui charge le DOCX. C’est ici que commence la partie **baliser les règles horizontales** — Aspose.Words traite automatiquement une règle horizontale comme un paragraphe avec une bordure, mais nous laisserons le moteur PDF/UA gérer le balisage. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Notez que nous n’avons encore rien enregistré — nous **chargeons** simplement le DOCX, ce qui constitue la première moitié de *convertir docx en pdf*. L’objet `Document` contient maintenant tout le contenu Word, y compris les règles horizontales que vous avez insérées. + +## Étape 3 : Configurer les options d’enregistrement PDF pour la conformité PDF/UA‑2 + +La magie de **l’ajout de l’accessibilité au PDF** réside dans `PdfSaveOptions`. En définissant le niveau de conformité à `PDF_UA_2`, Aspose.Words : + +1. Baliser les éléments structurels (titres, tableaux, etc.). +2. Marquer les éléments décoratifs — comme les règles horizontales — comme *artefacts*, afin que les lecteurs d’écran les ignorent. +3. Insérer les métadonnées PDF/UA nécessaires. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Pourquoi définir la conformité ?** Sans `PDF_UA_2`, le PDF résultant peut toujours être lisible mais ne passera pas les validateurs d’accessibilité automatisés. L’exigence **baliser les règles horizontales** est satisfaite automatiquement car PDF/UA les traite comme des *artefacts* lorsque le drapeau de conformité est activé. + +## Étape 4 : Enregistrer le document au format PDF + +Nous allons maintenant enfin **enregistrer le document au format pdf**. Cette ligne unique effectue le travail lourd — conversion du DOCX, application des balises d’accessibilité, et écriture du fichier sur le disque. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Exécutez la classe (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) et vous verrez un message de confirmation. Ouvrez le `ua_compliant.pdf` généré dans Adobe Acrobat et vérifiez **Fichier → Propriétés → Description → PDF/A, PDF/UA**—vous devriez voir « PDF/UA‑2 » répertorié. + +### Résultat attendu + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Ouvrez le PDF, et vous remarquerez : + +- Le texte du document est sélectionnable et recherchable. +- La ligne horizontale est invisible pour les lecteurs d’écran (traitée comme un artefact). +- Le PDF passe les outils de validation PDF/UA de base (par ex., PAC 3). + +## Étape 5 : Vérifier l’accessibilité – Checklist rapide + +Même si Aspose.Words effectue la majeure partie du travail, il est recommandé de vérifier la sortie. + +| Vérification | Comment vérifier | +|--------------|-------------------| +| **Titre du document** | Ouvrez Acrobat → Fichier → Propriétés → Champ Titre (doit correspondre à `pdfOptions.setTitle`). | +| **Balise d’artefact** | Utilisez l’outil « Ordre de lecture » d’Acrobat. Les règles horizontales doivent apparaître comme *Artefact* (gris). | +| **Ordre de lecture logique** | Exécutez le « Vérificateur d’accessibilité » dans Acrobat ; assurez‑vous qu’il n’y a aucune erreur structurelle. | +| **PDF balisé** | Dans Acrobat, consultez le panneau « Balises » – vous devriez voir une hiérarchie (Document → Section → Paragraphe, etc.). | +| **Conformité PDF/UA** | Acrobat affichera « PDF/UA‑2 » sous l’onglet « Normes ». | + +Si l’une de ces vérifications échoue, revérifiez que vous avez utilisé la dernière version d’Aspose.Words et que `setCompliance(PdfCompliance.PDF_UA_2)` est correctement appliquée. + +## Pièges courants & comment les éviter + +1. **Licence manquante** – La version d’essai ajoute un filigrane qui peut compromettre la validation PDF/UA. Appliquez votre licence tôt dans `main` : + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Chemin d’entrée incorrect** – Une `FileNotFoundException` arrêtera la conversion. Utilisez des chemins absolus ou placez le DOCX à la racine du projet et référencez‑le avec `new File("input.docx").getAbsolutePath()`. +3. **Utilisation d’une version Aspose ancienne** – Le support PDF/UA a été ajouté dans la version 22.9. Mettez à jour vers la dernière version pour éviter les fonctionnalités manquantes. +4. **Règle horizontale comme image** – Si vous avez inséré la ligne comme une image au lieu d’une règle horizontale native Word, Aspose la traite comme une image ordinaire, pas comme un artefact. Remplacez l’image par la *Ligne horizontale* intégrée de Word pour un balisage correct. + +## Étendre la solution – Que faire si vous avez besoin de plus ? + +- **Balises personnalisées** : Si vous avez d’autres éléments décoratifs (par ex., des icônes décoratives), vous pouvez les marquer manuellement comme artefacts en utilisant `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Documents multiples** : Parcourez un dossier de fichiers DOCX et convertissez‑les par lots, en réutilisant la même instance `PdfSaveOptions` pour les performances. +- **Ajout d’une balise de langue** : Pour les PDF multilingues, définissez `pdfOptions.setLanguage("en-US")` afin d’aider les technologies d’assistance à choisir la bonne voix. + +## Exemple complet fonctionnel (tout le code ensemble) + +Voici le programme Java complet et exécutable. Copiez‑collez‑le dans votre IDE, ajustez les chemins, puis lancez‑le. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Exécutez‑le, ouvrez le PDF généré, et vous disposerez d’un fichier propre et accessible prêt à être distribué. + +## Conclusion + +Nous venons de démontrer comment **enregistrer le document au format pdf** avec Aspose.Words pour Java tout en **ajoutant automatiquement l’accessibilité au pdf** et en **balisant les règles horizontales** comme des artefacts. Les points clés : + +- Utilisez `PdfSaveOptions` avec la conformité `PDF_UA_2` pour répondre aux normes d’accessibilité. +- Charger un DOCX et appeler `doc.save(..., pdfOptions)` suffit pour **convertir docx en pdf**. +- Les règles horizontales sont gérées automatiquement — aucun code supplémentaire n’est nécessaire, répondant à l’exigence **baliser les règles horizontales**. +- L’approche est entièrement conforme à **aspose convert docx pdf**, fonctionne avec la dernière version de la bibliothèque, et produit un PDF prêt pour la validation. + +Prêt pour le prochain défi ? Essayez d’ajouter des métadonnées personnalisées, d’incorporer des polices, ou de traiter par lots un dossier complet de fichiers DOCX. Chacune de ces extensions s’appuie sur la même base que nous avons présentée. + +Des questions sur la conformité PDF/UA, les licences ou la gestion d’autres éléments Word ? Laissez un commentaire ou consultez la documentation officielle d’Aspose—il y a une multitude d’exemples à explorer. Bon codage, et profitez de la création de PDFs accessibles ! + +![enregistrer le document au format pdf avec Aspose.Words Java – exemple de PDF accessible](placeholder-image.png "enregistrer le document au format pdf avec Aspose.Words Java") + +## Tutoriels associés + +- [Comment enregistrer le document au format pdf avec Aspose.Words pour Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Comment convertir Word en PDF avec Aspose.Words pour Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convertir DOCX en PDF en Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/french/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..82ca30e338 --- /dev/null +++ b/words/french/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-05-26 +description: Enregistrez le document Word au format markdown et découvrez comment + exporter les équations mathématiques vers LaTeX avec Aspose.Words pour Java. Convertissez + les équations Word en LaTeX en quelques lignes seulement. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: fr +og_description: Enregistrez le fichier Word au format Markdown et apprenez à exporter + les équations mathématiques vers LaTeX en utilisant Aspose.Words pour Java. Un guide + complet et exécutable. +og_title: Enregistrer Word en markdown – Exporter les mathématiques en LaTeX avec + Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Enregistrer le document Word au format Markdown – Exporter les formules en + LaTeX avec Java +url: /fr/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Enregistrer Word en markdown – Exporter les mathématiques en LaTeX avec Java + +Vous avez déjà eu besoin de **save word as markdown** mais vous craigniez que vos équations ne deviennent un fouillis illisible ? Vous n'êtes pas seul. Dans ce guide, nous allons parcourir **how to export math** depuis un fichier `.docx` directement en LaTeX tandis que le reste du document devient du Markdown propre. + +Nous couvrirons tout, de la configuration de la bibliothèque Aspose.Words à la vérification du fichier final `out.md`. À la fin, vous pourrez **convert word equations latex** en un seul appel de méthode, et vous comprendrez les petites nuances qui rendent la conversion fiable. + +--- + +## Ce dont vous avez besoin + +- **Java 8+** – le code s'exécute sur n'importe quel JDK récent. +- **Aspose.Words for Java** – soit la dépendance Maven/Gradle, soit le JAR si vous préférez une configuration manuelle. +- Un document Word (`math.docx`) contenant au moins une équation Office Math. +- Un IDE ou simplement la ligne de commande `javac`/`java` – ce qui vous convient. + +Si vous avez déjà tout cela, super. Sinon, la section suivante montre exactement comment ajouter la bibliothèque à votre projet. + +## Enregistrer Word en markdown – Étape 1 : Ajouter Aspose.Words à votre projet + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose propose une licence temporaire gratuite pour les tests. Déposez le fichier `license.xml` dans votre dossier resources et appelez `License license = new License(); license.setLicense("license.xml");` avant de charger tout document. + +Une fois la dépendance résolue, vous êtes prêt à écrire le code de conversion. + +--- + +## Comment exporter les équations mathématiques en LaTeX + +Le travail lourd est effectué par `MarkdownSaveOptions`. En passant son `OfficeMathExportMode` à `LATEX`, chaque objet Office Math est rendu comme un fragment LaTeX dans la sortie Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Pourquoi cela fonctionne + +- **`Document`** est le point d'entrée d'Aspose ; il abstrait le fichier `.docx` et vous donne accès à chaque nœud, y compris les équations. +- **`MarkdownSaveOptions`** indique à la bibliothèque *comment* vous voulez la sortie. Le comportement par défaut est de rendre les équations sous forme d'images, ce qui va à l'encontre de l'objectif d'un format texte. +- **`OfficeMathExportMode.LATEX`** force le moteur à traduire chaque nœud `OfficeMath` en son équivalent LaTeX, que les analyseurs Markdown (comme GitHub ou Jekyll) peuvent rendre lorsqu'ils sont combinés avec un plugin MathJax. + +## Convertir les équations Word en LaTeX – Étape 2 : Vérifier la sortie Markdown + +Après avoir exécuté le programme, ouvrez `out.md`. Vous devriez voir quelque chose comme ceci : + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note :** Les fragments LaTeX sont entourés de `$…$` pour les mathématiques en ligne et de `$$…$$` pour les mathématiques en bloc. C'est la syntaxe standard que la plupart des générateurs de sites statiques comprennent lorsque MathJax est activé. + +Si vous préférez que les équations restent uniquement en ligne, vous pouvez ajuster davantage `MarkdownSaveOptions` : + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx en markdown latex – Étape 3 : Cas limites et pièges courants + +| Situation | À surveiller | Solution | +|-----------|--------------|----------| +| **Complex nested equations** | Aspose peut générer des accolades supplémentaires `{}` que certains analyseurs traitent littéralement. | Post‑traitez le Markdown avec une simple expression régulière pour réduire `{{` → `{`. | +| **Missing MathJax on the target site** | Les équations apparaissent sous forme de code LaTeX brut. | Ajoutez `` à votre modèle HTML. | +| **Large documents** | La consommation de mémoire augmente car le document entier est chargé en une fois. | Utilisez `LoadOptions.setLoadFormat(LoadFormat.DOCX)` et envisagez de traiter les pages par lots si vous rencontrez `OutOfMemoryError`. | +| **License not set** | Vous recevrez un avertissement et la sortie peut être filigranée. | Chargez la licence tôt dans `main` comme indiqué dans l'astuce Maven ci‑dessus. | + +## Enregistrer Word en markdown – Exemple complet fonctionnel + +Ci‑dessous se trouve une classe autonome que vous pouvez copier‑coller dans n'importe quel projet Java. Remplacez simplement `YOUR_DIRECTORY` par le chemin vers vos fichiers. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Exécutez le programme (`java MathToLatexMarkdown`) et vous verrez le message console confirmant le succès. Ouvrez `out.md` dans n'importe quel éditeur – les équations devraient être des extraits LaTeX propres prêts à être rendus. + +## Capture d'écran du résultat attendu + +![sortie de save word as markdown avec des équations LaTeX](https://example.com/images/markdown-latex-output.png "sortie de save word as markdown avec des équations LaTeX") + +*L'image montre un extrait du Markdown généré où l'équation `\int_{a}^{b} f(x)\,dx` est entourée de `$$`.* + +## Conclusion + +Nous venons de démontrer comment **save word as markdown** tout en conservant chaque équation Office Math en LaTeX natif. L'étape clé était de configurer `MarkdownSaveOptions` avec `OfficeMathExportMode.LATEX`, ce qui transforme un pipeline Word‑vers‑Markdown typique en un outil de conversion pleinement compatible avec les mathématiques. + +Vous pouvez maintenant : + +1. **How to export math** depuis n'importe quel `.docx` sans perdre en fidélité. +2. **Convert word equations latex** pour les générateurs de sites statiques, la documentation ou les blogs académiques. +3. Étendre l'approche pour traiter en lot de nombreux fichiers, l'intégrer aux pipelines CI, ou même créer un petit service web. + +Si vous êtes curieux de la prochaine frontière, essayez de combiner cela avec **docx to markdown latex** pour les documents riches en images, ou explorez `HtmlSaveOptions` d'Aspose pour une version HTML prête pour le web. Les possibilités sont infinies — expérimentez, cassez des choses, puis partagez vos découvertes avec la communauté. + +Des questions ou une équation difficile qui ne s’est pas affichée comme prévu ? Laissez un commentaire ci‑dessous, et bon codage ! + +## Tutoriels associés + +- [Comment exporter LaTeX depuis Word : convertir DOCX en Markdown et enregistrer en PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Convertir docx en markdown – Exporter les équations mathématiques en LaTeX avec Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Comment convertir Word en PDF avec Aspose.Words pour Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/french/java/document-loading-and-saving/_index.md index 0275dc5098..c7bf5b1169 100644 --- a/words/french/java/document-loading-and-saving/_index.md +++ b/words/french/java/document-loading-and-saving/_index.md @@ -97,6 +97,9 @@ Débloquez la puissance d'Aspose.Words for Java. Apprenez à charger des documen ### [Récupérer un docx corrompu – Guide complet pour réparer et traiter les documents](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) Apprenez à réparer les fichiers DOCX endommagés, récupérer le contenu et le traiter avec Aspose.Words for Java. +### [Ouvrir un document Word corrompu – Définir le mode de récupération en Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Apprenez à ouvrir des documents Word corrompus en Java en activant le mode de récupération d'Aspose.Words. + ### [Options avancées d'enregistrement avec Aspose.Words for Java](./advance-saving-options/) Apprenez la manipulation avancée de documents avec Aspose.Words for Java. Chiffrez, gérez les métafichiers, et plus encore. Vos documents Word, à votre façon. diff --git a/words/french/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/french/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..9be525e5da --- /dev/null +++ b/words/french/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Ouvrez un document Word corrompu en Java avec Aspose.Words. Apprenez + comment activer le mode de récupération et récupérer les fichiers Word corrompus + de manière fiable. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: fr +og_description: Ouvrir un document Word corrompu en Java avec Aspose.Words. Ce guide + montre comment activer le mode de récupération et récupérer efficacement les fichiers + Word corrompus. +og_title: Ouvrir un document Word corrompu – définir le mode de récupération en Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Ouvrir un document Word corrompu – Définir le mode de récupération en Java +url: /fr/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ouvrir un document Word corrompu – Définir le mode de récupération en Java + +Vous avez déjà essayé d'ouvrir un document Word corrompu et vu le programme s'étouffer sur une exception ? Vous n'êtes pas seul—ces fichiers .docx cassés peuvent être un vrai casse‑tête. La bonne nouvelle, c'est qu'Aspose.Words for Java vous offre un contrôle fin afin que vous puissiez **open corrupted word document** sans que l'application ne plante, et même décider si vous voulez des avertissements, une récupération silencieuse, ou un rejet strict. + +Dans ce tutoriel, nous parcourrons le processus complet : de la création du bon `LoadOptions`, au choix de la valeur appropriée de **set recovery mode**, et enfin en confirmant que le document a bien été chargé. À la fin, vous saurez **how to recover corrupted word file** de façon programmatique, sans besoin de copier‑coller manuellement. + +> **Ce dont vous aurez besoin** +> * Java 8 ou plus récent (l'API fonctionne également avec Java 11) +> * Aspose.Words for Java 23.9 (ou la dernière version) +> * Un fichier .docx corrompu d'exemple—renommez simplement n'importe quel fichier valide pour simuler la corruption si vous n'en avez pas sous la main + +Plongeons‑y. + +## Ouvrir un document Word corrompu – Vue d'ensemble étape par étape + +Voici le flux de haut niveau que nous allons implémenter : + +1. **Create `LoadOptions`** – cet objet indique à Aspose.Words comment se comporter lorsqu'il rencontre des problèmes. +2. **Set recovery mode** – choisissez `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` ou `REJECT_CORRUPTED`. +3. **Load the document** en utilisant les options configurées. +4. **Verify** que le chargement a réussi (par ex., afficher le nombre de pages). + +Chaque étape est expliquée en détail, avec des extraits de code que vous pouvez copier‑coller directement dans votre IDE. + +## Définir le mode de récupération pour différents scénarios + +Aspose.Words définit trois stratégies de récupération dans `LoadOptions.RecoveryMode` : + +| Mode | Comportement | Quand l'utiliser | +|------|--------------|-------------------| +| `RECOVER_WITH_WARNINGS` | Essaye de charger le document, mais expose les problèmes sous forme d'avertissements dans la console. | Vous voulez voir *ce qui* a mal tourné sans interrompre. | +| `RECOVER_WITHOUT_WARNINGS` | Corrige silencieusement ce qu'il peut et supprime les avertissements. | Environnements de production où les journaux doivent rester propres. | +| `REJECT_CORRUPTED` | Lance une exception dès que la corruption est détectée. | Pipelines de validation stricts qui doivent échouer rapidement. | + +Choisir le bon mode est l'essence d'un **set recovery mode** correct. Dans la plupart des sessions de débogage, `RECOVER_WITH_WARNINGS` est le meilleur compromis car il vous indique exactement quelles parties ont été réparées. + +## Comment récupérer un fichier Word corrompu avec Aspose.Words + +Voici un **programme Java complet et exécutable** qui démontre le processus complet. N'hésitez pas à le placer dans un fichier `RecoveryModeDemo.java`, ajuster le chemin, et lancer l'exécution. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Pourquoi chaque ligne est importante + +* **`LoadOptions loadOptions = new LoadOptions();`** – sans cet objet, Aspose.Words utilise la récupération par défaut, qui *rejette* les fichiers corrompus. Le créer vous donne le point d'accroche pour modifier ce comportement. +* **`setRecoveryMode(...)`** – il s'agit de l'appel **set recovery mode** qui décide si les avertissements apparaissent, restent cachés, ou provoquent une exception. +* **`new Document(path, loadOptions);`** – le constructeur accepte le `LoadOptions` que nous venons de configurer, ainsi la bibliothèque sait comment traiter le fichier endommagé dès le départ. +* **`doc.getPageCount()`** – une vérification rapide de bon sens. Si le document se charge et renvoie un nombre de pages, vous avez réussi **how to recover corrupted word file**. +* **`doc.save(...)`** – optionnel mais pratique ; vous pouvez écrire la version réparée sur le disque pour une utilisation ultérieure. + +## Gestion des cas limites courants + +### 1. Fichier non trouvé + +Si le chemin est incorrect, `Document` lance une `FileNotFoundException`. Enveloppez le chargement dans un bloc try‑catch et consignez un message convivial : + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Corruption irrécupérable + +Même avec `RECOVER_WITH_WARNINGS`, certaines structures sont irrémédiablement endommagées. Dans ce cas, Aspose.Words charge tout ce qu'il peut, mais vous verrez des avertissements comme « Cannot read paragraph properties ». Faites attention à la sortie console ; ces avertissements indiquent souvent des sections manquantes que vous devrez peut‑être reconstruire manuellement. + +### 3. Gros fichiers et performances + +La récupération ajoute un léger surcoût car la bibliothèque analyse le fichier deux fois — une fois pour détecter les problèmes, une autre pour reconstruire. Pour des documents de plusieurs gigaoctets, envisagez de diffuser le fichier en streaming ou d'augmenter le tas JVM (`-Xmx2g`) afin d'éviter `OutOfMemoryError`. + +## Astuces pro – Rendre la récupération robuste + +* **Log warnings to a file** – redirigez `System.err` vers un logger afin d'avoir une trace d'audit de ce qui a été corrigé. +* **Validate after recovery** – exécutez `doc.updatePageLayout();` puis revérifiez le nombre de pages ; parfois la mise en page change après la réparation des sections endommagées. +* **Automate batch recovery** – encapsulez la démo dans une boucle qui traite un dossier de fichiers corrompus, en utilisant les mêmes `LoadOptions` à chaque fois. + +## Conclusion + +Vous savez maintenant exactement **how to recover corrupted word file** avec Aspose.Words pour Java. En créant une instance `LoadOptions`, en **set recovery mode** à la stratégie qui correspond à votre scénario, et en chargeant le document avec ces options, vous pouvez en toute sécurité **open corrupted word document** sans faire planter votre application. Le code d'exemple ci‑dessus est une solution complète, prête à l'exécution, qui affiche le nombre de pages et même enregistre une copie nettoyée. + +Et ensuite ? Essayez de changer le mode de récupération à `RECOVER_WITHOUT_WARNINGS` et comparez la sortie console, ou expérimentez le chargement de documents chiffrés (vous devrez fournir un mot de passe via + +## Tutoriels associés + +- [Aspose.Words Java : Guide complet du traitement de documents Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Comment convertir Word en PDF avec Aspose.Words pour Java](/words/english/java/document-converting/using-document-converting/) +- [Comment comparer deux fichiers Word avec Aspose.Words pour Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/french/java/document-styling/_index.md index c097a73742..b964846358 100644 --- a/words/french/java/document-styling/_index.md +++ b/words/french/java/document-styling/_index.md @@ -43,6 +43,8 @@ Apprenez à personnaliser les thèmes de vos documents avec Aspose.Words pour Ja Apprenez à appliquer des filigranes et à configurer des pages avec Aspose.Words pour Java. Un guide complet avec code source. ### [Style d'en-tête et de pied de page du document](./document-header-footer-styling/) Apprenez à styliser les en-têtes et pieds de page de vos documents avec Aspose.Words pour Java dans ce guide détaillé. Instructions étape par étape et code source inclus. +### [Définir les paramètres de police par défaut dans Aspose.Words pour Java – Guide complet](./set-default-font-settings-in-aspose-words-for-java-complete/) +Apprenez à configurer la police par défaut pour vos documents avec Aspose.Words pour Java. Guide complet avec exemples de code. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/french/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..719027b106 --- /dev/null +++ b/words/french/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Définissez les paramètres de police par défaut dans Aspose.Words pour + Java et apprenez à configurer les paramètres de police et à détecter les polices + manquantes en quelques lignes de code. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: fr +og_description: Définissez les paramètres de police par défaut dans Aspose.Words pour + Java, apprenez à configurer les paramètres de police et à détecter les polices manquantes + rapidement et de manière fiable. +og_title: Définir les paramètres de police par défaut dans Aspose.Words pour Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Définir les paramètres de police par défaut dans Aspose.Words pour Java – Guide + complet +url: /fr/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Définir les paramètres de police par défaut dans Aspose.Words pour Java – Guide complet + +Vous êtes‑vous déjà demandé comment **définir les paramètres de police par défaut** lors du chargement d'un document Word avec Aspose.Words pour Java ? Vous n'êtes pas seul. Des glyphes manquants peuvent transformer un rapport soigné en un fouillis illisible, et détecter ces avertissements de substitution de police tôt permet d'économiser des heures de débogage. + +Dans ce tutoriel, nous parcourrons un exemple concis et complet qui **définit les paramètres de police par défaut**, vous montre comment **définir les paramètres de police** par programme, et démontre une méthode fiable pour **détecter les polices manquantes** avant qu'elles ne perturbent votre mise en page. + +--- + +## Ce que vous apprendrez + +- Comment créer un objet `LoadOptions` avec une nouvelle instance de `FontSettings`. +- Comment attacher un écouteur d'avertissement qui **détectera les polices manquantes** lors du chargement du document. +- Comment charger un fichier DOCX tandis que l'écouteur signale silencieusement toute substitution. +- Conseils pour personnaliser les polices de secours et gérer les cas limites en production. + +Pas de bibliothèques supplémentaires, pas de fichiers de configuration obscurs—juste du Java pur et Aspose.Words. + +--- + +## Prérequis + +Avant de commencer, assurez‑vous d'avoir : + +1. **Aspose.Words for Java** (version 23.10 ou plus récente) dans votre classpath. +2. Un kit de développement Java 17 (ou ultérieur) – tout JDK moderne fonctionne. +3. Un fichier DOCX qui utilise intentionnellement une police que vous n'avez pas installée (par ex., *« MissingFont.ttf »*). + +Si le JAR Aspose vous manque, récupérez‑le depuis le dépôt officiel Maven : + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +C’est tout—aucune police supplémentaire n’est requise pour cette démonstration. + +--- + +## Étape 1 : Créer LoadOptions et **définir les paramètres de police par défaut** + +La première chose dont nous avons besoin est un objet `LoadOptions` propre qui indique à Aspose comment se comporter lorsqu'il rencontre des polices inconnues. En appelant `setFontSettings(new FontSettings())`, nous **définissons les paramètres de police par défaut** qui commencent avec une liste de secours vide. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Pourquoi c’est important :** +> Lorsque vous ne configurez pas explicitement les polices, Aspose utilise les paramètres par défaut du système, ce qui peut masquer les problèmes de polices manquantes. En partant d’une nouvelle instance de `FontSettings`, vous obtenez un contrôle complet sur les polices considérées comme valides. + +--- + +## Étape 2 : Attacher un écouteur d’avertissement pour **détecter les polices manquantes** + +Aspose génère un objet `WarningInfo` pour chaque substitution qu’il effectue. En écoutant `WarningType.FONT_SUBSTITUTION`, nous pouvons **détecter les polices manquantes** dès que le document est analysé. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Astuce :** L’écouteur s’exécute sur le même thread qui charge le document, il n’y a donc pratiquement aucun impact sur les performances. Si vous devez collecter les avertissements pour une analyse ultérieure, stockez‑les dans une `List` au lieu de les imprimer directement. + +--- + +## Étape 3 : Charger le document en utilisant les options configurées + +Maintenant que nous avons **défini les paramètres de police** et préparé un écouteur, nous chargeons simplement le fichier. Toute police manquante déclenche immédiatement notre rappel. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Si le fichier source fait référence à une police qui n’est pas installée, vous verrez une sortie similaire à : + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Cette ligne indique exactement quelle police était manquante et quel substitut a été utilisé—parfait pour la journalisation ou le retour utilisateur. + +--- + +## Étape 4 : Continuer le traitement normal (facultatif) + +À ce stade, le document est entièrement chargé, et vous pouvez poursuivre toute manipulation souhaitée—édition, conversion en PDF ou extraction de texte. L’écouteur d’avertissement a déjà fait son travail, vous n’avez donc pas besoin de vérifications supplémentaires. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Et si vous voulez un substitut personnalisé ?** +> Au lieu de laisser le `FontSettings` vide, vous pouvez ajouter des polices spécifiques : + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Désormais, toute police manquante sera remplacée par *Times New Roman*—un choix fiable pour la plupart des documents occidentaux. + +--- + +## Vue d’ensemble visuelle + +![Diagramme montrant comment définir les paramètres de police par défaut dans Aspose.Words pour Java](image.png "Diagramme du flux de définition des paramètres de police par défaut") + +*Texte alternatif : diagramme du flux de définition des paramètres de police par défaut dans Aspose.Words pour Java.* + +Le diagramme illustre le flux depuis l’initialisation de `LoadOptions` (où nous **définissons les paramètres de police par défaut**) jusqu’à l’attachement de l’écouteur d’avertissement (pour **détecter les polices manquantes**) et enfin le chargement du document. + +--- + +## Pièges courants et comment les éviter + +| Piège | Pourquoi cela se produit | Solution | +|-------|--------------------------|----------| +| **Oubli d’appeler `setFontSettings`** | Aspose utilise les paramètres par défaut du système, masquant les polices manquantes. | Toujours créer une nouvelle instance de `FontSettings` et l’assigner à `LoadOptions`. | +| **Écouteur non déclenché** | L’écouteur a été ajouté après le chargement du document. | Ajoutez l’écouteur d’avertissement *avant* d’appeler `new Document(...)`. | +| **Erreur de chemin entraînant `FileNotFoundException`** | Le chemin codé en dur ne correspond pas à la sensibilité à la casse du système d’exploitation. | Utilisez `Paths.get("...").toAbsolutePath()` ou configurez un chemin relatif depuis la racine du projet. | +| **Plusieurs polices manquantes submergent les journaux** | Les gros documents peuvent générer des dizaines d’avertissements. | Filtrez les doublons ou regroupez les messages dans un `Set` avant l’impression. | + +--- + +## Étendre la solution + +Si vous devez **définir les paramètres de police** pour toute une application, envisagez de créer un `FontSettings` singleton et de le réutiliser dans tous les `LoadOptions`. Ainsi, vous maintenez une stratégie de secours cohérente et évitez la création répétée d’objets. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Désormais, n’importe quelle partie de votre code peut simplement appeler `FontConfig.getLoadOptions()` et bénéficier instantanément de la même logique de **définition des paramètres de police par défaut**. + +--- + +## Conclusion + +Nous venons de couvrir tout ce dont vous avez besoin pour **définir les paramètres de police par défaut** dans Aspose.Words pour Java, **définir les paramètres de police** par programme, et **détecter les polices manquantes** avant qu’elles ne corrompent votre sortie. L’exemple complet et exécutable se trouve dans les extraits de code ci‑dessus, et vous pouvez le coller directement dans votre IDE pour voir les avertissements en action. + +Prochaines étapes ? Essayez de changer la police de secours, expérimentez différents formats de documents (DOC, RTF, HTML), ou intégrez le collecteur d’avertissements dans un tableau de bord de surveillance. Plus vous jouerez avec `FontSettings`, plus vous serez sûr que vos documents générés apparaissent exactement comme prévu—sans surprises, sans glyphes cassés. + +Des questions ou un scénario de substitution de police difficile ? Laissez un commentaire ci‑dessous, et bon codage ! + +## Tutoriels associés + +- [Définir les paramètres de secours de police](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Définir les paramètres de secours de police](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Définir les paramètres de secours de police](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/java/images-shapes/_index.md b/words/french/java/images-shapes/_index.md index 3eff7e8098..c371f79247 100644 --- a/words/french/java/images-shapes/_index.md +++ b/words/french/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Apprenez à générer des miniatures de haute qualité et des bitmaps de taille ### [Créer un document Word Java – Ajouter une forme rectangle avec effet d'ombre](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Apprenez à insérer une forme rectangle avec ombre dans un document Word en Java à l'aide d'Aspose.Words. +### [Créer une forme rectangle dans un document Word Java – Guide complet étape par étape](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Apprenez à créer une forme rectangle dans un document Word en Java avec un guide complet étape par étape. + ## Ressources supplémentaires - [Documentation Aspose.Words pour Java](https://reference.aspose.com/words/java/) diff --git a/words/french/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/french/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..10aabd08c9 --- /dev/null +++ b/words/french/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Créer une forme rectangulaire dans un document Word en Java et appliquer + un effet d’ombre. Apprenez comment ajouter une ombre à la forme, définir la distance + de l’ombre et enregistrer le fichier. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: fr +og_description: Créer une forme rectangulaire dans un document Word Java, appliquer + un effet d’ombre, ajouter l’ombre à la forme et définir la distance de l’ombre avec + Aspose.Words. +og_title: Créer une forme rectangulaire dans un document Word Java – Guide complet +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Créer une forme rectangulaire dans un document Word Java – Guide complet étape + par étape +url: /fr/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer une forme rectangulaire dans un document Word Java – Guide complet étape par étape + +Vous avez déjà eu besoin de **create rectangle shape** dans un document Word Java mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul—de nombreux développeurs rencontrent ce problème lorsqu'ils génèrent des rapports ou des factures de façon programmatique. Dans ce tutoriel, nous allons vous montrer exactement comment **create rectangle shape**, appliquer une ombre soignée et ajuster la distance de l'ombre afin que le résultat soit professionnel. + +Nous utiliserons Aspose.Words for Java, une bibliothèque robuste qui vous permet de manipuler des fichiers Word sans avoir besoin de Microsoft Office installé. À la fin de ce guide, vous serez capable de créer des projets **create word document java** qui **add shape shadow**, **apply shadow effect**, et **set shadow distance** avec seulement quelques lignes de code. + +--- + +## Ce que vous allez créer + +- Un nouveau fichier `.docx` contenant un rectangle cyan. +- Une ombre portée réaliste, floue, inclinée et partiellement transparente. +- Un contrôle complet sur la distance de l'ombre par rapport à la forme. +- Une classe Java prête à l'exécution que vous pouvez intégrer dans n'importe quel projet Maven ou Gradle. + +Aucun outil externe, aucune étape manuelle d'interface—juste du code pur. + +--- + +## Prérequis + +- Java 8 ou supérieur (le code fonctionne avec Java 11, Java 17, etc.). +- Bibliothèque Aspose.Words for Java (disponible via Maven Central). +- Un IDE ou éditeur de texte de votre choix (IntelliJ IDEA, Eclipse, VS Code…). +- Une connaissance de base de la syntaxe Java. + +Si vous n'avez jamais ajouté de dépendance Maven auparavant, voici le petit extrait : + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Maintenant, plongeons-nous. + +--- + +## Étape 1 : Créer une forme rectangulaire dans un document Word + +La première chose dont nous avons besoin est d'un document vierge et d'un `DocumentBuilder`. Pensez au builder comme à un stylo qui écrit dans le document. Une fois que nous l'avons, nous pouvons **create rectangle shape** avec un seul appel de méthode. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Pourquoi c'est important :** La méthode `insertShape` ne crée pas seulement la géométrie mais ajoute également la forme à la collection interne du document, vous permettant de commencer immédiatement à la styliser. + +--- + +## Étape 2 : Appliquer l'effet d'ombre à la forme + +Maintenant que le rectangle est présent sur la page, nous allons **apply shadow effect**. Les ombres donnent de la profondeur, faisant paraître la forme comme soulevée de la page—une amélioration UI subtile qui peut améliorer la lisibilité des rapports. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Astuce :** Un flou de `5.0` paraît naturel pour la plupart des documents affichés à l'écran. Si vous imprimez, vous pourriez préférer une valeur légèrement inférieure pour éviter un aspect flou. + +--- + +## Étape 3 : Définir la distance de l'ombre – Ajustement fin du placement + +Les ombres ne concernent pas seulement le flou ; elles nécessitent également le bon décalage. C’est ici que nous **set shadow distance**. Une distance de `7.0` points crée un décalage modeste, perceptible mais pas excessif. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Et si vous avez besoin d'un décalage plus grand ?** Augmentez la valeur ; diminuez‑la pour un aspect plus serré. N'oubliez pas que la distance travaille avec l'angle pour positionner correctement l'ombre. + +--- + +## Étape 4 : Enregistrer le document – Persister votre travail + +Enfin, nous écrivons le document sur le disque. Modifiez le chemin vers l'emplacement où vous souhaitez que le fichier soit enregistré. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +L'exécution de la classe crée un fichier `shadow.docx` qui, lorsqu'il est ouvert dans Microsoft Word ou LibreOffice, affiche un rectangle cyan avec une ombre grise douce inclinée à 45° et décalée de 7 points. + +--- + +## Exemple complet fonctionnel + +Ci-dessous se trouve le code complet, prêt à copier‑coller. Il inclut tous les imports, commentaires et l'appel final `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Résultat attendu :** Ouvrez `shadow.docx` → vous verrez un rectangle cyan centré sur la première page, projetant une ombre grise subtile légèrement décalée vers le bas‑à‑droite. Le flou et la transparence de l'ombre donnent l'impression d'un éclairage naturel. + +--- + +## Questions fréquentes & cas particuliers + +### « Puis-je utiliser une forme différente ? » + +Absolument. Remplacez `ShapeType.RECTANGLE` par `ShapeType.OVAL`, `ShapeType.LINE`, ou tout autre enum supporté. Le reste du code d'ombre reste identique. + +### « Et si j’ai besoin de plusieurs ombres ? » + +Aspose.Words ne prend en charge qu'une seule ombre par forme. Pour simuler plusieurs ombres, dupliquez la forme, décalez chaque copie et ajustez la transparence. + +### « L'ombre est‑elle visible dans LibreOffice ? » + +Oui—Aspose.Words écrit du OOXML standard, que LibreOffice interprète correctement. L'ombre peut apparaître légèrement différente selon les moteurs de rendu, mais l'effet persiste. + +### « Comment changer la couleur de l'ombre pour qu'elle corresponde à ma marque ? » + +Il suffit d'échanger `java.awt.Color.GRAY` contre n'importe quel `java.awt.Color` que vous préférez, comme `new java.awt.Color(0, 120, 215)` pour un bleu d'entreprise. + +--- + +## Illustration d'image + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Texte alternatif :* illustration **create rectangle shape** montrant un rectangle cyan avec une ombre portée grise dans un document Word. + +--- + +## Récapitulatif & étapes suivantes + +Nous avons couvert comment **create rectangle shape**, **apply shadow effect**, **add shape shadow**, et **set shadow distance** en utilisant Aspose.Words for Java. Le code est autonome, s'exécute sur n'importe quel JDK moderne, et produit un fichier `.docx` soigné prêt à être distribué. + +Vous voulez aller plus loin ? Essayez : + +- Ajouter du texte à l'intérieur du rectangle avec `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Créer un tableau de formes pour construire un diagramme. +- Exporter le document en PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Chacune de ces actions s'appuie sur les mêmes fondamentaux que nous venons d'explorer, vous permettant d'étendre facilement l'exemple. + +## Réflexions finales + +Maîtriser les tâches **create word document java** comme le façonnage et l’ombrage vous donne un avantage considérable lors de l'automatisation de rapports, contrats ou supports marketing. L'approche présentée ici est propre, maintenable et—plus important—facile à ajuster pour n'importe quel style visuel dont vous avez besoin. + +Testez le code, ajustez le flou, l'angle et la distance, et voyez vos documents passer du fade au raffiné. Si vous rencontrez un problème, laissez un commentaire ci‑dessous ; je serai heureux d'aider. + +Bon codage ! + +## Tutoriels associés + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/german/java/document-conversion-and-export/_index.md index a29231de85..d68ce69a9b 100644 --- a/words/german/java/document-conversion-and-export/_index.md +++ b/words/german/java/document-conversion-and-export/_index.md @@ -99,17 +99,32 @@ Erfahren Sie, wie Sie Tabellen formatieren und Tabellenstile in Aspose.Words for ### [Dokument als TXT speichern – Schnellleitfaden zum Exportieren von Word-Mathematik](./save-document-as-txt-quick-guide-to-exporting-word-math/) Erfahren Sie, wie Sie Word-Dokumente als TXT exportieren und dabei mathematische Formeln korrekt extrahieren. +### [DOCX nach TXT exportieren mit Java – Vollständiger Programmierleitfaden](./export-docx-to-txt-with-java-complete-programming-guide/) +Erfahren Sie, wie Sie DOCX‑Dateien mit Aspose.Words for Java in Textdateien exportieren – Schritt‑für‑Schritt‑Anleitung. + ### [DOCX in Markdown konvertieren – Mathegleichungen nach LaTeX exportieren mit Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) +### [Word als Markdown speichern – Mathematik nach LaTeX exportieren mit Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Erfahren Sie, wie Sie Word-Dokumente in Markdown konvertieren und mathematische Formeln als LaTeX exportieren. + ### [Wie man Bilder in Markdown beim Konvertieren von DOCX einbettet](./how-to-embed-images-in-markdown-when-converting-docx/) Erfahren Sie, wie Sie Bilder aus DOCX extrahieren und korrekt in Markdown einfügen, um einwandfreie Formatierung zu gewährleisten. +### [Bilder als Base64 einbetten beim Konvertieren von DOCX zu Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Erfahren Sie, wie Sie Bilder aus DOCX beim Konvertieren zu Markdown als Base64‑Kodierung einbetten, um korrekte Darstellung sicherzustellen. + ### [Aspose Word zu PDF – DOCX in PDF konvertieren in Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Erfahren Sie, wie Sie DOCX-Dateien mit Aspose.Words for Java einfach in PDF konvertieren. ### [Barrierefreies PDF aus DOCX erstellen – Komplettanleitung](./create-accessible-pdf-from-docx-complete-guide/) Erfahren Sie, wie Sie mit Aspose.Words for Java ein PDF aus DOCX erstellen, das den PDF/UA‑Standards für Barrierefreiheit entspricht. +### [Dokument als PDF speichern mit Aspose.Words Java – Vollständiger Leitfaden zur Barrierefreiheit](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Erfahren Sie, wie Sie mit Aspose.Words für Java PDFs erstellen, die den PDF/UA‑Barrierefreiheitsstandards entsprechen. + +### [Barrierefreies PDF in Java erstellen – Vollständiger Tagging-Leitfaden](./create-accessible-pdf-in-java-full-tagging-guide/) +Erfahren Sie, wie Sie mit Aspose.Words for Java ein vollständig getaggtes, barrierefreies PDF in Java erstellen. + ## Häufig gestellte Fragen **Q: Wie füge ich einem bestehenden PDF mit Aspose.Words ein Wasserzeichen hinzu?** diff --git a/words/german/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/german/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..0344bb0e07 --- /dev/null +++ b/words/german/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-26 +description: Erstellen Sie ein barrierefreies PDF in Java mit Schritt‑für‑Schritt‑Code. + Erfahren Sie, wie Sie PDFs für Barrierefreiheit taggen und das PDF‑Tagging mit PdfSaveOptions + aktivieren. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: de +og_description: Erstellen Sie barrierefreie PDFs in Java mit Schritt‑für‑Schritt‑Code. + Erfahren Sie, wie Sie PDFs für Barrierefreiheit taggen und das PDF‑Tagging mit PdfSaveOptions + aktivieren. +og_title: Barrierefreies PDF in Java erstellen – Vollständiger Tagging‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Barrierefreies PDF in Java erstellen – Vollständiger Tagging‑Leitfaden +url: /de/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Erstellen von barrierefreiem PDF in Java – Vollständiger Tagging-Leitfaden + +Haben Sie sich jemals gefragt, wie man **create accessible PDF**-Dateien direkt aus Java-Code erstellt? Sie sind nicht allein. Viele Entwickler müssen Nutzer unterstützen, die auf Screenreader angewiesen sind, und der Unterschied zwischen einem einfachen PDF und einem barrierefreien kann enorm sein. In diesem Tutorial führen wir Sie durch **how to tag PDF for accessibility**, zeigen Ihnen **how to create tagged PDF** mit Aspose PDF for Java und enthüllen die genauen Schritte, um **add accessibility tags to PDF** hinzuzufügen, damit jeder Leser dieselben Informationen erhält. + +Wir behandeln außerdem **enable PDF tagging** Best Practices, häufige Stolperfallen und ein vollständiges, ausführbares Beispiel, das Sie noch heute in Ihr Projekt einbinden können. Keine vagen Verweise – nur konkreter Code, Erklärungen und eine finale Datei, die Sie in Adobe Acrobat öffnen können, um die Tags zu überprüfen. + +## Was Sie lernen werden + +- Das Warum hinter PDF‑Tagging und Barrierefreiheits‑Compliance. +- Voraussetzungen und Bibliotheks‑Setup (Aspose PDF for Java 23.10 oder neuer). +- Wie man **create accessible PDF** von Grund auf, Schritt für Schritt erstellt. +- Möglichkeiten, **add accessibility tags to PDF** über den einfachen Aufruf `setTagDocumentStructure` hinaus zu verwenden. +- Tipps zum Testen der Ausgabe und zur Fehlersuche bei häufigen Problemen. + +Am Ende dieses Leitfadens können Sie PDFs erzeugen, die WCAG 2.1 AA‑Prüfungen bestehen und gleichzeitig professionell aussehen. + +--- + +## Voraussetzungen + +Bevor wir beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Moderne Sprachfeatures und bessere Unicode‑Unterstützung. | +| **Aspose PDF for Java** (v23.10 oder neuer) | Stellt die Klasse `PdfSaveOptions` und Tagging‑Unterstützung bereit. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Für einfache Kompilierung und Debugging. | +| **Write permission** to a folder where the PDF will be saved | Der Aufruf `doc.save` benötigt einen beschreibbaren Pfad. | + +Wenn Sie Aspose PDF noch nicht zu Ihrem Projekt hinzugefügt haben, fügen Sie die folgende Maven‑Abhängigkeit in Ihre `pom.xml` ein: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Profi‑Tipp:** Verwenden Sie die neueste Version; neuere Releases verbessern die Tagging‑Genauigkeit und fügen sprachspezifische Barrierefreiheits‑Features hinzu. + +--- + +## Schritt 1: Dokument‑Skelett einrichten + +Zuerst erstellen wir ein frisches `Document`‑Objekt. Denken Sie daran wie an eine leere Leinwand, die später die Tags für die Barrierefreiheit aufnehmen wird. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Warum das wichtig ist:** Ohne Inhalt gibt es nichts zu taggen. Das Hinzufügen selbst eines einfachen `TextFragment` gibt der Tagging‑Engine etwas zum Arbeiten, und sie erstellt automatisch ein `

`‑Tag (Paragraph), wenn wir später das Struktur‑Tagging aktivieren. + +--- + +## Schritt 2: PDF‑Speicheroptionen erstellen (der Kern des Taggings) + +Jetzt bereiten wir die Optionen vor, die Aspose PDF mitteilen, einen logischen Strukturbaum in die Datei einzubetten. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Der Aufruf `setTagDocumentStructure(true)` ist der **enable PDF tagging** Schalter. Wenn er auf `true` steht, baut die Bibliothek einen Tag‑Baum, der das visuelle Layout spiegelt, sodass das PDF von unterstützenden Technologien gelesen werden kann. + +> **Hinweis:** Dies ist der einfachste Weg, um **how to create tagged pdf** zu erreichen. Für feinere Kontrolle (z. B. Sprache oder benutzerdefinierte Tags) können Sie `pdfOptions.setTagLanguage("en-US")` und `pdfOptions.setTagStructureTreeRoot(...)` erkunden. + +--- + +## Schritt 3: Barrierefreies PDF speichern + +Abschließend schreiben wir das Dokument mit den konfigurierten Optionen auf die Festplatte. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Wenn `doc.save` abgeschlossen ist, finden Sie `accessible.pdf` im Ordner `output`. Öffnen Sie es in Adobe Acrobat und schauen Sie unter **File → Properties → Description → Tags** – Sie sollten einen ausgefüllten Tag‑Baum sehen. + +--- + +## Wie man PDF für Barrierefreiheit taggt – über die Grundlagen hinaus + +Das obige Drei‑Schritt‑Snippet fügt bereits **adds accessibility tags to PDF** hinzu, aber reale Dokumente benötigen oft noch etwas Feinschliff. Hier ein paar Verbesserungen, die Sie einbauen können: + +### 1. Dokumentsprache festlegen + +Screenreader verwenden das Sprachattribut, um Text korrekt auszusprechen. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Titel und Betreff angeben + +Metadaten helfen assistiven Tools, Kontext zu geben, bevor der Nutzer die Datei überhaupt öffnet. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Bilder mit Alternativtext taggen + +Wenn Sie Bilder einbetten, benötigen sie `alt`‑Beschreibungen. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Tabellenköpfe markieren + +Tabellen sind berüchtigt dafür, Leser zu verwirren, wenn Sie die Kopfzeilen nicht kennzeichnen. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Diese zusätzlichen Schritte machen Ihr PDF nicht nur *technisch* getaggt, sondern wirklich **accessible** für ein vielfältiges Publikum. + +--- + +## Häufige Fallstricke beim Aktivieren von PDF‑Tagging + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Tags missing in Acrobat | `setTagDocumentStructure` left as `false` | Ensure you call `pdfOptions.setTagDocumentStructure(true)`. | +| Wrong reading order | Complex layout without explicit tags | Use `pdfOptions.setTagStructureTreeRoot(...)` to define a custom order. | +| Images read as “image” without description | No alternative text set | Call `image.getAlternativeText().setValue("...")`. | +| Language not recognized | `setTagLanguage` omitted or wrong locale | Provide a BCP‑47 language code (`en-US`, `fr-FR`). | + +Das Bewusstsein für diese Probleme spart Ihnen später Stunden an Fehlersuche. + +--- + +## Ergebnis überprüfen – Was zu erwarten ist + +Nach dem Ausführen des Programms öffnen Sie `output/accessible.pdf` in Adobe Acrobat Reader: + +1. **Tags panel** (`View → Show/Hide → Navigation Panes → Tags`) sollte eine Hierarchie wie `/Document → /Part → /Sect → /Para` anzeigen. +2. **Reading order** sollte dem visuellen Fluss folgen (Text zuerst, dann Bilder). +3. **Screen reader** (NVDA, VoiceOver) liest “Hello, accessible PDF!” statt nur “Page 1”. + +Falls einer dieser Punkte fehlt, überprüfen Sie die obigen Schritte erneut – insbesondere den Aufruf `setTagDocumentStructure`. + +--- + +## Vollständiges funktionierendes Beispiel (Copy‑Paste‑bereit) + + + +## Verwandte Tutorials + +- [Erstelle barrierefreies PDF aus Word – Konvertiere zu PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Erstelle barrierefreies PDF aus DOCX – Komplettanleitung](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Wie man ein Dokument als PDF mit Aspose.Words für Java speichert](/words/english/java/document-loading-and-saving/saving-documents-as-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/german/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/german/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..16bfa52e16 --- /dev/null +++ b/words/german/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Binden Sie Bilder als Base64 ein, während Sie DOCX mit Aspose.Words für + Java in Markdown konvertieren. Erfahren Sie, wie Sie Word in Markdown konvertieren, + Word als Markdown speichern und Bilder verarbeiten. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: de +og_description: Binden Sie Bilder als Base64 ein, während Sie DOCX mit Aspose.Words + für Java in Markdown konvertieren. Vollständige Anleitung zur Umwandlung von Word + in Markdown und zum Speichern von Word als Markdown. +og_title: Bilder als Base64 einbetten beim Konvertieren von DOCX zu Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Bilder beim Konvertieren von DOCX zu Markdown als Base64 einbetten +url: /de/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bilder als Base64 einbetten beim Konvertieren von DOCX zu Markdown + +Haben Sie sich jemals gefragt, wie man **Bilder als Base64 einbettet**, während man **docx zu markdown konvertiert**? Sie sind nicht allein – Entwickler fragen ständig, wie man Bilder inline hält, ohne separate Dateien zu jonglieren. Die gute Nachricht ist, dass Aspose.Words for Java das ganz einfach macht: Sie können ein Word‑Dokument in Markdown konvertieren und automatisch jedes Bild als Base64‑String einbetten. + +In diesem Tutorial führen wir Sie durch den gesamten Prozess – vom Laden einer `.docx`, die Bilder enthält, über das Konfigurieren eines `MarkdownSaveOptions`‑Callbacks, das die schwere Arbeit übernimmt, bis hin zum Speichern des Ergebnisses als saubere `.md`‑Datei. Am Ende wissen Sie genau, wie man **Word zu Markdown konvertiert**, **Bilder zu Base64 konvertiert** und **Word als Markdown speichert**, ohne dass Bildordner zurückbleiben. Keine externen Werkzeuge, keine manuelle Nachbearbeitung – nur reiner Java‑Code, den Sie in jedes Projekt einbinden können. + +## Was Sie benötigen + +- **Java 17** (oder ein aktuelles JDK) – der Code verwendet Lambda‑Syntax, Sie können ihn jedoch an ältere Versionen anpassen. +- **Aspose.Words for Java** Bibliothek (neueste Version ab 2026). Fügen Sie die Maven‑Abhängigkeit oder das JAR zu Ihrem Klassenpfad hinzu. +- Eine Beispiel‑**DOCX**‑Datei, die mindestens ein Bild enthält. +- Eine IDE oder ein einfacher Texteditor – Visual Studio Code, IntelliJ IDEA oder sogar `vim` reichen aus. + +Wenn Sie das bereits haben, großartig – lassen Sie uns gleich loslegen. + +## Schritt 1: Word‑Dokument laden + +Zuerst erstellen wir eine `Document`‑Instanz, die auf die Quelldatei verweist. Das ist derselbe Schritt, egal ob Sie **docx zu markdown konvertieren** oder die Datei nur für andere Zwecke lesen. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Warum das wichtig ist:** Das `Document`‑Objekt ist der Einstiegspunkt für jede Aspose‑Operation. Es enthält die gesamte Word‑Struktur – einschließlich Bilder, Tabellen und Stile – sodass der spätere Callback jede Ressource inspizieren kann. + +## Schritt 2: MarkdownSaveOptions erstellen und einen Resource‑Saving‑Callback registrieren + +Die Magie steckt in `MarkdownSaveOptions`. Durch das Anhängen eines `IResourceSavingCallback` erhalten wir die Kontrolle darüber, wie jede externe Ressource (wie ein Bild) geschrieben wird. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Warum `setSaveToMemory(true)` verwenden? + +Wenn `saveToMemory` true ist, schreibt Aspose die Bildbytes in einen Memory‑Stream statt in eine Datei. Der Markdown‑Exporter konvertiert dann diesen Stream in einen Base64‑String und fügt ihn direkt in das Markdown‑Image‑Tag ein: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Das ist das Kernprinzip von **Bilder als Base64 einbetten**. + +## Schritt 3: Dokument als Markdown speichern + +Jetzt, wo der Callback eingerichtet ist, besteht der letzte Schritt einfach darin, `save` aufzurufen. Hier wird tatsächlich **Word zu Markdown konvertiert** und, dank des Callbacks, auch **Bilder zu Base64 konvertiert**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Ergebnis:** `out.md` enthält Markdown‑Text, wobei jedes Bild als `data:`‑URI dargestellt wird. Es werden keine zusätzlichen Bilddateien auf der Festplatte erstellt, sodass der Ordner aufgeräumt bleibt. + +## Schritt 4: Ausgabe überprüfen und häufige Stolperfallen + +Öffnen Sie die erzeugte `out.md` in einem beliebigen Markdown‑Viewer (VS Code, GitHub oder einem Static‑Site‑Generator). Sie sollten etwas Ähnliches sehen: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Fehlersuch‑Checkliste + +| Problem | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| Bild erscheint als defekter Link | `setSaveToMemory` wurde weggelassen | Stellen Sie sicher, dass `args.setSaveToMemory(true);` im Callback enthalten ist | +| Base64‑String ist abgeschnitten | Kodierung der Ausgabedatei stimmt nicht überein | Speichern Sie das Markdown mit UTF‑8 (Standard für Aspose) | +| Unerwartete Dateinamen | `setKeepResourceOriginalName(true)` | Setzen Sie es auf `false`, um die benutzerdefinierte Namenslogik zu erzwingen | + +## Schritt 5: Erweiterte Varianten (optional) + +### Nur ausgewählte Bilder konvertieren + +Wenn Sie nur bestimmte Bilder einbetten möchten (z. B. solche, die größer als 100 KB sind), fügen Sie eine Größenprüfung hinzu: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Ein anderes Bildformat verwenden + +`ResourceSavingArgs` liefert Ihnen die Rohbytes, sodass Sie JPEGs vor dem Einbetten als PNGs neu kodieren könnten – nützlich, wenn der Ziel‑Markdown‑Viewer PNG bevorzugt. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Diese Anpassungen zeigen, wie flexibel der Ansatz **Bilder als Base64 einbetten** ist, wenn Sie **docx zu markdown konvertieren**. + +## Fazit + +Sie haben gerade gelernt, wie man **Bilder als Base64 einbettet**, während man **docx zu markdown konvertiert** mit Aspose.Words for Java. Durch das Anschließen eines einfachen `IResourceSavingCallback` übernimmt die Bibliothek die gesamte Schwerstarbeit: Sie **konvertiert Word zu Markdown**, **konvertiert Bilder zu Base64** und schließlich **speichert Word als Markdown** mit einem einzigen `save`‑Aufruf. + +Fühlen Sie sich frei zu experimentieren – probieren Sie verschiedene Bild‑Filterregeln aus, wechseln Sie zur HTML‑Ausgabe oder verketten Sie diesen Schritt mit einem Static‑Site‑Generator. Das gleiche Muster funktioniert auch für andere Formate (HTML, EPUB), sodass Sie den Callback überall wiederverwenden können, wo Sie Inline‑Ressourcen benötigen. + +**Nächste Schritte:** +- Erkunden Sie `HtmlSaveOptions` für HTML‑mit‑Base64‑Bildern. +- Kombinieren Sie dies mit einer CI‑Pipeline, um die Dokumentationsgenerierung zu automatisieren. +- Tauchen Sie in Aspose’s `DocumentVisitor` ein, wenn Sie noch feinere Kontrolle über den Konvertierungsprozess benötigen. + +Viel Spaß beim Coden und genießen Sie Ihre sauberen, eigenständigen Markdown‑Dateien! + +## Verwandte Tutorials + +- [Wie man Bilder in Markdown einbettet beim Konvertieren von DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [docx zu markdown konvertieren – Mathematische Gleichungen nach LaTeX exportieren mit Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Bilder aus Word speichern – Aspose.Words für Java Leitfaden](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/german/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..840a16c2f6 --- /dev/null +++ b/words/german/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Exportiere docx nach txt mit Java und Aspose.Words. Erfahre, wie du docx + in Text konvertierst, Unicode beibehältst und Word in wenigen Schritten als txt + exportierst. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: de +og_description: Exportiere docx nach txt in Java. Dieses Tutorial zeigt, wie man docx + in Text konvertiert, Unicode‑Plain‑Text beibehält und Word effizient als txt exportiert. +og_title: Exportieren von DOCX nach TXT mit Java – Komplettanleitung +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Export von docx nach txt mit Java – Vollständiger Programmierleitfaden +url: /de/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Export docx nach txt mit Java – Vollständiger Programmierleitfaden + +Haben Sie jemals **docx nach txt exportieren** müssen, waren aber besorgt, Sonderzeichen zu verlieren? Sie sind nicht der Einzige. Wenn Sie Word‑Dokumente in reine Textdateien konvertieren, können Unicode‑Symbole, Tabellen und sogar einfache Formatierungen wie von Zauberhand verschwinden. + +In diesem Leitfaden zeigen wir Ihnen eine zuverlässige Methode, **docx nach txt zu exportieren** mit Aspose.Words für Java, wobei jedes Unicode‑Zeichen erhalten bleibt und Tabellenlayouts lesbar bleiben. Am Ende wissen Sie außerdem, wie man **docx in Text konvertiert**, **Word in Text konvertiert** und sogar **Word als txt exportiert** – ganz ohne Probleme. + +## Was dieses Tutorial behandelt + +* Aspose.Words in einem Java‑Projekt einrichten +* Laden einer DOCX‑Datei und Vorbereitung für die reine Textausgabe +* Konfigurieren der Unterstützung für **plain text unicode** über `TxtSaveOptions` +* Optionale Tricks, um Tabellen im resultierenden `.txt`‑Datei lesbar zu halten +* Speichern der Datei und Überprüfen der Ausgabe + +Keine externen Skripte, keine mysteriösen Befehlszeilentools – nur reiner Java‑Code, den Sie in jedes Maven‑ oder Gradle‑Projekt einbinden können. + +> **Warum das wichtig ist?** Plain‑Text‑Dateien sind leichtgewichtig, versionskontrollfreundlich und perfekt für die Such‑Indexierung oder nachgelagerte Verarbeitungspipelines. Wenn Sie jemals versucht haben, eine Word‑Datei mit `cat` anzuzeigen und nur Kauderwelsch erhalten haben, löst dieses Tutorial dieses Problem. + +--- + +## Export docx nach txt – Übersicht + +Bevor wir in den Code eintauchen, klären wir die Terminologie. **docx nach txt exportieren** bedeutet, ein Microsoft‑Word‑`.docx`‑Paket zu nehmen und dessen Textinhalt in eine einfache `.txt`‑Datei zu schreiben. Im Gegensatz zu einer PDF‑Konvertierung entfernt ein Text‑Export das Styling, kann jedoch Zeilenumbrüche, Absatzmarkierungen und – wenn Sie es richtig konfigurieren – Unicode‑Zeichen wie Emojis, akzentuierte Buchstaben oder asiatische Schriften beibehalten. + +Aspose.Words macht das mühelos, weil es das Word‑Dateiformat abstrahiert und eine `TxtSaveOptions`‑Klasse bereitstellt, mit der Sie die Kodierung, Tabellenverarbeitung und mehr festlegen können. + +### Voraussetzungen + +* Java 11 oder neuer (die API funktioniert mit Java 8+, aber wir gehen von einem aktuellen JDK aus) +* Aspose.Words für Java JAR (verfügbar über Maven Central) +* Eine Beispiel‑`unicode.docx`‑Datei, die verschiedene Unicode‑Zeichen enthält – denken Sie an „こんにちは“, „😊“ und eine einfache Tabelle + +Wenn Sie diese haben, legen wir los. + +--- + +## Schritt 1: Laden der DOCX‑Datei (docx in Text konvertieren) + +Das Erste, was Sie tun müssen, ist das Quelldokument in den Speicher zu lesen. Hier beginnt der **docx in Text konvertieren**‑Prozess offiziell. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Warum das wichtig ist:* `Document` ist die Darstellung einer Word‑Datei in Aspose.Words. Durch das Laden erhalten Sie Zugriff auf alle Absätze, Tabellen und sogar versteckte Elemente. Wenn die Datei nicht gefunden wird, wirft Aspose eine klare `FileNotFoundException`, sodass Sie sofort wissen, was schiefgelaufen ist. + +--- + +## Schritt 2: TxtSaveOptions für Unicode konfigurieren (Plain text unicode) + +Plain‑Text‑Dateien sind lediglich Byte‑Streams, daher müssen Sie Java mitteilen, welchen Zeichensatz es verwenden soll. UTF‑8 ist der De‑Facto‑Standard für **plain text unicode**, weil er jeden Unicode‑Code‑Punkt kodieren kann. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro‑Tipp:** Wenn Sie den Aufruf `setEncoding` weglassen, verwendet Aspose standardmäßig den Standard‑Zeichensatz der Plattform, der auf vielen Windows‑Maschinen Windows‑1252 ist. Dieser Standard lässt Zeichen wie „ß“ oder „—“ stillschweigend wegfallen. + +--- + +## Schritt 3: Tabellenlayout erhalten (Optional, aber praktisch für die Lesbarkeit) + +Wenn Sie **Word als txt exportieren**, werden Tabellen normalerweise zu einer einzigen Textzeile abgeflacht, was sie unlesbar macht. Aspose.Words bietet ein einfaches Flag, um die visuelle Struktur beizubehalten. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Wann Sie es verwenden sollten:* Wenn Ihr Quell‑DOCX Rechnungen, Zeitpläne oder andere rasterähnliche Daten enthält, fügt das Aktivieren von `PreserveTableLayout` Tabs und Zeilenumbrüche ein, sodass die resultierende Datei immer noch einer Tabelle ähnelt. Wenn Sie das nicht benötigen, können Sie die Zeile weglassen und erhalten eine kompaktere Ausgabe. + +--- + +## Schritt 4: Dokument als Plain‑Text speichern (Word als txt exportieren) + +Jetzt ist die schwere Arbeit erledigt – schreiben Sie einfach die Bytes auf die Festplatte. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Das Ausführen des Programms erzeugt `plain.txt` im selben Ordner. Öffnen Sie es mit einem beliebigen Texteditor (Notepad++, VS Code, sogar `cat` im Terminal) und Sie werden sehen: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Beachten Sie, wie die japanische Begrüßung und das Smiley erhalten blieben und die Tabelle dank `PreserveTableLayout` ihre Spalten behielt. Das ist das Wesentliche eines sauberen **docx nach txt Exports**. + +--- + +## Schritt 5: Ausgabe überprüfen (Sanity‑Check beim Word‑zu‑Text‑Konvertieren) + +Ein schneller Sanity‑Check verhindert stillen Datenverlust. Hier sind einige Möglichkeiten, um sicherzustellen, dass Sie **Word korrekt in Text konvertieren**: + +1. **Checksum-Vergleich** – berechnen Sie einen SHA‑256‑Hash der `.txt`‑Datei vor und nach einer Rundreise‑Konvertierung (txt → docx → txt), um die Stabilität sicherzustellen. +2. **Nach Unicode‑Markern suchen** – verwenden Sie `grep` oder die IDE‑Suche‑im‑Datei, um Zeichen wie „😊“ zu finden. +3. **In mehreren Editoren öffnen** – einige alte Windows‑Notepad‑Versionen interpretieren UTF‑8 ohne BOM immer noch falsch; das Öffnen der Datei in VS Code bestätigt die korrekte Kodierung. + +Wenn einer dieser Checks fehlschlägt, prüfen Sie erneut, ob `saveOptions.setEncoding(StandardCharsets.UTF_8)` vorhanden ist und ob Ihr Quell‑DOCX tatsächlich Unicode‑Text enthält. + +--- + +## Häufige Fallstricke & wie man sie vermeidet + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **Fehlende Zeichen** | Der Standard‑System‑Zeichensatz (z. B. Windows‑1252) lässt Nicht‑ASCII‑Glyphen weg. | Setzen Sie explizit UTF‑8 über `saveOptions.setEncoding`. | +| **Tabellen werden zu einer einzigen Zeile** | `PreserveTableLayout` bleibt standardmäßig `false`. | Rufen Sie `saveOptions.setPreserveTableLayout(true)` auf. | +| **Datei nicht gefunden** | Falscher Pfad oder fehlende Leseberechtigungen. | Verwenden Sie absolute Pfade oder `Paths.get(...)` mit geeigneter Fehlerbehandlung. | +| **Leistungsabfall bei riesigen Dokumenten** | Das gesamte Dokument wird vollständig in den Speicher geladen. | Streamen Sie das Dokument in Teilen mit `DocumentBuilder`, wenn Sie nur bestimmte Abschnitte benötigen. | + +--- + +## Bonus: Mehrere DOCX‑Dateien stapelweise exportieren + +Wenn Sie **docx in Text konvertieren** für einen ganzen Ordner müssen, verpacken Sie die Logik in einer Schleife: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Dieses Snippet **exportiert docx nach txt** für jede Datei im Verzeichnis und spart Ihnen Stunden manueller Arbeit. + +--- + +## Fazit + +Sie haben gerade gelernt, wie man **docx nach txt** mit Java **exportiert**, wobei jedes Unicode‑Zeichen erhalten bleibt, Tabellen lesbar bleiben und der gesamte Prozess wiederholbar ist. Durch die Konfiguration von `TxtSaveOptions` für UTF‑8 und das optionale Beibehalten von Tabellenlayouts können Sie zuverlässig **docx in Text konvertieren**, **Word in Text konvertieren** und **Word als txt exportieren** für jede nachgelagerte Arbeitsablauf. + +Bereit für die nächste Herausforderung? Versuchen Sie, in andere Plain‑Text‑Formate wie Markdown (`.md`) oder CSV zu exportieren, oder erkunden Sie die PDF‑Konvertierungsfunktionen von Aspose.Words. Die gleichen Prinzipien – explizite Kodierung, Layout‑Erhaltung und gründliche Verifizierung – gelten überall. + +Viel Spaß beim Programmieren, und möge Ihre Textdateien stets Unicode‑reich bleiben! + +--- + +![Diagramm, das die Export‑docx‑nach‑txt‑Pipeline zeigt](/images/export-docx-to-txt-pipeline.png){alt="Diagramm, das die Export‑docx‑nach‑txt‑Pipeline zeigt"} + +## Verwandte Tutorials + +- [Docx nach Txt konvertieren](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – DOCX nach PDF in Java konvertieren](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Docx nach Markdown konvertieren – Mathegleichungen nach LaTeX exportieren mit Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/german/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..e10b67542b --- /dev/null +++ b/words/german/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Dokument als PDF mit Aspose.Words Java speichern und Barrierefreiheit + zum PDF hinzufügen. Lernen Sie, DOCX in PDF zu konvertieren, horizontale Linien + zu taggen und die PDF/UA‑2‑Konformität sicherzustellen. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: de +og_description: Dokument mit Aspose.Words Java als PDF speichern und gleichzeitig + Barrierefreiheit zum PDF hinzufügen. Schritt‑für‑Schritt‑Anleitung zum Konvertieren + von DOCX in PDF und zum Taggen von Horizontalregeln für PDF/UA‑2‑Konformität. +og_title: Dokument als PDF mit Aspose.Words Java speichern – Barrierefreiheit leicht + gemacht +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Dokument als PDF mit Aspose.Words Java speichern – Vollständiger Leitfaden + zur Barrierefreiheit +url: /de/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Dokument als PDF speichern mit Aspose.Words Java – Vollständiger Leitfaden zur Barrierefreiheit + +Haben Sie sich jemals gefragt, wie man **save document as PDF** speichert und dabei die Zugänglichkeit für Bildschirmleser gewährleistet? Sie sind nicht allein. Viele Entwickler müssen *convert docx to pdf* und gleichzeitig die PDF/UA‑2‑Standards einhalten, insbesondere wenn die Quelle horizontale Linien enthält, die korrekt getaggt werden müssen. In diesem Tutorial führen wir Sie Schritt für Schritt durch die genauen Schritte, um **save document as PDF** mit Aspose.Words für Java zu **add accessibility to PDF** und sicherzustellen, dass jede horizontale Linie **tagged** als Artefakt markiert wird. + +Wir beginnen mit einem sauberen Java‑Projekt, laden ein DOCX, das bereits horizontale Linien enthält, konfigurieren die PDF‑Speicheroptionen für PDF/UA‑2‑Konformität und schreiben schließlich ein vollständig zugängliches PDF. Am Ende können Sie **save document as pdf** mit der Gewissheit ausführen, dass es die Barrierefreiheitsprüfungen besteht. + +## Voraussetzungen + +- Java 8 oder neuer installiert (das Tutorial wurde mit JDK 17 getestet). +- Maven 3.6+ (oder Gradle, falls Sie es bevorzugen) zur Verwaltung der Abhängigkeiten. +- Eine gültige Aspose.Words für Java‑Lizenz (die kostenlose Testversion funktioniert, aber eine Lizenz entfernt Evaluationswasserzeichen). +- Eine DOCX‑Datei (`input.docx`), die mindestens eine horizontale Linie enthält – denken Sie an einen einfachen Trennstrich, den Sie in Word einfügen würden. + +> **Pro Tipp:** Wenn Sie keine DOCX-Datei zur Hand haben, erstellen Sie einfach ein neues Word‑Dokument, schreiben ein paar Absätze, fügen *Einfügen → Horizontale Linie* ein, speichern es als `input.docx` und legen es in einem Ordner Ihrer Wahl ab. + +## Schritt 1: Maven‑Projekt einrichten + +Zuerst erstellen Sie ein neues Maven‑Projekt (oder fügen es zu einem bestehenden hinzu). Die `pom.xml` benötigt die Aspose.Words‑Abhängigkeit: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Warum das wichtig ist:** Das Hinzufügen des `aspose-words`‑Artifacts ist der erste Schritt zu *convert docx to pdf*. Ohne dieses erkennt der Compiler `Document`, `PdfSaveOptions` und andere wichtige Klassen nicht. + +## Schritt 2: Laden des Quell‑DOCX mit horizontalen Linien + +Jetzt schreiben wir eine kleine Java‑Klasse, die das DOCX lädt. Hier beginnt der Teil **tag horizontal rules** – Aspose.Words behandelt eine horizontale Linie automatisch als Absatz mit Rahmen, aber wir lassen die PDF/UA‑Engine das Tagging übernehmen. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Beachten Sie, dass wir noch nichts gespeichert haben – wir **laden** nur das DOCX, was die erste Hälfte von *convert docx to pdf* ist. Das `Document`‑Objekt enthält nun den gesamten Word‑Inhalt, einschließlich aller von Ihnen eingefügten horizontalen Linien. + +## Schritt 3: PDF‑Speicheroptionen für PDF/UA‑2‑Konformität konfigurieren + +Die Magie von **add accessibility to PDF** steckt in `PdfSaveOptions`. Durch Setzen des Konformitätslevels auf `PDF_UA_2` wird Aspose.Words: + +1. Strukturelle Elemente (Überschriften, Tabellen usw.) taggen. +2. Dekorative Elemente – wie horizontale Linien – als *Artifacts* markieren, sodass Bildschirmleser sie ignorieren. +3. Die erforderlichen PDF/UA‑Metadaten einfügen. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Warum Konformität setzen?** Ohne `PDF_UA_2` kann das resultierende PDF zwar lesbar sein, besteht jedoch nicht die automatischen Barrierefreiheitsprüfungen. Die Anforderung **tag horizontal rules** wird automatisch erfüllt, da PDF/UA sie als *Artifacts* behandelt, wenn das Konformitäts‑Flag gesetzt ist. + +## Schritt 4: Dokument als PDF speichern + +Jetzt führen wir endlich **save document as pdf** aus. Diese eine Zeile übernimmt die Hauptarbeit – das Konvertieren des DOCX, das Anwenden der Barrierefreiheits‑Tags und das Schreiben der Datei auf die Festplatte. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Führen Sie die Klasse aus (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) und Sie sehen eine Bestätigungsnachricht. Öffnen Sie das resultierende `ua_compliant.pdf` in Adobe Acrobat und prüfen Sie **File → Properties → Description → PDF/A, PDF/UA** – dort sollte „PDF/UA‑2“ angezeigt werden. + +### Erwartete Ausgabe + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Öffnen Sie das PDF, und Sie bemerken: + +- Der Dokumenttext ist auswählbar und durchsuchbar. +- Die horizontale Linie ist für Bildschirmleser unsichtbar (als Artefakt behandelt). +- Das PDF besteht grundlegende PDF/UA‑Validierungstools (z. B. PAC 3). + +## Schritt 5: Barrierefreiheit überprüfen – Schnell‑Checkliste + +Obwohl Aspose.Words den Großteil der Arbeit übernimmt, ist es gute Praxis, das Ergebnis zu überprüfen. + +| Prüfung | Wie prüfen | +|-------|----------------| +| **Document title** | Öffnen Sie Acrobat → File → Properties → Title‑Feld (sollte `pdfOptions.setTitle` entsprechen). | +| **Artifact tagging** | Verwenden Sie Acrobats „Reading Order“-Werkzeug. Horizontale Linien sollten als *Artifact* (grau) erscheinen. | +| **Logical reading order** | Führen Sie den „Accessibility Checker“ in Acrobat aus; stellen Sie sicher, dass keine strukturellen Fehler vorliegen. | +| **Tagged PDF** | In Acrobat schauen Sie im „Tags“-Panel – Sie sollten eine Hierarchie sehen (Document → Section → Paragraph usw.). | +| **PDF/UA compliance** | Acrobat zeigt unter dem Reiter „Standards“ „PDF/UA‑2“ an. | + +Falls einer dieser Checks fehlschlägt, überprüfen Sie, ob Sie die neueste Aspose.Words‑Version verwenden und `setCompliance(PdfCompliance.PDF_UA_2)` korrekt angewendet wurde. + +## Häufige Fallstricke & wie man sie vermeidet + +1. **Missing License** – Die Testversion fügt ein Wasserzeichen hinzu, das die PDF/UA‑Validierung brechen kann. Wenden Sie Ihre Lizenz früh im `main` an: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – Eine `FileNotFoundException` stoppt die Konvertierung. Verwenden Sie absolute Pfade oder legen Sie das DOCX im Projekt‑Root ab und referenzieren Sie es mit `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – PDF/UA‑Unterstützung wurde in Version 22.9 hinzugefügt. Aktualisieren Sie auf die neueste Version, um fehlende Funktionen zu vermeiden. +4. **Horizontal Rule as Image** – Wenn Sie die Linie als Bild statt als native Word‑Horizontallinie eingefügt haben, behandelt Aspose sie als reguläres Bild, nicht als Artefakt. Ersetzen Sie das Bild durch Word’s integrierte *Horizontal Line* für korrektes Tagging. + +## Lösung erweitern – Was, wenn Sie mehr benötigen? + +- **Custom Tags**: Wenn Sie andere dekorative Elemente (z. B. dekorative Icons) haben, können Sie diese manuell als Artefakte markieren, indem Sie `PdfSaveOptions.setArtifactTaggingEnabled(true)` verwenden. +- **Multiple Documents**: Durchlaufen Sie einen Ordner mit DOCX‑Dateien und konvertieren Sie sie stapelweise, wobei Sie dieselbe `PdfSaveOptions`‑Instanz zur Leistungssteigerung wiederverwenden. +- **Adding a Language Tag**: Für mehrsprachige PDFs setzen Sie `pdfOptions.setLanguage("en-US")`, um assistiven Technologien die richtige Stimme zuzuweisen. + +## Vollständiges funktionierendes Beispiel (Gesamter Code zusammen) + +Unten finden Sie das komplette, ausführbare Java‑Programm. Kopieren Sie es in Ihre IDE, passen Sie die Pfade an und führen Sie es aus. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Führen Sie es aus, öffnen Sie das erzeugte PDF, und Sie haben eine saubere, barrierefreie Datei, die bereit zur Verteilung ist. + +## Fazit + +Wir haben gerade gezeigt, wie man **save document as pdf** mit Aspose.Words für Java automatisch **add accessibility to pdf** und **tag horizontal rules** als Artefakte speichert. Die wichtigsten Erkenntnisse: + +- Verwenden Sie `PdfSaveOptions` mit `PDF_UA_2`‑Konformität, um die Barrierefreiheitsstandards zu erfüllen. +- Das Laden eines DOCX und Aufrufen von `doc.save(..., pdfOptions)` reicht aus, um **convert docx to pdf** durchzuführen. +- Horizontale Linien werden für Sie verarbeitet – kein zusätzlicher Code nötig, wodurch die Anforderung **tag horizontal rules** erfüllt wird. +- Der Ansatz ist vollständig **aspose convert docx pdf**‑konform, funktioniert mit der neuesten Bibliotheksversion und erzeugt ein validierungsbereites PDF. + +Bereit für die nächste Herausforderung? Versuchen Sie, benutzerdefinierte Metadaten hinzuzufügen, Schriftarten einzubetten oder eine Stapelverarbeitung eines ganzen Ordners mit DOCX‑Dateien durchzuführen. Jede dieser Erweiterungen baut auf derselben Grundlage auf, die wir hier gelegt haben. + +Haben Sie Fragen zu PDF/UA‑Konformität, Lizenzierung oder dem Umgang mit anderen Word‑Elementen? Hinterlassen Sie einen Kommentar oder prüfen Sie die offizielle Dokumentation von Aspose – es gibt eine Fülle von Beispielen zu entdecken. Viel Spaß beim Programmieren und beim Erstellen barrierefreier PDFs! + +![Dokument als PDF speichern mit Aspose.Words Java – Beispiel für ein barrierefreies PDF](placeholder-image.png "Dokument als PDF speichern mit Aspose.Words Java – Beispiel für ein barrierefreies PDF") + +## Verwandte Tutorials + +- [Wie man ein Dokument als PDF mit Aspose.Words für Java speichert](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Wie man Word mit Aspose.Words für Java in PDF konvertiert](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – DOCX in PDF in Java konvertieren](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/german/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..0b03a39c9a --- /dev/null +++ b/words/german/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-26 +description: Speichern Sie Word als Markdown und entdecken Sie, wie Sie mathematische + Gleichungen mit Aspose.Words für Java nach LaTeX exportieren können. Konvertieren + Sie Word‑Gleichungen nach LaTeX in nur wenigen Zeilen. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: de +og_description: Speichern Sie Word als Markdown und lernen Sie, wie Sie mathematische + Gleichungen mit Aspose.Words für Java nach LaTeX exportieren. Ein vollständiger, + ausführbarer Leitfaden. +og_title: Word als Markdown speichern – Mathematik nach LaTeX exportieren mit Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Word als Markdown speichern – Mathematik nach LaTeX exportieren mit Java +url: /de/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word als Markdown speichern – Mathematik nach LaTeX exportieren mit Java + +Haben Sie jemals **Word als Markdown speichern** müssen, aber befürchtet, dass Ihre Gleichungen zu einem wirren Durcheinander werden? Sie sind nicht allein. In diesem Leitfaden zeigen wir Ihnen **wie man Mathematik exportiert** aus einer `.docx`‑Datei direkt nach LaTeX, während der Rest des Dokuments zu sauberem Markdown wird. + +Wir behandeln alles, von der Einrichtung der Aspose.Words‑Bibliothek bis zur Überprüfung der finalen `out.md`‑Datei. Am Ende können Sie **Word‑Gleichungen nach LaTeX konvertieren** mit einem einzigen Methodenaufruf und verstehen die kleinen Nuancen, die die Konvertierung zuverlässig machen. + +--- + +## Was Sie benötigen + +- **Java 8+** – der Code läuft auf jedem aktuellen JDK. +- **Aspose.Words for Java** – entweder die Maven/Gradle‑Abhängigkeit oder das JAR, wenn Sie die manuelle Einrichtung bevorzugen. +- Ein Word‑Dokument (`math.docx`), das mindestens eine Office Math‑Gleichung enthält. +- Eine IDE oder reiner `javac`/`java`‑Befehl – je nachdem, womit Sie sich wohlfühlen. + +Wenn Sie das bereits haben, großartig. Wenn nicht, zeigt der nächste Abschnitt genau, wie Sie die Bibliothek in Ihr Projekt einbinden. + +## Word als Markdown speichern – Schritt 1: Aspose.Words zu Ihrem Projekt hinzufügen + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Profi‑Tipp:** Aspose bietet eine kostenlose temporäre Lizenz zum Testen an. Legen Sie die Datei `license.xml` in Ihren Ressourcenordner und rufen Sie `License license = new License(); license.setLicense("license.xml");` auf, bevor Sie ein Dokument laden. + +Sobald die Abhängigkeit aufgelöst ist, können Sie den Konvertierungscode schreiben. + +## Wie man mathematische Gleichungen nach LaTeX exportiert + +Die eigentliche Arbeit erledigt `MarkdownSaveOptions`. Indem Sie dessen `OfficeMathExportMode` auf `LATEX` umstellen, wird jedes Office‑Math‑Objekt als LaTeX‑Fragment im Markdown‑Ausgabe eingebettet. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Warum das funktioniert + +- **`Document`** ist Asposes Einstiegspunkt; es abstrahiert die `.docx`‑Datei und gibt Ihnen Zugriff auf jeden Knoten, einschließlich Gleichungen. +- **`MarkdownSaveOptions`** teilt der Bibliothek mit, *wie* die Ausgabe aussehen soll. Das Standardverhalten ist, Gleichungen als Bilder zu rendern, was dem Zweck eines textbasierten Formats widerspricht. +- **`OfficeMathExportMode.LATEX`** zwingt die Engine, jeden `OfficeMath`‑Knoten in sein LaTeX‑Äquivalent zu übersetzen, das Markdown‑Parser (wie GitHub oder Jekyll) rendern können, wenn ein MathJax‑Plugin eingebunden ist. + +## Word‑Gleichungen nach LaTeX konvertieren – Schritt 2: Markdown‑Ausgabe überprüfen + +Nach dem Ausführen des Programms öffnen Sie `out.md`. Sie sollten etwas Ähnliches sehen: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Hinweis:** Die LaTeX‑Fragmente sind in `$…$` für Inline‑Mathematik und `$$…$$` für Block‑Mathematik eingeschlossen. Das ist die Standardsyntax, die die meisten statischen Site‑Generatoren verstehen, wenn MathJax aktiviert ist. + +Wenn Sie bevorzugen, dass die Gleichungen nur inline bleiben, können Sie die `MarkdownSaveOptions` weiter anpassen: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx zu Markdown LaTeX – Schritt 3: Sonderfälle & häufige Fallstricke + +| Situation | Worauf zu achten ist | Lösung | +|-----------|----------------------|--------| +| **Komplexe verschachtelte Gleichungen** | Aspose kann zusätzliche geschweifte Klammern `{}` ausgeben, die manche Parser wörtlich behandeln. | Das Markdown mit einem einfachen Regex nachbearbeiten, um `{{` → `{` zu reduzieren. | +| **Fehlendes MathJax auf der Zielseite** | Gleichungen erscheinen als roher LaTeX‑Code. | `` zu Ihrer HTML‑Vorlage hinzufügen. | +| **Große Dokumente** | Der Speicherverbrauch steigt, weil das gesamte Dokument auf einmal geladen wird. | `LoadOptions.setLoadFormat(LoadFormat.DOCX)` verwenden und in Erwägung ziehen, Seiten stapelweise zu verarbeiten, falls ein `OutOfMemoryError` auftritt. | +| **Lizenz nicht gesetzt** | Sie erhalten eine Warnung und die Ausgabe kann ein Wasserzeichen enthalten. | Die Lizenz früh im `main` laden, wie im Maven‑Tipp oben gezeigt. | + +## Word als Markdown speichern – Vollständiges funktionierendes Beispiel + +Unten finden Sie eine eigenständige Klasse, die Sie in jedes Java‑Projekt kopieren können. Ersetzen Sie einfach `YOUR_DIRECTORY` durch den Pfad zu Ihren Dateien. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Führen Sie das Programm (`java MathToLatexMarkdown`) aus und Sie sehen die Konsolennachricht, die den Erfolg bestätigt. Öffnen Sie `out.md` in einem beliebigen Editor – die Gleichungen sollten saubere LaTeX‑Snippets sein, bereit zum Rendern. + +## Erwarteter Ausgabeschnappschuss + +![Word als Markdown Ausgabe mit LaTeX‑Gleichungen](https://example.com/images/markdown-latex-output.png "Word als Markdown Ausgabe mit LaTeX‑Gleichungen") + +*Das Bild zeigt einen Ausschnitt des erzeugten Markdown, bei dem die Gleichung `\int_{a}^{b} f(x)\,dx` in `$$` eingeschlossen ist.* + +## Fazit + +Wir haben gerade gezeigt, wie man **Word als Markdown speichert**, während jede Office‑Math‑Gleichung als natives LaTeX erhalten bleibt. Der entscheidende Schritt war die Konfiguration von `MarkdownSaveOptions` mit `OfficeMathExportMode.LATEX`, wodurch eine typische Word‑zu‑Markdown‑Pipeline zu einem voll‑mathematik‑fähigen Konvertierungswerkzeug wird. + +Jetzt können Sie: + +1. **Wie man Mathematik exportiert** aus jeder `.docx` ohne Qualitätsverlust. +2. **Word‑Gleichungen nach LaTeX konvertieren** für statische Site‑Generatoren, Dokumentation oder akademische Blogs. +3. Den Ansatz erweitern, um viele Dateien stapelweise zu verarbeiten, in CI‑Pipelines zu integrieren oder sogar einen kleinen Web‑Service zu bauen. + +Wenn Sie neugierig auf die nächste Grenze sind, versuchen Sie, dies mit **docx zu markdown latex** für bildlastige Dokumente zu kombinieren, oder erkunden Sie Asposes `HtmlSaveOptions` für eine web‑fertige HTML‑Version. Die Möglichkeiten sind endlos – experimentieren Sie, brechen Sie Dinge und teilen Sie dann Ihre Erkenntnisse mit der Community. + +Haben Sie Fragen oder eine knifflige Gleichung, die nicht wie erwartet gerendert wurde? Hinterlassen Sie unten einen Kommentar und happy coding! + +## Verwandte Tutorials + +- [Wie man LaTeX aus Word exportiert: DOCX zu Markdown konvertieren & als PDF speichern](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [DOCX zu Markdown konvertieren – Mathematische Gleichungen nach LaTeX exportieren mit Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Wie man Word zu PDF konvertiert mit Aspose.Words für Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/german/java/document-loading-and-saving/_index.md index d97518329e..c3d6d0908b 100644 --- a/words/german/java/document-loading-and-saving/_index.md +++ b/words/german/java/document-loading-and-saving/_index.md @@ -131,10 +131,10 @@ Lernen Sie, wie Sie Dokumente als Textdateien mit Aspose.Words für Java speiche Lernen Sie, wie Sie Dokumentformate in Java mit Aspose.Words erkennen. DOC, DOCX und mehr identifizieren. Dateien effizient organisieren. ### [Beschädigtes docx wiederherstellen – Vollständiger Leitfaden zum Reparieren und Verarbeiten von Dokumenten](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) -Erfahren Sie, wie Sie beschädigte DOCX‑Dateien reparieren und anschließend mit Aspose.Words für Java verarbeiten. ### [Erfassung von Font‑Substitutions‑Warnungen in Java mit Aspose.Words – Vollständiger Leitfaden](./capture-font-substitution-warnings-in-java-with-aspose-words/) -Erfahren Sie, wie Sie Font‑Substitutions‑Warnungen in Java mit Aspose.Words erfassen und verarbeiten – vollständige Anleitung. + +### [Beschädigtes Word‑Dokument öffnen – Wiederherstellungsmodus in Java setzen](./open-corrupted-word-document-set-recovery-mode-in-java/) ## Häufig gestellte Fragen diff --git a/words/german/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/german/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..f916e44800 --- /dev/null +++ b/words/german/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Öffnen Sie ein beschädigtes Word‑Dokument in Java mit Aspose.Words. Erfahren + Sie, wie Sie den Wiederherstellungsmodus aktivieren und beschädigte Word‑Dateien + zuverlässig wiederherstellen. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: de +og_description: Öffnen Sie ein beschädigtes Word‑Dokument in Java mit Aspose.Words. + Dieser Leitfaden zeigt, wie Sie den Wiederherstellungsmodus aktivieren und beschädigte + Word‑Dateien effizient wiederherstellen. +og_title: Beschädigtes Word‑Dokument öffnen – Wiederherstellungsmodus in Java festlegen +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Beschädigtes Word‑Dokument öffnen – Wiederherstellungsmodus in Java festlegen +url: /de/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Beschädigtes Word-Dokument öffnen – Wiederherstellungsmodus festlegen in Java + +Haben Sie schon einmal versucht, ein beschädigtes Word-Dokument zu öffnen und dabei beobachtet, wie das Programm wegen einer Ausnahme abstürzt? Sie sind nicht allein – diese kaputten .docx‑Dateien können ein echtes Ärgernis sein. Die gute Nachricht ist, dass Aspose.Words für Java Ihnen feinkörnige Kontrolle bietet, sodass Sie **open corrupted word document** ohne Absturz der Anwendung öffnen können und sogar entscheiden können, ob Sie Warnungen, stille Wiederherstellung oder eine harte Ablehnung wünschen. + +In diesem Tutorial führen wir Sie durch den gesamten Prozess: vom Erstellen der richtigen `LoadOptions` über die Auswahl des passenden **set recovery mode**‑Werts bis hin zur Bestätigung, dass das Dokument tatsächlich geladen wurde. Am Ende wissen Sie **how to recover corrupted word file** programmgesteuert, ohne manuelles Kopieren‑Einfügen. + +> **Was Sie benötigen** +> * Java 8 oder neuer (die API funktioniert auch mit Java 11) +> * Aspose.Words für Java 23.9 (oder die neueste Version) +> * Eine Beispiel‑.docx‑Datei, die beschädigt ist – benennen Sie einfach eine gültige Datei um, um eine Beschädigung zu simulieren, falls Sie keine zur Hand haben + +Lassen Sie uns eintauchen. + +## Beschädigtes Word-Dokument öffnen – Schritt‑für‑Schritt‑Übersicht + +Im Folgenden finden Sie den High‑Level‑Ablauf, den wir implementieren werden: + +1. **Create `LoadOptions`** – dieses Objekt teilt Aspose.Words mit, wie es sich verhalten soll, wenn es auf Probleme stößt. +2. **Set recovery mode** – wählen Sie `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` oder `REJECT_CORRUPTED`. +3. **Load the document** – laden Sie das Dokument mit den konfigurierten Optionen. +4. **Verify** – prüfen Sie, ob das Laden erfolgreich war (z. B. Seitenzahl ausgeben). + +Jeder Schritt wird im Detail erklärt, mit Code‑Snippets, die Sie direkt in Ihre IDE kopieren‑und‑einfügen können. + +## Wiederherstellungsmodus für verschiedene Szenarien festlegen + +Aspose.Words definiert drei Wiederherstellungsstrategien in `LoadOptions.RecoveryMode`: + +| Modus | Verhalten | Wann zu verwenden | +|------|-----------|-------------------| +| `RECOVER_WITH_WARNINGS` | Versucht, das Dokument zu laden, gibt jedoch alle Probleme als Warnungen in der Konsole aus. | Sie möchten *sehen*, was schiefgelaufen ist, ohne abzubrechen. | +| `RECOVER_WITHOUT_WARNINGS` | Repariert stillschweigend, was möglich ist, und unterdrückt Warnungen. | Produktionsumgebungen, in denen Protokolle sauber bleiben müssen. | +| `REJECT_CORRUPTED` | Wirft sofort eine Ausnahme, sobald eine Beschädigung erkannt wird. | Strenge Validierungspipelines, die sofort fehlschlagen müssen. | + +Die richtige Auswahl des Modus ist das Wesentliche, um **set recovery mode** korrekt zu setzen. In den meisten Debug‑Sitzungen ist `RECOVER_WITH_WARNINGS` der optimale Wert, da er genau anzeigt, welche Teile repariert wurden. + +## Wie man beschädigte Word-Datei mit Aspose.Words wiederherstellt + +Unten finden Sie ein **vollständiges, ausführbares Java‑Programm**, das den gesamten Prozess demonstriert. Sie können es einfach in eine `RecoveryModeDemo.java`‑Datei einfügen, den Pfad anpassen und ausführen. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Warum jede Zeile wichtig ist + +* **`LoadOptions loadOptions = new LoadOptions();`** – ohne dieses Objekt verwendet Aspose.Words die Standard‑Wiederherstellung, die beschädigte Dateien *ablehnt*. Durch das Erstellen erhalten Sie den Hook, um dieses Verhalten zu ändern. +* **`setRecoveryMode(...)`** – dies ist der Aufruf **set recovery mode**, der entscheidet, ob Warnungen angezeigt, verborgen bleiben oder eine Ausnahme ausgelöst wird. +* **`new Document(path, loadOptions);`** – der Konstruktor akzeptiert die gerade konfigurierten `LoadOptions`, sodass die Bibliothek von Anfang an weiß, wie die beschädigte Datei zu behandeln ist. +* **`doc.getPageCount()`** – ein schneller Plausibilitätstest. Wenn das Dokument geladen wird und eine Seitenzahl zurückgibt, haben Sie erfolgreich **how to recover corrupted word file**. +* **`doc.save(...)`** – optional, aber praktisch; Sie können die reparierte Version wieder auf die Festplatte schreiben, um sie später zu verwenden. + +## Umgang mit gängigen Sonderfällen + +### 1. Datei nicht gefunden + +Wenn der Pfad falsch ist, wirft `Document` eine `FileNotFoundException`. Umhüllen Sie das Laden in einen try‑catch‑Block und protokollieren Sie eine freundliche Meldung: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Unwiederherstellbare Beschädigung + +Selbst mit `RECOVER_WITH_WARNINGS` sind einige Strukturen nicht reparierbar. In diesem Fall lädt Aspose.Words, was es kann, aber Sie sehen Warnungen wie „Cannot read paragraph properties“. Achten Sie auf die Konsolenausgabe; diese Warnungen weisen oft auf fehlende Abschnitte hin, die Sie manuell rekonstruieren müssen. + +### 3. Große Dateien und Leistung + +Die Wiederherstellung verursacht einen kleinen Overhead, da die Bibliothek die Datei zweimal parst – einmal, um Probleme zu erkennen, und erneut, um sie wieder aufzubauen. Bei Dokumenten von mehreren Gigabyte sollten Sie das Streaming der Datei in Betracht ziehen oder den JVM‑Heap (`-Xmx2g`) erhöhen, um `OutOfMemoryError` zu vermeiden. + +## Pro‑Tipps – Wiederherstellung robust gestalten + +* **Warnungen in eine Datei protokollieren** – leiten Sie `System.err` zu einem Logger um, sodass Sie eine Prüfspur dessen haben, was repariert wurde. +* **Nach der Wiederherstellung validieren** – führen Sie `doc.updatePageLayout();` aus und prüfen Sie anschließend erneut die Seitenzahl; manchmal ändert sich das Layout nach dem Reparieren defekter Abschnitte. +* **Batch‑Wiederherstellung automatisieren** – verpacken Sie die Demo in eine Schleife, die einen Ordner mit beschädigten Dateien verarbeitet, wobei jedes Mal dieselben `LoadOptions` verwendet werden. + +## Fazit + +Sie wissen jetzt genau **how to recover corrupted word file** mit Aspose.Words für Java. Indem Sie eine `LoadOptions`‑Instanz erstellen, **set recovery mode** auf die passende Strategie einstellen und das Dokument mit diesen Optionen laden, können Sie sicher **open corrupted word document** öffnen, ohne Ihre Anwendung zum Absturz zu bringen. Der obige Beispielcode ist eine vollständige, sofort ausführbare Lösung, die die Seitenzahl ausgibt und sogar eine bereinigte Kopie speichert. + +Was kommt als Nächstes? Versuchen Sie, den Wiederherstellungsmodus zu `RECOVER_WITHOUT_WARNINGS` zu wechseln und vergleichen Sie die Konsolenausgabe, oder experimentieren Sie mit dem Laden verschlüsselter Dokumente (Sie müssen ein Passwort übergeben via + +## Verwandte Tutorials + +- [Aspose.Words Java: Umfassender Leitfaden zur Word-Dokumentverarbeitung](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Wie man Word mit Aspose.Words für Java in PDF konvertiert](/words/english/java/document-converting/using-document-converting/) +- [Wie man zwei Word-Dateien mit Aspose.Words für Java vergleicht](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/german/java/document-styling/_index.md index b31788bb06..cfdc2fc831 100644 --- a/words/german/java/document-styling/_index.md +++ b/words/german/java/document-styling/_index.md @@ -43,6 +43,8 @@ Erfahren Sie, wie Sie Dokumentdesigns mit Aspose.Words für Java anpassen. Diese Erfahren Sie, wie Sie mit Aspose.Words für Java Wasserzeichen anwenden und Seitenkonfigurationen einrichten. Eine umfassende Anleitung mit Quellcode. ### [Stil der Kopf- und Fußzeile des Dokuments](./document-header-footer-styling/) Erfahren Sie in dieser ausführlichen Anleitung, wie Sie Dokumentkopf- und -fußzeilen mit Aspose.Words für Java formatieren. Schritt-für-Schritt-Anleitung und Quellcode inklusive. +### [Standard-Schrifteinstellungen in Aspose.Words für Java festlegen – Komplettanleitung](./set-default-font-settings-in-aspose-words-for-java-complete/) +Erfahren Sie, wie Sie mit Aspose.Words für Java die Standardschriftart und -größe festlegen. Schritt-für-Schritt-Anleitung mit Codebeispielen. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/german/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..00f89e4bf5 --- /dev/null +++ b/words/german/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Legen Sie die Standard‑Schrifteinstellungen in Aspose.Words für Java + fest und erfahren Sie, wie Sie Schrifteinstellungen setzen und fehlende Schriften + mit nur wenigen Codezeilen erkennen können. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: de +og_description: Legen Sie die Standard‑Schrifteinstellungen in Aspose.Words für Java + fest, lernen Sie, Schrifteinstellungen zu setzen und fehlende Schriften schnell + und zuverlässig zu erkennen. +og_title: Standard‑Schrifteinstellungen in Aspose.Words für Java festlegen +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Standard‑Schrifteinstellungen in Aspose.Words für Java festlegen – Vollständige + Anleitung +url: /de/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Standard‑Schrifteinstellungen in Aspose.Words für Java festlegen – Vollständige Anleitung + +Haben Sie sich jemals gefragt, wie man **Standard‑Schrifteinstellungen** beim Laden eines Word‑Dokuments mit Aspose.Words for Java festlegt? Sie sind nicht allein. Fehlende Glyphen können einen gepflegten Bericht in ein wirres Durcheinander verwandeln, und das frühzeitige Erkennen dieser Schriftart‑Ersetzungshinweise spart Stunden an Fehlersuche. + +In diesem Tutorial führen wir Sie durch ein prägnantes, End‑to‑End‑Beispiel, das **Standard‑Schrifteinstellungen festlegt**, Ihnen zeigt, wie man **Schrifteinstellungen** programmgesteuert **setzt**, und eine zuverlässige Methode demonstriert, **fehlende Schriftarten** zu **erkennen**, bevor sie Ihr Layout zerstören. + +--- + +## Was Sie lernen werden + +- Wie man ein `LoadOptions`‑Objekt mit einer neuen `FontSettings`‑Instanz erstellt. +- Wie man einen Warnungs‑Listener anhängt, der **fehlende Schriftarten** beim Laden des Dokuments **erkennt**. +- Wie man eine DOCX‑Datei lädt, während der Listener stillschweigend alle Ersetzungen meldet. +- Tipps zum Anpassen von Ersatzschriftarten und zum Umgang mit Randfällen in der Produktion. + +Keine zusätzlichen Bibliotheken, keine obskuren Konfigurationsdateien – nur reines Java und Aspose.Words. + +--- + +## Voraussetzungen + +Bevor wir beginnen, stellen Sie sicher, dass Sie Folgendes haben: + +1. **Aspose.Words for Java** (Version 23.10 oder neuer) in Ihrem Klassenpfad. +2. Ein Java 17 (oder neuer) Development Kit – jedes moderne JDK funktioniert. +3. Eine DOCX‑Datei, die absichtlich eine Schriftart verwendet, die Sie nicht installiert haben (z. B. *„MissingFont.ttf“*). + +Falls Ihnen das Aspose‑JAR fehlt, holen Sie es aus dem offiziellen Maven‑Repository: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Das war's – für diese Demo müssen keine zusätzlichen Schriftarten installiert werden. + +--- + +## Schritt 1: LoadOptions erstellen und **Standard‑Schrifteinstellungen festlegen** + +Das Erste, was wir benötigen, ist ein sauberes `LoadOptions`‑Objekt, das Aspose mitteilt, wie es sich verhalten soll, wenn es unbekannte Schriftarten trifft. Durch Aufruf von `setFontSettings(new FontSettings())` **setzen wir Standard‑Schrifteinstellungen**, die mit einer leeren Ersatzliste beginnen. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Warum das wichtig ist:** +> Wenn Sie Schriftarten nicht explizit konfigurieren, greift Aspose auf die standardmäßige Sammlung des Systems zurück, wodurch fehlende Schriftartenprobleme verbergen können. Durch den Start mit einer neuen `FontSettings`‑Instanz erhalten Sie die volle Kontrolle darüber, welche Schriftarten als gültig gelten. + +--- + +## Schritt 2: Einen Warnungs‑Listener anhängen, um **fehlende Schriftarten zu erkennen** + +Aspose erzeugt für jede durchgeführte Ersetzung ein `WarningInfo`‑Objekt. Durch das Abhören von `WarningType.FONT_SUBSTITUTION` können wir **fehlende Schriftarten** sofort erkennen, sobald das Dokument geparst wird. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Profi‑Tipp:** Der Listener läuft im selben Thread, der das Dokument lädt, sodass praktisch kein Performance‑Nachteil entsteht. Wenn Sie Warnungen für eine spätere Analyse sammeln müssen, schieben Sie sie in eine `List` statt sie direkt auszugeben. + +--- + +## Schritt 3: Das Dokument mit den konfigurierten Optionen laden + +Jetzt, wo wir **Schrifteinstellungen gesetzt** und einen Listener vorbereitet haben, laden wir einfach die Datei. Jede fehlende Schriftart löst sofort unseren Rückruf aus. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Wenn die Quelldatei eine Schriftart referenziert, die nicht installiert ist, sehen Sie eine Ausgabe ähnlich wie: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Diese Zeile gibt genau an, welche Schriftart fehlte und welche Ersatzschriftart verwendet wurde – perfekt für Protokollierung oder Benutzer‑Feedback. + +--- + +## Schritt 4: Normale Verarbeitung fortsetzen (optional) + +An diesem Punkt ist das Dokument vollständig geladen, und Sie können mit jeder gewünschten Manipulation fortfahren – Bearbeiten, in PDF konvertieren oder Text extrahieren. Der Warnungs‑Listener hat seine Aufgabe bereits erledigt, sodass Sie keine zusätzlichen Prüfungen benötigen. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Was, wenn Sie einen benutzerdefinierten Ersatz wollen?** +> Anstatt die `FontSettings` leer zu lassen, können Sie bestimmte Schriftarten hinzufügen: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Jetzt wird jede fehlende Schriftart durch *Times New Roman* ersetzt – eine zuverlässige Wahl für die meisten westlichen Dokumente. + +--- + +## Visuelle Übersicht + +![Diagramm, das zeigt, wie man Standard‑Schrifteinstellungen in Aspose.Words für Java festlegt](image.png "Diagramm des Ablaufs zum Festlegen von Standard‑Schrifteinstellungen") + +*Alt‑Text: Ablaufdiagramm zum Festlegen von Standard‑Schrifteinstellungen in Aspose.Words für Java.* + +Das Diagramm veranschaulicht den Ablauf von der Initialisierung von `LoadOptions` (wo wir **Standard‑Schrifteinstellungen festlegen**) über das Anhängen des Warnungs‑Listeners (um **fehlende Schriftarten zu erkennen**) bis hin zum Laden des Dokuments. + +--- + +## Häufige Fallstricke & wie man sie vermeidet + +| Fallstrick | Warum es passiert | Lösung | +|------------|-------------------|--------| +| **Vergessen, `setFontSettings` aufzurufen** | Aspose verwendet die System‑Standardwerte, wodurch fehlende Schriftarten verborgen werden. | Erstellen Sie immer eine neue `FontSettings`‑Instanz und weisen Sie sie `LoadOptions` zu. | +| **Listener wird nicht ausgelöst** | Listener wurde nach dem Laden des Dokuments hinzugefügt. | Fügen Sie den Warnungs‑Listener *vor* dem Aufruf von `new Document(...)` hinzu. | +| **Pfad‑Tippfehler führt zu `FileNotFoundException`** | Hartkodierter Pfad stimmt nicht mit der Groß‑/Kleinschreibung des Betriebssystems überein. | Verwenden Sie `Paths.get("...").toAbsolutePath()` oder konfigurieren Sie einen relativen Pfad vom Projekt‑Root. | +| **Mehrere fehlende Schriftarten überfluten das Protokoll** | Große Dokumente können Dutzende von Warnungen erzeugen. | Filtern Sie Duplikate oder aggregieren Sie Meldungen in einem `Set` bevor Sie sie ausgeben. | + +--- + +## Lösung erweitern + +Wenn Sie **Schrifteinstellungen** für eine gesamte Anwendung **setzen** müssen, sollten Sie ein Singleton `FontSettings` erstellen und es über alle `LoadOptions` hinweg wiederverwenden. So behalten Sie eine konsistente Ersatzstrategie bei und vermeiden wiederholte Objekterstellungen. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Jetzt kann jeder Teil Ihres Code‑Bases einfach `FontConfig.getLoadOptions()` aufrufen und sofort von derselben **Standard‑Schrifteinstellungen‑Logik** profitieren. + +--- + +## Fazit + +Wir haben gerade alles behandelt, was Sie benötigen, um **Standard‑Schrifteinstellungen** in Aspose.Words für Java **zu setzen**, **Schrifteinstellungen** programmgesteuert **zu setzen** und **fehlende Schriftarten** zu **erkennen**, bevor sie Ihre Ausgabe beschädigen. Das vollständige, ausführbare Beispiel befindet sich in den obigen Code‑Snippets, und Sie können es direkt in Ihre IDE einfügen, um die Warnungen in Aktion zu sehen. + +Nächste Schritte? Versuchen Sie, die Ersatzschriftart zu wechseln, experimentieren Sie mit verschiedenen Dokumentformaten (DOC, RTF, HTML) oder integrieren Sie den Warnungs‑Collector in ein Monitoring‑Dashboard. Je mehr Sie mit `FontSettings` spielen, desto mehr Vertrauen haben Sie, dass Ihre erzeugten Dokumente exakt wie beabsichtigt aussehen – keine Überraschungen, keine beschädigten Glyphen. + +Haben Sie Fragen oder ein kniffliges Schriftart‑Ersetzungsszenario? Hinterlassen Sie unten einen Kommentar, und happy coding! + +## Verwandte Tutorials + +- [Schrifteinstellungen für Fallback festlegen](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Schrifteinstellungen für Fallback festlegen](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Schrifteinstellungen für Fallback festlegen](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/java/images-shapes/_index.md b/words/german/java/images-shapes/_index.md index ae049eb3fb..3aa523e537 100644 --- a/words/german/java/images-shapes/_index.md +++ b/words/german/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Erfahren Sie, wie Sie mit Aspose.Words für Java hochwertige Miniaturansichten u ### [Word-Dokument in Java erstellen – Rechteckform mit Schatteneffekt hinzufügen](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Ein Codebeispiel, das zeigt, wie man in Aspose.Words für Java ein Rechteck mit Schatten in ein Word-Dokument einfügt. +### [Rechteckform in Java-Word-Dokument erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Ein detailliertes Beispiel, das zeigt, wie man mit Aspose.Words für Java ein Rechteck in ein Word-Dokument einfügt. + ## Weitere Ressourcen - [Aspose.Words für Java-Dokumentation](https://reference.aspose.com/words/java/) diff --git a/words/german/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/german/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..77bc4483b9 --- /dev/null +++ b/words/german/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-05-26 +description: Erstelle ein Rechteck in einem Java‑Word‑Dokument und wende einen Schatteneffekt + an. Lerne, wie man einem Shape einen Schatten hinzufügt, den Schattenabstand einstellt + und die Datei speichert. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: de +og_description: Erstelle ein Rechteck in einem Java‑Word‑Dokument, wende den Schatteneffekt + an, füge dem Shape einen Schatten hinzu und lege den Schattenabstand mit Aspose.Words + fest. +og_title: Rechteckform in Java‑Word‑Dokument erstellen – Komplettanleitung +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Rechteckform in Java‑Word‑Dokument erstellen – Vollständige Schritt‑für‑Schritt‑Anleitung +url: /de/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rechteckige Form in Java Word-Dokument erstellen – Vollständige Schritt‑für‑Schritt-Anleitung + +Haben Sie jemals **create rectangle shape** in einem Java‑Word‑Dokument erstellen müssen, wussten aber nicht, wo Sie anfangen sollen? Sie sind nicht allein – viele Entwickler stoßen auf dieses Problem, wenn sie Berichte oder Rechnungen programmgesteuert erzeugen. In diesem Tutorial zeigen wir Ihnen genau, wie Sie **create rectangle shape** erstellen, einen eleganten Schatten hinzufügen und den Abstand des Schattens feinjustieren, damit das Ergebnis professionell wirkt. + +Wir verwenden Aspose.Words for Java, eine robuste Bibliothek, mit der Sie Word‑Dateien manipulieren können, ohne Microsoft Office installiert zu haben. Am Ende dieses Leitfadens können Sie **create word document java**‑Projekte erstellen, die **add shape shadow**, **apply shadow effect** und **set shadow distance** mit nur wenigen Codezeilen. + +--- + +## Was Sie erstellen werden + +- Eine neue `.docx`‑Datei, die ein cyanblaues Rechteck enthält. +- Einen realistischen Drop‑Shadow, der unscharf, schräg und teilweise transparent ist. +- Vollständige Kontrolle über den Abstand des Schattens zur Form. +- Eine sofort ausführbare Java‑Klasse, die Sie in jedes Maven‑ oder Gradle‑Projekt einbinden können. + +Keine externen Werkzeuge, keine manuellen UI‑Schritte – nur reiner Code. + +## Voraussetzungen + +- Java 8 oder neuer (der Code funktioniert mit Java 11, Java 17 usw.). +- Aspose.Words for Java‑Bibliothek (verfügbar über Maven Central). +- Eine IDE oder einen Texteditor Ihrer Wahl (IntelliJ IDEA, Eclipse, VS Code …). +- Grundlegende Kenntnisse der Java‑Syntax. + +Falls Sie noch nie eine Maven‑Abhängigkeit hinzugefügt haben, hier ein kurzer Ausschnitt: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Jetzt tauchen wir ein. + +## Schritt 1: Rechteckige Form in einem Word‑Dokument erstellen + +Das Erste, was wir benötigen, ist ein leeres Dokument und ein `DocumentBuilder`. Denken Sie an den Builder wie an einen Stift, der in das Dokument schreibt. Sobald wir das haben, können wir **create rectangle shape** mit einem einzigen Methodenaufruf erstellen. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Warum das wichtig ist:** Die Methode `insertShape` erstellt nicht nur die Geometrie, sondern fügt die Form auch zur internen Sammlung des Dokuments hinzu, sodass Sie sofort mit dem Styling beginnen können. + +## Schritt 2: Schatteneffekt auf die Form anwenden + +Jetzt, wo das Rechteck auf der Seite ist, werden wir **apply shadow effect**. Schatten verleihen Tiefe und lassen die Form wirken, als würde sie von der Seite abheben – eine subtile UI‑Verbesserung, die die Lesbarkeit in Berichten steigern kann. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro‑Tipp:** Ein Unschärfe‑Wert von `5.0` wirkt bei den meisten bildschirmbasierten Dokumenten natürlich. Beim Drucken möchten Sie möglicherweise einen etwas niedrigeren Wert wählen, um ein unscharfes Aussehen zu vermeiden. + +## Schritt 3: Schattenabstand festlegen – Feineinstellung der Position + +Schatten drehen sich nicht nur um Unschärfe; sie benötigen auch den richtigen Versatz. Hier kommen wir zu **set shadow distance**. Ein Abstand von `7.0` Punkten erzeugt einen dezenten Versatz, der sichtbar, aber nicht übertrieben ist. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Was, wenn Sie einen größeren Versatz benötigen?** Erhöhen Sie den Wert; verringern Sie ihn für ein kompakteres Aussehen. Denken Sie daran, dass der Abstand zusammen mit dem Winkel wirkt, um den Schatten korrekt zu positionieren. + +## Schritt 4: Dokument speichern – Ihre Arbeit sichern + +Abschließend schreiben wir das Dokument auf die Festplatte. Ändern Sie den Pfad zu dem Ort, an dem die Datei gespeichert werden soll. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Das Ausführen der Klasse erzeugt eine `shadow.docx`‑Datei, die beim Öffnen in Microsoft Word oder LibreOffice ein cyanblaues Rechteck mit einem weichen grauen Schatten zeigt, der um 45° gedreht und um 7 Punkte versetzt ist. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie den vollständigen, zum Kopieren‑und‑Einfügen bereitstehenden Code. Er enthält alle Importe, Kommentare und den abschließenden Aufruf von `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Erwartete Ausgabe:** Öffnen Sie `shadow.docx` → Sie sehen ein cyanblaues Rechteck, das in der Mitte der ersten Seite zentriert ist und einen dezenten grauen Schatten wirft, der leicht nach unten rechts versetzt ist. Die Unschärfe und Transparenz des Schattens lassen ihn wie natürliches Licht wirken. + +## Häufige Fragen & Sonderfälle + +### „Kann ich eine andere Form verwenden?“ + +Absolut. Ersetzen Sie `ShapeType.RECTANGLE` durch `ShapeType.OVAL`, `ShapeType.LINE` oder ein anderes unterstütztes Enum. Der Rest des Schatten‑Codes bleibt unverändert. + +### „Was, wenn ich mehrere Schatten benötige?“ + +Aspose.Words unterstützt nur einen Schatten pro Form. Um mehrere Schatten zu simulieren, duplizieren Sie die Form, versetzen jede Kopie und passen die Transparenz an. + +### „Ist der Schatten in LibreOffice sichtbar?“ + +Ja – Aspose.Words schreibt standardmäßiges OOXML, das LibreOffice korrekt interpretiert. Der Schatten kann aufgrund unterschiedlicher Rendering‑Engines leicht anders aussehen, aber der Effekt bleibt erhalten. + +### „Wie ändere ich die Schattenfarbe, um sie an meine Marke anzupassen?“ + +Tauschen Sie einfach `java.awt.Color.GRAY` gegen jede gewünschte `java.awt.Color` aus, z. B. `new java.awt.Color(0, 120, 215)` für ein Unternehmensblau. + +## Bildillustration + +![Rechteckform in Java Word-Dokument erstellen](https://example.com/images/rectangle-shadow.png) + +*Alt-Text:* **create rectangle shape** Illustration, die ein cyanblaues Rechteck mit einem grauen Drop‑Shadow in einem Word‑Dokument zeigt. + +## Zusammenfassung & nächste Schritte + +Wir haben behandelt, wie man **create rectangle shape**, **apply shadow effect**, **add shape shadow** und **set shadow distance** mit Aspose.Words for Java verwendet. Der Code ist eigenständig, läuft auf jedem modernen JDK und erzeugt eine hochwertige `.docx`‑Datei, die bereit zur Verteilung ist. + +Sie möchten weitergehen? Versuchen Sie: + +- Text innerhalb des Rechtecks hinzufügen mit `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Eine Tabelle von Formen erstellen, um ein Diagramm zu bauen. +- Das Dokument nach PDF exportieren (`doc.save("output.pdf", SaveFormat.PDF);`). + +Jeder dieser Punkte baut auf denselben Grundlagen auf, die wir gerade untersucht haben, sodass Sie sich sicher fühlen, das Beispiel zu erweitern. + +## Abschließende Gedanken + +Das Beherrschen von **create word document java**‑Aufgaben wie Formen und Schattieren verschafft Ihnen einen großen Vorteil bei der Automatisierung von Berichten, Verträgen oder Marketing‑Materialien. Der hier gezeigte Ansatz ist sauber, wartbar und – am wichtigsten – leicht an jede gewünschte visuelle Stilrichtung anpassbar. + +Probieren Sie den Code aus, passen Sie Unschärfe, Winkel und Abstand an und beobachten Sie, wie Ihre Dokumente von schlicht zu professionell werden. Wenn Sie auf ein Problem stoßen, hinterlassen Sie unten einen Kommentar; ich helfe gern. + +Viel Spaß beim Coden! + +## Verwandte Tutorials + +- [Word-Dokument Java erstellen – Rechteckform mit Schatteneffekt hinzufügen](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Formularfelder erstellen und Inhalte mit DocumentBuilder in Aspose.Words for Java hinzufügen](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [PDF aus Word mit Barcode-Generierung erstellen – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/greek/java/document-conversion-and-export/_index.md index 28d81a268a..8325d328f3 100644 --- a/words/greek/java/document-conversion-and-export/_index.md +++ b/words/greek/java/document-conversion-and-export/_index.md @@ -91,8 +91,14 @@ weight: 22 ### [Μετατροπή docx σε markdown – Εξαγωγή μαθηματικών εξισώσεων σε LaTeX με Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Μάθετε πώς να μετατρέψετε αρχεία DOCX σε Markdown και να εξάγετε εξισώσεις Math σε LaTeX χρησιμοποιώντας το Aspose.Words. +### [Αποθήκευση Word ως markdown – Εξαγωγή μαθητικών σε LaTeX με Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Μάθετε πώς να αποθηκεύετε έγγραφα Word σε μορφή markdown και να εξάγετε εξισώσεις Math σε LaTeX χρησιμοποιώντας το Aspose.Words for Java. + ### [Πώς να ενσωματώσετε εικόνες σε Markdown κατά τη μετατροπή DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) -Μάθετε πώς να ενσωματώσετε εικόνες σε αρχεία Markdown όταν μετατρέπετε DOCX με Aspose.Words for Java. +Μάθετε πώς να ενσωματώνετε εικόνες σε αρχεία Markdown όταν μετατρέπετε DOCX με Aspose.Words for Java. + +### [Ενσωμάτωση Εικόνων ως Base64 Κατά τη Μετατροπή DOCX σε Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Μάθετε πώς να ενσωματώνετε εικόνες σε μορφή Base64 κατά τη μετατροπή αρχείων DOCX σε Markdown με το Aspose.Words for Java. ### [Αποθήκευση Εγγράφου ως TXT – Σύντομος Οδηγός για Εξαγωγή Μαθηματικών Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Μάθετε πώς να αποθηκεύετε έγγραφα Word ως αρχείο κειμένου TXT, διατηρώντας εξαγόμενα μαθηματικά στοιχεία. @@ -103,6 +109,15 @@ weight: 22 ### [Δημιουργία Προσβάσιμου PDF από DOCX – Πλήρης Οδηγός](./create-accessible-pdf-from-docx-complete-guide/) Δημιουργήστε PDF προσβάσιμο από DOCX με πλήρη οδηγίες, εξασφαλίζοντας συμβατότητα με πρότυπα προσβασιμότητας. +### [Δημιουργία Προσβάσιμου PDF σε Java – Πλήρης Οδηγός Ετικετοποίησης](./create-accessible-pdf-in-java-full-tagging-guide/) +Μάθετε πώς να δημιουργήσετε PDF προσβάσιμα με πλήρη σήμανση χρησιμοποιώντας Aspose.Words for Java. + +### [Αποθήκευση Εγγράφου ως PDF με Aspose.Words Java – Πλήρης Οδηγός Προσβασιμότητας](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Μάθετε πώς να δημιουργείτε PDF προσβάσιμα από έγγραφα Word χρησιμοποιώντας το Aspose.Words for Java, με οδηγίες βήμα‑βήμα. + +### [Εξαγωγή docx σε txt με Java – Πλήρης Οδηγός Προγραμματισμού](./export-docx-to-txt-with-java-complete-programming-guide/) +Μάθετε πώς να μετατρέψετε αρχεία DOCX σε απλό κείμενο TXT χρησιμοποιώντας το Aspose.Words for Java, βήμα‑βήμα με κώδικα. + ## Συχνές Ερωτήσεις **Π: Πώς προσθέτω υδατογράφημα σε υπάρχον PDF χρησιμοποιώντας το Aspose.Words;** diff --git a/words/greek/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/greek/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..8332baf1d9 --- /dev/null +++ b/words/greek/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-26 +description: Δημιουργήστε προσβάσιμο PDF σε Java με βήμα‑βήμα κώδικα. Μάθετε πώς να + ετικετοποιήσετε το PDF για προσβασιμότητα και να ενεργοποιήσετε την ετικετοποίηση + PDF χρησιμοποιώντας το PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: el +og_description: Δημιουργήστε προσβάσιμο PDF σε Java με βήμα‑βήμα κώδικα. Μάθετε πώς + να ετικετοποιείτε το PDF για προσβασιμότητα και να ενεργοποιήσετε την ετικετοποίηση + PDF χρησιμοποιώντας το PdfSaveOptions. +og_title: Δημιουργία Προσβάσιμου PDF σε Java – Πλήρης Οδηγός Επισήμανσης +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Δημιουργία Προσβάσιμου PDF σε Java – Πλήρης Οδηγός Επισήμανσης +url: /el/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Προσβάσιμου PDF σε Java – Οδηγός Πλήρους Επισήμανσης + +Έχετε αναρωτηθεί ποτέ πώς να **δημιουργήσετε προσβάσιμο PDF** απευθείας από κώδικα Java; Δεν είστε μόνοι. Πολλοί προγραμματιστές πρέπει να εξυπηρετούν χρήστες που βασίζονται σε προγράμματα ανάγνωσης οθόνης, και η διαφορά μεταξύ ενός απλού PDF και ενός προσβάσιμου μπορεί να είναι τεράστια. Σε αυτό το tutorial θα σας καθοδηγήσουμε βήμα‑βήμα **πώς να επισημάνετε PDF για προσβασιμότητα**, θα σας δείξουμε **πώς να δημιουργήσετε επισημασμένο PDF** με το Aspose PDF for Java, και θα αποκαλύψουμε τα ακριβή βήματα για **προσθήκη ετικετών προσβασιμότητας σε PDF** ώστε κάθε αναγνώστης να λαμβάνει τις ίδιες πληροφορίες. + +Θα καλύψουμε επίσης τις βέλτιστες πρακτικές για **enable PDF tagging**, τις κοινές παγίδες, και ένα πλήρες, εκτελέσιμο παράδειγμα που μπορείτε να ενσωματώσετε στο πρόγραμμά σας σήμερα. Χωρίς ασαφείς αναφορές—μόνο συγκεκριμένο κώδικα, εξηγήσεις και ένα τελικό αρχείο που μπορείτε να ανοίξετε στο Adobe Acrobat για να επαληθεύσετε τις ετικέτες. + +## Τι Θα Μάθετε + +- Το «γιατί» πίσω από την επισήμανση PDF και τη συμμόρφωση με την προσβασιμότητα. +- Προαπαιτούμενα και ρύθμιση βιβλιοθήκης (Aspose PDF for Java 23.10 ή νεότερη). +- Πώς να **δημιουργήσετε προσβάσιμο PDF** από το μηδέν, βήμα‑βήμα. +- Τρόποι για **προσθήκη ετικετών προσβασιμότητας σε PDF** πέρα από την βασική κλήση `setTagDocumentStructure`. +- Συμβουλές για δοκιμή του αποτελέσματος και αντιμετώπιση κοινών προβλημάτων. + +Στο τέλος αυτού του οδηγού θα μπορείτε να δημιουργήσετε PDFs που περνούν τους ελέγχους WCAG 2.1 AA και ταυτόχρονα φαίνονται επαγγελματικά. + +--- + +## Προαπαιτούμενα + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +| Απαίτηση | Αιτία | +|----------|-------| +| **Java 8+** | Σύγχρονα χαρακτηριστικά γλώσσας και καλύτερη διαχείριση Unicode. | +| **Aspose PDF for Java** (v23.10 ή νεότερο) | Παρέχει την κλάση `PdfSaveOptions` και υποστήριξη επισήμανσης. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, κ.λπ.) | Για εύκολη μεταγλώττιση και αποσφαλμάτωση. | +| **Δικαίωμα εγγραφής** σε φάκελο όπου θα αποθηκευτεί το PDF | Η κλήση `doc.save` απαιτεί διαδρομή με δυνατότητα εγγραφής. | + +Αν δεν έχετε προσθέσει ακόμη το Aspose PDF στο έργο σας, προσθέστε την ακόλουθη εξάρτηση Maven στο `pom.xml` σας: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** Χρησιμοποιήστε την πιο πρόσφατη έκδοση· οι νεότερες εκδόσεις βελτιώνουν την ακρίβεια της επισήμανσης και προσθέτουν λειτουργίες προσβασιμότητας ειδικές για γλώσσες. + +--- + +## Βήμα 1: Ρύθμιση του Σκελετού του Εγγράφου + +Πρώτα, δημιουργούμε ένα νέο αντικείμενο `Document`. Σκεφτείτε το ως έναν κενό καμβά που αργότερα θα περιέχει τις ετικέτες που χρειαζόμαστε για την προσβασιμότητα. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Γιατί είναι σημαντικό:** Χωρίς περιεχόμενο, δεν υπάρχει τίποτα για επισήμανση. Η προσθήκη ακόμη και ενός απλού `TextFragment` δίνει στη μηχανή επισήμανσης κάτι για να δουλέψει, και δημιουργεί αυτόματα μια ετικέτα `

` (παράγραφος) όταν ενεργοποιήσουμε αργότερα την επισήμανση δομής. + +## Βήμα 2: Δημιουργία Επιλογών Αποθήκευσης PDF (ο Πυρήνας της Επισήμανσης) + +Τώρα προετοιμάζουμε τις επιλογές που λένε στο Aspose PDF να ενσωματώσει ένα λογικό δέντρο δομής μέσα στο αρχείο. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Η κλήση `setTagDocumentStructure(true)` είναι ο διακόπτης **enable PDF tagging**. Όταν είναι true, η βιβλιοθήκη δημιουργεί ένα δέντρο ετικετών που αντικατοπτρίζει τη οπτική διάταξη, καθιστώντας το PDF αναγνώσιμο από βοηθητικές τεχνολογίες. + +> **Σημείωση:** Αυτή είναι ο πιο απλός τρόπος για **how to create tagged pdf**. Για πιο λεπτομερή έλεγχο (π.χ., ορισμός γλώσσας ή προσαρμοσμένων ετικετών), μπορείτε να εξερευνήσετε `pdfOptions.setTagLanguage("en-US")` και `pdfOptions.setTagStructureTreeRoot(...)`. + +## Βήμα 3: Αποθήκευση του Προσβάσιμου PDF + +Τέλος, γράφουμε το έγγραφο στο δίσκο χρησιμοποιώντας τις επιλογές που μόλις διαμορφώσαμε. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Όταν ολοκληρωθεί το `doc.save`, θα βρείτε το `accessible.pdf` στο φάκελο `output`. Ανοίξτε το στο Adobe Acrobat και δείτε **File → Properties → Description → Tags** – θα πρέπει να δείτε ένα γεμάτο δέντρο ετικετών. + +## Πώς να Επισήμανση PDF για Προσβασιμότητα – Πέρα από τα Βασικά + +Το τριβήμα απόσπασμα παραπάνω ήδη **προσθέτει ετικέτες προσβασιμότητας σε PDF**, αλλά τα έγγραφα του πραγματικού κόσμου συχνά χρειάζονται λίγη περισσότερη επεξεργασία. Εδώ είναι μερικές βελτιώσεις που μπορείτε να προσθέσετε: + +### 1. Ορισμός Γλώσσας Εγγράφου + +Οι αναγνώστες οθόνης χρησιμοποιούν το χαρακτηριστικό γλώσσας για να προφέρουν το κείμενο σωστά. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Παροχή Τίτλου και Θέματος + +Τα μεταδεδομένα βοηθούν τα βοηθητικά εργαλεία να παρέχουν πλαίσιο πριν ακόμη ο χρήστης ανοίξει το αρχείο. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Επισήμανση Εικόνων με Εναλλακτικό Κείμενο + +Εάν ενσωματώνετε εικόνες, χρειάζονται περιγραφές `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Σήμανση Επικεφαλίδων Πίνακα + +Οι πίνακες είναι γνωστοί για τη σύγχυση που προκαλούν στους αναγνώστες εκτός αν επισημάνετε τις γραμμές επικεφαλίδας. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Αυτά τα επιπλέον βήματα κάνουν το PDF σας όχι μόνο *τεχνικά* επισημασμένο, αλλά πραγματικά **προσβάσιμο** για ένα ποικίλο κοινό. + +## Συνηθισμένες Παγίδες Όταν Ενεργοποιείτε την Επισήμανση PDF + +| Σύμπτωμα | Πιθανή Αιτία | Διόρθωση | +|----------|--------------|----------| +| Ετικέτες λείπουν στο Acrobat | `setTagDocumentStructure` παραμένει `false` | Βεβαιωθείτε ότι καλείτε `pdfOptions.setTagDocumentStructure(true)`. | +| Λάθος σειρά ανάγνωσης | Πολύπλοκη διάταξη χωρίς ρητές ετικέτες | Χρησιμοποιήστε `pdfOptions.setTagStructureTreeRoot(...)` για να ορίσετε προσαρμοσμένη σειρά. | +| Οι εικόνες διαβάζονται ως «image» χωρίς περιγραφή | Δεν έχει οριστεί εναλλακτικό κείμενο | Κλήση `image.getAlternativeText().setValue("...")`. | +| Η γλώσσα δεν αναγνωρίζεται | `setTagLanguage` παραλείπεται ή λανθασμένο locale | Παρέχετε κωδικό γλώσσας BCP‑47 (`en-US`, `fr-FR`). | + +Η γνώση αυτών των προβλημάτων σας εξοικονομεί ώρες εντοπισμού σφαλμάτων αργότερα. + +## Επαλήθευση του Αποτελέσματος – Τι να Περιμένετε + +Μετά την εκτέλεση του προγράμματος, ανοίξτε το `output/accessible.pdf` στο Adobe Acrobat Reader: + +1. Το πάνελ ετικετών (`View → Show/Hide → Navigation Panes → Tags`) πρέπει να εμφανίζει μια ιεραρχία όπως `/Document → /Part → /Sect → /Para`. +2. Η σειρά ανάγνωσης πρέπει να ακολουθεί τη οπτική ροή (κείμενο πρώτα, έπειτα εικόνες). +3. Ο αναγνώστης οθόνης (NVDA, VoiceOver) θα διαβάσει «Hello, accessible PDF!» αντί για απλώς «Page 1». + +Αν κάποιο από αυτά τα στοιχεία λείπει, ελέγξτε ξανά τα παραπάνω βήματα—ιδιαίτερα την κλήση `setTagDocumentStructure`. + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + + + +## Σχετικά Μαθήματα + +- [Δημιουργία Προσβάσιμου PDF από Word – Μετατροπή σε PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Δημιουργία Προσβάσιμου PDF από DOCX – Πλήρης Οδηγός](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Πώς να αποθηκεύσετε έγγραφο ως pdf με Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/greek/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..fdeac82004 --- /dev/null +++ b/words/greek/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Ενσωματώστε εικόνες ως base64 ενώ μετατρέπετε docx σε markdown με το + Aspose.Words for Java. Μάθετε πώς να μετατρέπετε το Word σε markdown, να αποθηκεύετε + το Word ως markdown και να διαχειρίζεστε εικόνες. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: el +og_description: Ενσωματώστε εικόνες σε μορφή base64 κατά τη μετατροπή του docx σε + markdown με το Aspose.Words for Java. Πλήρης οδηγός για τη μετατροπή του Word σε + markdown και την αποθήκευση του Word ως markdown. +og_title: Ενσωμάτωση εικόνων ως Base64 κατά τη μετατροπή DOCX σε Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Ενσωμάτωση εικόνων ως Base64 κατά τη μετατροπή DOCX σε Markdown +url: /el/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ενσωμάτωση Εικόνων ως Base64 Κατά τη Μετατροπή DOCX σε Markdown + +Έχετε αναρωτηθεί ποτέ πώς να **ενσωματώσετε εικόνες ως base64** ενώ **μετατρέπετε docx σε markdown**; Δεν είστε ο μόνος—οι προγραμματιστές ρωτούν συνεχώς πώς να διατηρούν τις εικόνες ενσωματωμένες χωρίς να διαχειρίζονται ξεχωριστά αρχεία. Τα καλά νέα είναι ότι το Aspose.Words for Java το κάνει εύκολο: μπορείτε να μετατρέψετε ένα έγγραφο Word σε Markdown και να ενσωματώσετε αυτόματα κάθε εικόνα ως συμβολοσειρά Base64. + +Σε αυτό το tutorial θα περάσουμε από όλη τη διαδικασία—από τη φόρτωση ενός `.docx` που περιέχει εικόνες, στη ρύθμιση ενός callback `MarkdownSaveOptions` που κάνει τη βαριά δουλειά, και τέλος την αποθήκευση του αποτελέσματος ως καθαρό αρχείο `.md`. Στο τέλος θα ξέρετε ακριβώς πώς να **convert word to markdown**, **convert images to base64**, και **save word as markdown** χωρίς να αφήνετε ανεπιθύμητους φακέλους εικόνων. Χωρίς εξωτερικά εργαλεία, χωρίς χειροκίνητη επεξεργασία—απλός κώδικας Java που μπορείτε να ενσωματώσετε σε οποιοδήποτε project. + +## Τι Θα Χρειαστείτε + +- **Java 17** (ή οποιοδήποτε πρόσφατο JDK) – ο κώδικας χρησιμοποιεί σύνταξη lambda, αλλά μπορείτε να τον προσαρμόσετε σε παλαιότερες εκδόσεις. +- **Aspose.Words for Java** βιβλιοθήκη (τελευταία έκδοση του 2026). Προσθέστε την εξάρτηση Maven ή το JAR στο classpath σας. +- Ένα δείγμα **DOCX** αρχείου που περιέχει τουλάχιστον μία εικόνα. +- Ένα IDE ή έναν απλό επεξεργαστή κειμένου—Visual Studio Code, IntelliJ IDEA, ή ακόμη και `vim` αρκούν. + +Αν έχετε ήδη όλα αυτά, υπέροχα—ας ξεκινήσουμε αμέσως. + +## Βήμα 1: Φόρτωση του Εγγράφου Word + +Πρώτα δημιουργούμε μια παρουσία `Document` που δείχνει στο αρχείο προέλευσης. Αυτό είναι το ίδιο βήμα είτε **convert docx to markdown** είτε απλώς διαβάζετε το αρχείο για άλλους σκοπούς. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Why this matters:** Το αντικείμενο `Document` είναι το σημείο εισόδου για κάθε λειτουργία του Aspose. Κρατά όλη τη δομή του Word—συμπεριλαμβανομένων εικόνων, πινάκων και στυλ—ώστε το callback που θα ακολουθήσει να μπορεί να εξετάσει κάθε πόρο. + +## Βήμα 2: Δημιουργία MarkdownSaveOptions και Καταχώρηση Callback Αποθήκευσης Πόρων + +Η μαγεία βρίσκεται στο `MarkdownSaveOptions`. Συνδέοντας ένα `IResourceSavingCallback` αποκτούμε έλεγχο πάνω στο πώς γράφεται κάθε εξωτερικός πόρος (όπως μια εικόνα). + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Γιατί να Χρησιμοποιήσετε `setSaveToMemory(true)`; + +Όταν το `saveToMemory` είναι true, το Aspose γράφει τα bytes της εικόνας σε ροή μνήμης αντί για αρχείο. Ο εξαγωγέας Markdown στη συνέχεια μετατρέπει αυτή τη ροή σε συμβολοσειρά Base64 και την ενσωματώνει απευθείας στην ετικέτα εικόνας του Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Αυτό είναι το βασικό στοιχείο του **embed images as base64**. + +## Βήμα 3: Αποθήκευση του Εγγράφου ως Markdown + +Τώρα που το callback είναι σε θέση, το τελικό βήμα είναι απλώς η κλήση του `save`. Εδώ πραγματικά **convert word to markdown** και, λόγω του callback, επίσης **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Result:** Το `out.md` περιέχει κείμενο Markdown με κάθε εικόνα να αντιπροσωπεύεται ως `data:` URI. Δεν δημιουργούνται επιπλέον αρχεία εικόνας στο δίσκο, οπότε ο φάκελος παραμένει τακτοποιημένος. + +## Βήμα 4: Επαλήθευση του Αποτελέσματος και Συνηθισμένα Προβλήματα + +Ανοίξτε το παραγόμενο `out.md` σε οποιονδήποτε προβολέα Markdown (VS Code, GitHub, ή στατικό γεννήτρια ιστοτόπων). Θα πρέπει να δείτε κάτι σαν: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Λίστα Ελέγχου Επίλυσης Προβλημάτων + +| Πρόβλημα | Πιθανή Αιτία | Διόρθωση | +|----------|--------------|----------| +| Η εικόνα εμφανίζεται ως σπασμένος σύνδεσμος | `setSaveToMemory` παραλείφθηκε | Βεβαιωθείτε ότι το `args.setSaveToMemory(true);` βρίσκεται μέσα στο callback | +| Η συμβολοσειρά Base64 είναι κομμένη | Ασυμφωνία κωδικοποίησης αρχείου εξόδου | Αποθηκεύστε το Markdown χρησιμοποιώντας UTF‑8 (προεπιλογή για το Aspose) | +| Απρόσμενα ονόματα αρχείων | `setKeepResourceOriginalName(true)` | Θέστε το σε `false` για να επιβάλετε την προσαρμοσμένη λογική ονοματοδοσίας | + +## Βήμα 5: Προχωρημένες Παραλλαγές (Προαιρετικό) + +### Μετατροπή Μόνο Επιλεγμένων Εικόνων + +Αν θέλετε να ενσωματώσετε μόνο ορισμένες εικόνες (π.χ. εκείνες μεγαλύτερες από 100 KB), προσθέστε έναν έλεγχο μεγέθους: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Χρήση Διαφορετικής Μορφής Εικόνας + +Το `ResourceSavingArgs` σας δίνει τα ακατέργαστα bytes, ώστε να μπορείτε να ξανακωδικοποιήσετε JPEG ως PNG πριν την ενσωμάτωση—χρήσιμο όταν ο καταναλωτής Markdown προτιμά PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Αυτές οι προσαρμογές δείχνουν πόσο ευέλικτη είναι η προσέγγιση **embed images as base64** όταν **convert docx to markdown**. + +## Συμπέρασμα + +Μόλις μάθατε πώς να **ενσωματώσετε εικόνες ως base64** ενώ **μετατρέπετε docx σε markdown** χρησιμοποιώντας το Aspose.Words for Java. Συνδέοντας ένα απλό `IResourceSavingCallback`, η βιβλιοθήκη κάνει όλη τη βαριά δουλειά: **convert word to markdown**, **convert images to base64**, και τέλος **save word as markdown** με μία μόνο κλήση `save`. + +Νιώστε ελεύθεροι να πειραματιστείτε—δοκιμάστε διαφορετικούς κανόνες φιλτραρίσματος εικόνων, μεταβείτε σε έξοδο HTML, ή συνδέστε αυτό το βήμα με μια στατική γεννήτρια ιστοτόπων. Το ίδιο μοτίβο λειτουργεί και για άλλες μορφές (HTML, EPUB), ώστε να μπορείτε να επαναχρησιμοποιήσετε το callback όπου χρειάζεστε ενσωματωμένους πόρους. + +**Επόμενα βήματα:** +- Εξερευνήστε το `HtmlSaveOptions` για HTML με εικόνες Base64. +- Συνδυάστε το με μια CI pipeline για αυτοματοποίηση δημιουργίας τεκμηρίωσης. +- Εμβαθύνετε στο `DocumentVisitor` του Aspose αν χρειάζεστε ακόμη πιο λεπτομερή έλεγχο της διαδικασίας μετατροπής. + +Καλή προγραμματιστική δουλειά και απολαύστε τα καθαρά, αυτόνομα αρχεία Markdown σας! + +## Σχετικά Μαθήματα + +- [Πώς να Ενσωματώσετε Εικόνες σε Markdown Κατά τη Μετατροπή DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Μετατροπή docx σε markdown – Εξαγωγή Μαθηματικών Εξισώσεων σε LaTeX με Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Αποθήκευση Εικόνων από Word – Οδηγός Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/greek/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..4e3ce0081e --- /dev/null +++ b/words/greek/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-26 +description: Εξαγωγή docx σε txt χρησιμοποιώντας Java και Aspose.Words. Μάθετε πώς + να μετατρέπετε docx σε κείμενο, να διατηρείτε το Unicode και να εξάγετε το Word + ως txt σε λίγα βήματα. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: el +og_description: Εξαγωγή docx σε txt σε Java. Αυτό το σεμινάριο δείχνει πώς να μετατρέψετε + το docx σε κείμενο, να διατηρήσετε το απλό κείμενο Unicode και να εξάγετε το Word + ως txt αποδοτικά. +og_title: Εξαγωγή docx σε txt με Java – Πλήρης Οδηγός +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Εξαγωγή docx σε txt με Java – Πλήρης Οδηγός Προγραμματισμού +url: /el/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή docx σε txt με Java – Πλήρης Οδηγός Προγραμματισμού + +Έχετε ποτέ χρειαστεί να **εξάγετε docx σε txt** αλλά ανησυχείτε για την απώλεια ειδικών χαρακτήρων; Δεν είστε μόνοι. Όταν μετατρέπετε έγγραφα Word σε αρχεία plain‑text, τα σύμβολα Unicode, οι πίνακες και ακόμη και η απλή μορφοποίηση μπορούν να εξαφανιστούν σαν μαγεία. + +Σε αυτόν τον οδηγό θα περάσουμε βήμα‑βήμα μια αξιόπιστη μέθοδο για **εξαγωγή docx σε txt** χρησιμοποιώντας το Aspose.Words for Java, διατηρώντας κάθε χαρακτήρα Unicode και κρατώντας τις διατάξεις των πινάκων αναγνώσιμες. Στο τέλος θα γνωρίζετε επίσης πώς να **μετατρέψετε docx σε κείμενο**, **μετατρέψετε word σε κείμενο**, και ακόμη **εξάγετε word ως txt** χωρίς προβλήματα. + +## Τι Καλύπτει Αυτός ο Οδηγός + +* Ρύθμιση του Aspose.Words σε ένα έργο Java +* Φόρτωση αρχείου DOCX και προετοιμασία του για έξοδο plain‑text +* Διαμόρφωση υποστήριξης **plain text unicode** μέσω του `TxtSaveOptions` +* Προαιρετικές τεχνικές για να διατηρηθούν οι πίνακες ευανάγνωστοι στο παραγόμενο αρχείο `.txt` +* Αποθήκευση του αρχείου και επαλήθευση του αποτελέσματος + +Χωρίς εξωτερικά σκριπτάκια, χωρίς μυστηριώδη εργαλεία γραμμής εντολών—μόνο καθαρός κώδικας Java που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο Maven ή Gradle. + +> **Γιατί να νοιάζεστε;** Τα αρχεία plain‑text είναι ελαφριά, φιλικά στο version‑control και ιδανικά για ευρετηρίαση ή επεξεργασία σε downstream pipelines. Αν έχετε προσπαθήσει ποτέ να `cat` ένα αρχείο Word και έχετε λάβει ακατανόητο κείμενο, αυτός ο οδηγός λύνει το πρόβλημα. + +## Export docx to txt – Επισκόπηση + +Πριν βουτήξουμε στον κώδικα, ας ξεκαθαρίσουμε την ορολογία. **Εξαγωγή docx σε txt** σημαίνει τη λήψη ενός πακέτου Microsoft Word `.docx` και την εγγραφή του κειμενικού του περιεχομένου σε ένα απλό αρχείο `.txt`. Σε αντίθεση με μια μετατροπή PDF, η εξαγωγή κειμένου αφαιρεί το στυλ αλλά μπορεί να διατηρήσει αλλαγές γραμμής, δείκτες παραγράφων και—αν το ρυθμίσετε σωστά—χαρακτήρες Unicode όπως emojis, τονισμένα γράμματα ή ασιατικά σενάρια. + +Το Aspose.Words το κάνει αυτό αβίαστο επειδή αφαιρεί την πολυπλοκότητα του φορμάτ Word και προσφέρει μια κλάση `TxtSaveOptions` όπου μπορείτε να καθορίσετε την κωδικοποίηση, τη διαχείριση πινάκων και άλλα. + +### Προαπαιτούμενα + +* Java 11 ή νεότερη (το API λειτουργεί με Java 8+, αλλά θα υποθέσουμε ένα πρόσφατο JDK) +* Aspose.Words for Java JAR (διαθέσιμο από το Maven Central) +* Ένα δείγμα αρχείου `unicode.docx` που περιέχει διάφορους χαρακτήρες Unicode—π.χ. “こんにちは”, “😊”, και έναν απλό πίνακα + +Αν τα έχετε αυτά, ας ξεκινήσουμε. + +## Βήμα 1: Φόρτωση του Αρχείου DOCX (Μετατροπή docx σε κείμενο) + +Το πρώτο πράγμα που πρέπει να κάνετε είναι να διαβάσετε το πηγαίο έγγραφο στη μνήμη. Εδώ ξεκινά επίσημα η διαδικασία **μετατροπής docx σε κείμενο**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Γιατί είναι σημαντικό:* `Document` είναι η αναπαράσταση του Aspose.Words για ένα αρχείο Word. Φορτώνοντάς το, αποκτάτε πρόσβαση σε όλες τις παραγράφους, τους πίνακες και ακόμη και στα κρυφά στοιχεία. Αν το αρχείο δεν βρεθεί, το Aspose ρίχνει ένα σαφές `FileNotFoundException`, ώστε να ξέρετε αμέσως τι πήγε στραβά. + +## Βήμα 2: Διαμόρφωση TxtSaveOptions για Unicode (Plain text unicode) + +Τα αρχεία plain‑text είναι απλώς ροές byte, επομένως πρέπει να πείτε στη Java ποιο σύνολο χαρακτήρων να χρησιμοποιήσει. Το UTF‑8 είναι το de‑facto πρότυπο για **plain text unicode** επειδή μπορεί να κωδικοποιήσει κάθε κωδικό σημείο Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Συμβουλή:** Αν παραλείψετε την κλήση `setEncoding`, το Aspose χρησιμοποιεί το προεπιλεγμένο charset της πλατφόρμας, το οποίο σε πολλά Windows μηχανήματα είναι Windows‑1252. Αυτή η προεπιλογή θα αφαιρέσει σιωπηλά χαρακτήρες όπως “ß” ή “—”. + +## Βήμα 3: Διατήρηση Διάταξης Πίνακα (Προαιρετικό, αλλά χρήσιμο για αναγνωσιμότητα) + +Όταν **εξάγετε word ως txt**, οι πίνακες συνήθως ισοπεδώνουν σε μια μόνο γραμμή κειμένου, κάνοντάς τους μη αναγνώσιμους. Το Aspose.Words προσφέρει μια απλή σημαία για να διατηρήσετε τη οπτική δομή. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Πότε να το χρησιμοποιήσετε:* Αν το πηγαίο DOCX περιέχει τιμολόγια, προγράμματα ή οποιαδήποτε δεδομένα σε μορφή πλέγματος, η ενεργοποίηση του `PreserveTableLayout` θα εισάγει tabs και αλλαγές γραμμής ώστε το παραγόμενο αρχείο να μοιάζει ακόμη με πίνακα. Αν δεν το χρειάζεστε, μπορείτε να παραλείψετε τη γραμμή και να έχετε πιο συμπαγές αποτέλεσμα. + +## Βήμα 4: Αποθήκευση του Εγγράφου ως Plain‑Text (Export word as txt) + +Η εκτέλεση του προγράμματος παράγει το `plain.txt` στον ίδιο φάκελο. Ανοίξτε το με οποιονδήποτε επεξεργαστή κειμένου (Notepad++, VS Code, ακόμη και `cat` σε τερματικό) και θα δείτε: + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Running the program produces `plain.txt` in the same folder. Open it with any text editor (Notepad++, VS Code, even `cat` in a terminal) and you’ll see: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Παρατηρήστε πώς η ιαπωνική χαιρετισμός και το χαμόγελο επιβίωσαν, και ο πίνακας διατήρησε τις στήλες του χάρη στο `PreserveTableLayout`. Αυτή είναι η ουσία μιας καθαρής **εξαγωγής docx σε txt**. + +## Βήμα 5: Επαλήθευση του Αποτελέσματος (Έλεγχος λογικής μετατροπής word σε κείμενο) + +Ένας γρήγορος έλεγχος λογικής αποτρέπει σιωπηλή απώλεια δεδομένων. Εδώ είναι μερικοί τρόποι για να επιβεβαιώσετε ότι πραγματικά **μετατρέπετε word σε κείμενο** σωστά: + +1. **Σύγκριση checksum** – υπολογίστε ένα SHA‑256 hash του αρχείου `.txt` πριν και μετά από μια μετατροπή γύρω (txt → docx → txt) για να εξασφαλίσετε σταθερότητα. +2. **Αναζήτηση για δείκτες Unicode** – χρησιμοποιήστε `grep` ή τη λειτουργία find‑in‑file του IDE για να εντοπίσετε χαρακτήρες όπως “😊”. +3. **Άνοιγμα σε πολλαπλούς επεξεργαστές** – κάποιες παλιές εκδόσεις του Windows Notepad εξακολουθούν να ερμηνεύουν λανθασμένα UTF‑8 χωρίς BOM· το άνοιγμα του αρχείου στο VS Code επιβεβαιώνει τη σωστή κωδικοποίηση. + +Αν κάποιος από αυτούς τους ελέγχους αποτύχει, ελέγξτε ξανά ότι υπάρχει η εντολή `saveOptions.setEncoding(StandardCharsets.UTF_8)` και ότι το πηγαίο DOCX περιέχει πραγματικά κείμενο Unicode. + +## Συνηθισμένα Πιθανά Προβλήματα & Πώς να τα Αποφύγετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Λείπουν χαρακτήρες** | Το προεπιλεγμένο charset του συστήματος (π.χ. Windows‑1252) αφαιρεί μη‑ASCII σύμβολα. | Ορίστε ρητά UTF‑8 μέσω του `saveOptions.setEncoding`. | +| **Οι πίνακες γίνονται μια γραμμή** | Το `PreserveTableLayout` παραμένει στο προεπιλεγμένο `false`. | Καλέστε `saveOptions.setPreserveTableLayout(true)`. | +| **Αρχείο δεν βρέθηκε** | Λάθος διαδρομή ή έλλειψη δικαιωμάτων ανάγνωσης. | Χρησιμοποιήστε απόλυτες διαδρομές ή `Paths.get(...)` με κατάλληλη διαχείριση εξαιρέσεων. | +| **Μείωση απόδοσης σε μεγάλα έγγραφα** | Φόρτωση ολόκληρου του εγγράφου στη μνήμη. | Διαβάστε το έγγραφο σε τμήματα χρησιμοποιώντας `DocumentBuilder` αν χρειάζεστε μόνο συγκεκριμένα τμήματα. | + +## Bonus: Εξαγωγή Πολλαπλών Αρχείων DOCX σε Μαζική Επεξεργασία + +Αν χρειάζεστε να **μετατρέψετε docx σε κείμενο** για ολόκληρο φάκελο, τυλίξτε τη λογική σε έναν βρόχο: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Αυτό το απόσπασμα **εξάγει docx σε txt** για κάθε αρχείο στον κατάλογο, εξοικονομώντας σας ώρες χειροκίνητης εργασίας. + +## Συμπέρασμα + +Μόλις μάθατε πώς να **εξάγετε docx σε txt** με Java, διασφαλίζοντας ότι κάθε χαρακτήρας Unicode παραμένει αμετάβλητος, οι πίνακες παραμένουν αναγνώσιμοι, και όλη η διαδικασία είναι επαναλήψιμη. Διαμορφώνοντας το `TxtSaveOptions` για UTF‑8 και προαιρετικά διατηρώντας τις διατάξεις των πινάκων, μπορείτε αξιόπιστα να **μετατρέψετε docx σε κείμενο**, **μετατρέψετε word σε κείμενο**, και **εξάγετε word ως txt** για οποιοδήποτε downstream workflow. + +Έτοιμοι για την επόμενη πρόκληση; Δοκιμάστε να εξάγετε σε άλλες μορφές plain‑text όπως markdown (`.md`) ή CSV, ή εξερευνήστε τις δυνατότητες μετατροπής PDF του Aspose.Words. Οι ίδιες αρχές—ρητή κωδικοποίηση, διατήρηση διάταξης και πλήρης επαλήθευση—εφαρμόζονται παντού. + +Καλό κώδικα, και εύχομαι τα αρχεία κειμένου σας να παραμένουν πάντα πλούσια σε Unicode! + +--- + +![Διάγραμμα που δείχνει τη διαδικασία εξαγωγής docx σε txt](/images/export-docx-to-txt-pipeline.png){alt="διάγραμμα διαδικασίας εξαγωγής docx σε txt"} + +## Σχετικά Μαθήματα + +- [Μετατροπή Docx σε Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Μετατροπή DOCX σε PDF με Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Μετατροπή docx σε markdown – Εξαγωγή Μαθηματικών Εξισώσεων σε LaTeX με Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/greek/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..9596aa9d70 --- /dev/null +++ b/words/greek/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-05-26 +description: Αποθήκευση εγγράφου ως PDF χρησιμοποιώντας το Aspose.Words Java και προσθήκη + προσβασιμότητας στο PDF. Μάθετε πώς να μετατρέπετε docx σε PDF, να επισημαίνετε + οριζόντιες γραμμές και να εξασφαλίζετε τη συμμόρφωση με το PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: el +og_description: Αποθηκεύστε το έγγραφο ως PDF με το Aspose.Words Java, προσθέτοντας + προσβασιμότητα στο PDF. Οδηγός βήμα‑βήμα για τη μετατροπή docx σε PDF και την επισήμανση + οριζόντιων γραμμών για συμμόρφωση με PDF/UA‑2. +og_title: Αποθήκευση εγγράφου ως PDF με το Aspose.Words Java – Η προσβασιμότητα γίνεται + εύκολη +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Αποθήκευση εγγράφου ως PDF με το Aspose.Words Java – Πλήρης οδηγός προσβασιμότητας +url: /el/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αποθήκευση Εγγράφου ως PDF με Aspose.Words Java – Οδηγός Πλήρους Προσβασιμότητας + +Έχετε αναρωτηθεί ποτέ πώς να **αποθηκεύσετε ένα έγγραφο ως PDF** διατηρώντας το προσβάσιμο για προγράμματα ανάγνωσης οθόνης; Δεν είστε μόνοι. Πολλοί προγραμματιστές χρειάζονται να *μετατρέψουν docx σε pdf* και να τηρήσουν τα πρότυπα PDF/UA‑2, ειδικά όταν η πηγή περιέχει οριζόντιες γραμμές που πρέπει να επισημαίνονται σωστά. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα τις ακριβείς ενέργειες για **αποθήκευση εγγράφου ως PDF** χρησιμοποιώντας το Aspose.Words for Java, αυτόματα **προσθέτοντας προσβασιμότητα στο PDF**, και διασφαλίζοντας ότι κάθε οριζόντια γραμμή είναι **επισημασμένη** ως τεχνητό στοιχείο. + +Θα ξεκινήσουμε με ένα καθαρό έργο Java, θα φορτώσουμε ένα DOCX που ήδη περιέχει οριζόντιες γραμμές, θα ρυθμίσουμε τις επιλογές αποθήκευσης PDF για συμμόρφωση με PDF/UA‑2, και τέλος θα γράψουμε ένα πλήρως προσβάσιμο PDF. Στο τέλος, θα μπορείτε να **αποθηκεύσετε το έγγραφο ως pdf** με την εμπιστοσύνη ότι περνάει τους ελέγχους προσβασιμότητας. + +## Προαπαιτούμενα + +- Java 8 ή νεότερη εγκατεστημένη (το tutorial δοκιμάστηκε σε JDK 17). +- Maven 3.6+ (ή Gradle αν προτιμάτε) για διαχείριση εξαρτήσεων. +- Ένα έγκυρο license του Aspose.Words for Java (η δωρεάν δοκιμή λειτουργεί, αλλά ένα license αφαιρεί τα υδατογραφήματα αξιολόγησης). +- Ένα αρχείο DOCX (`input.docx`) που περιλαμβάνει τουλάχιστον μία οριζόντια γραμμή — σκεφτείτε έναν απλό διαχωριστικό γραμμής που θα προσθέτατε στο Word. + +> **Pro tip:** Αν δεν έχετε διαθέσιμο DOCX, δημιουργήστε ένα νέο έγγραφο Word, πληκτρολογήστε μερικές παραγράφους, εισάγετε *Insert → Horizontal Line*, αποθηκεύστε ως `input.docx` και τοποθετήστε το σε φάκελο της επιλογής σας. + +## Βήμα 1: Ρύθμιση του Maven Project + +Πρώτα, δημιουργήστε ένα νέο Maven project (ή προσθέστε σε υπάρχον). Το `pom.xml` χρειάζεται την εξάρτηση Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** Η προσθήκη του artifact `aspose-words` είναι το πρώτο βήμα για *convert docx to pdf*. Χωρίς αυτό, ο μεταγλωττιστής δεν θα αναγνωρίζει τις κλάσεις `Document`, `PdfSaveOptions` και άλλες κρίσιμες κλάσεις. + +## Βήμα 2: Φόρτωση του Πηγαίου DOCX που Περιέχει Οριζόντιες Γραμμές + +Τώρα θα γράψουμε μια μικρή κλάση Java που φορτώνει το DOCX. Εδώ αρχίζει το τμήμα **tag horizontal rules** — το Aspose.Words αντιμετωπίζει αυτόματα μια οριζόντια γραμμή ως παράγραφο με περίγραμμα, αλλά θα αφήσουμε τη μηχανή PDF/UA να χειριστεί την επισήμανση. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Παρατηρήστε ότι δεν έχουμε αποθηκεύσει τίποτα ακόμα — απλώς **φορτώνουμε** το DOCX, που είναι το πρώτο μισό του *convert docx to pdf*. Το αντικείμενο `Document` τώρα περιέχει όλο το περιεχόμενο του Word, συμπεριλαμβανομένων των οριζόντιων γραμμών που εισάγατε. + +## Βήμα 3: Ρύθμιση των Επιλογών Αποθήκευσης PDF για Συμμόρφωση με PDF/UA‑2 + +Η μαγεία του **adding accessibility to PDF** βρίσκεται στο `PdfSaveOptions`. Ορίζοντας το επίπεδο συμμόρφωσης σε `PDF_UA_2`, το Aspose.Words θα: + +1. Επισημάνει δομικά στοιχεία (κεφαλίδες, πίνακες κ.λπ.). +2. Σημάνει διακοσμητικά στοιχεία — όπως οι οριζόντιες γραμμές — ως *artifacts*, ώστε τα προγράμματα ανάγνωσης οθόνης να τα αγνοούν. +3. Εισάγει τα απαραίτητα μεταδεδομένα PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** Χωρίς `PDF_UA_2`, το παραγόμενο PDF μπορεί να είναι αναγνώσιμο αλλά δεν θα περάσει τους αυτοματοποιημένους ελεγκτές προσβασιμότητας. Η απαίτηση **tag horizontal rules** ικανοποιείται αυτόματα επειδή το PDF/UA τα αντιμετωπίζει ως *artifacts* όταν είναι ενεργοποιημένη η σημαία συμμόρφωσης. + +## Βήμα 4: Αποθήκευση του Εγγράφου ως PDF + +Τώρα τελικά **αποθηκεύουμε το έγγραφο ως pdf**. Αυτή η μοναδική γραμμή κάνει όλη τη βαριά δουλειά — μετατρέπει το DOCX, εφαρμόζει τις ετικέτες προσβασιμότητας και γράφει το αρχείο στο δίσκο. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Εκτελέστε την κλάση (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) και θα δείτε ένα μήνυμα επιβεβαίωσης. Ανοίξτε το παραγόμενο `ua_compliant.pdf` στο Adobe Acrobat και ελέγξτε **File → Properties → Description → PDF/A, PDF/UA** — θα πρέπει να δείτε την ένδειξη “PDF/UA‑2”. + +### Αναμενόμενη Έξοδος + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Ανοίξτε το PDF και θα παρατηρήσετε: + +- Το κείμενο του εγγράφου είναι επιλέξιμο και αναζητήσιμο. +- Η οριζόντια γραμμή είναι αόρατη στα προγράμματα ανάγνωσης οθόνης (θεωρείται artifact). +- Το PDF περνά τα βασικά εργαλεία επικύρωσης PDF/UA (π.χ., PAC 3). + +## Βήμα 5: Επαλήθευση Προσβασιμότητας – Γρήγορη Λίστα Ελέγχου + +Ακόμη και αν το Aspose.Words κάνει το μεγαλύτερο μέρος της δουλειάς, είναι καλή πρακτική να επαληθεύετε το αποτέλεσμα. + +| Έλεγχος | Πώς να Επαληθεύσετε | +|-------|----------------------| +| **Τίτλος εγγράφου** | Ανοίξτε το Acrobat → File → Properties → πεδίο Title (πρέπει να ταιριάζει με `pdfOptions.setTitle`). | +| **Επισήμανση artifact** | Χρησιμοποιήστε το εργαλείο “Reading Order” του Acrobat. Οι οριζόντιες γραμμές πρέπει να εμφανίζονται ως *Artifact* (γκρι). | +| **Λογική σειρά ανάγνωσης** | Εκτελέστε το “Accessibility Checker” στο Acrobat· βεβαιωθείτε ότι δεν υπάρχουν δομικά σφάλματα. | +| **Tagged PDF** | Στο Acrobat, δείτε το πάνελ “Tags” – πρέπει να υπάρχει ιεραρχία (Document → Section → Paragraph κ.λπ.). | +| **Συμμόρφωση PDF/UA** | Το Acrobat θα εμφανίσει “PDF/UA‑2” στην καρτέλα “Standards”. | + +Αν κάποιος από αυτούς τους ελέγχους αποτύχει, ελέγξτε ξανά ότι χρησιμοποιείτε την πιο πρόσφατη έκδοση του Aspose.Words και ότι η κλήση `setCompliance(PdfCompliance.PDF_UA_2)` έχει εφαρμοστεί σωστά. + +## Συνηθισμένα Πάγια & Πώς να τα Αποφύγετε + +1. **Missing License** – Η δοκιμαστική έκδοση προσθέτει υδατογράφημα που μπορεί να σπάσει την επικύρωση PDF/UA. Εφαρμόστε το license νωρίς στο `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – Μια `FileNotFoundException` θα σταματήσει τη μετατροπή. Χρησιμοποιήστε απόλυτες διαδρομές ή τοποθετήστε το DOCX στη ρίζα του έργου και αναφερθείτε του με `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – Η υποστήριξη PDF/UA προστέθηκε στην έκδοση 22.9. Αναβαθμίστε στην πιο πρόσφατη έκδοση για να αποφύγετε ελλείψεις λειτουργιών. +4. **Horizontal Rule as Image** – Αν εισάγατε τη γραμμή ως εικόνα αντί για ενσωματωμένη οριζόντια γραμμή του Word, το Aspose τη θεωρεί κανονική εικόνα, όχι artifact. Αντικαταστήστε την εικόνα με την ενσωματωμένη *Horizontal Line* του Word για σωστή επισήμανση. + +## Επέκταση της Λύσης – Τι Αν Χρειαστείτε Περισσότερα; + +- **Custom Tags**: Αν έχετε άλλα διακοσμητικά στοιχεία (π.χ., εικονίδια), μπορείτε να τα σημάνετε χειροκίνητα ως artifacts χρησιμοποιώντας `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Επανάληψη πάνω σε φάκελο DOCX αρχείων και batch‑convert, επαναχρησιμοποιώντας το ίδιο αντικείμενο `PdfSaveOptions` για καλύτερη απόδοση. +- **Adding a Language Tag**: Για πολυγλωσσικά PDF, ορίστε `pdfOptions.setLanguage("en-US")` ώστε οι βοηθητικές τεχνολογίες να επιλέγουν τη σωστή φωνή. + +## Πλήρες Παράδειγμα (Όλος ο Κώδικας Μαζί) + +Παρακάτω βρίσκεται το πλήρες, εκτελέσιμο πρόγραμμα Java. Αντιγράψτε‑και‑επικολλήστε το στο IDE σας, προσαρμόστε τις διαδρομές και τρέξτε. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Τρέξτε το, ανοίξτε το παραγόμενο PDF και θα έχετε ένα καθαρό, προσβάσιμο αρχείο έτοιμο για διανομή. + +## Συμπέρασμα + +Δείξαμε πώς να **αποθηκεύσετε το έγγραφο ως pdf** με το Aspose.Words for Java ενώ αυτόματα **προσθέτετε προσβασιμότητα στο pdf** και **επισήμανετε τις οριζόντιες γραμμές** ως artifacts. Τα κύρια σημεία: + +- Χρησιμοποιήστε `PdfSaveOptions` με συμμόρφωση `PDF_UA_2` για να πληροίτε τα πρότυπα προσβασιμότητας. +- Η φόρτωση ενός DOCX και η κλήση `doc.save(..., pdfOptions)` είναι ό,τι χρειάζεστε για **convert docx to pdf**. +- Οι οριζόντιες γραμμές διαχειρίζονται αυτόματα — δεν απαιτείται επιπλέον κώδικας, ικανοποιώντας την απαίτηση **tag horizontal rules**. +- Η προσέγγιση είναι πλήρως **aspose convert docx pdf** συμμορφωμένη, λειτουργεί με την πιο πρόσφατη έκδοση της βιβλιοθήκης και παράγει ένα PDF έτοιμο για επικύρωση. + +Είστε έτοιμοι για την επόμενη πρόκληση; Δοκιμάστε να προσθέσετε προσαρμοσμένα μεταδεδομένα, ενσωμάτωση γραμματοσειρών ή batch‑processing ολόκληρου φακέλου DOCX αρχείων. Κάθε μία από αυτές τις επεκτάσεις βασίζεται στην ίδια θεμελιώδη βάση που θέσαμε εδώ. + +Έχετε ερωτήσεις σχετικά με τη συμμόρφωση PDF/UA, τις άδειες ή τη διαχείριση άλλων στοιχείων του Word; Αφήστε ένα σχόλιο ή ελέγξτε την επίσημη τεκμηρίωση του Aspose — υπάρχει πληθώρα παραδειγμάτων προς εξερεύνηση. Καλή προγραμματιστική δουλειά και απολαύστε τη δημιουργία προσβάσιμων PDF! + +![αποθήκευση εγγράφου ως pdf χρησιμοποιώντας Aspose.Words Java – παράδειγμα προσβάσιμου PDF](placeholder-image.png "αποθήκευση εγγράφου ως pdf χρησιμοποιώντας Aspose.Words Java") + +## Σχετικά Tutorials + +- [Πώς να αποθηκεύσετε έγγραφο ως pdf με Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Πώς να μετατρέψετε Word σε PDF χρησιμοποιώντας Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Μετατροπή DOCX σε PDF σε Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/greek/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..5e4b8ffbab --- /dev/null +++ b/words/greek/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Αποθηκεύστε το Word ως markdown και ανακαλύψτε πώς να εξάγετε μαθηματικές + εξισώσεις σε LaTeX χρησιμοποιώντας το Aspose.Words for Java. Μετατρέψτε τις εξισώσεις + του Word σε LaTeX με λίγες μόνο γραμμές. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: el +og_description: Αποθηκεύστε το Word ως markdown και μάθετε πώς να εξάγετε μαθηματικές + εξισώσεις σε LaTeX χρησιμοποιώντας το Aspose.Words for Java. Ένας πλήρης, εκτελέσιμος + οδηγός. +og_title: Αποθήκευση Word ως markdown – Εξαγωγή μαθηματικών σε LaTeX με Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Αποθήκευση του Word ως markdown – Εξαγωγή μαθηματικών σε LaTeX με Java +url: /el/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Αποθήκευση Word ως Markdown – Εξαγωγή Μαθηματικών σε LaTeX με Java + +Έχετε ποτέ χρειαστεί να **αποθηκεύσετε το Word ως markdown** αλλά ανησυχείτε ότι οι εξισώσεις σας θα μετατραπούν σε ακατάληπτο μπερδεμένο κείμενο; Δεν είστε μόνοι. Σε αυτόν τον οδηγό θα σας δείξουμε **πώς να εξάγετε μαθηματικά** από ένα αρχείο `.docx` απευθείας σε LaTeX, ενώ το υπόλοιπο του εγγράφου γίνεται καθαρό Markdown. + +Θα καλύψουμε τα πάντα, από τη ρύθμιση της βιβλιοθήκης Aspose.Words μέχρι την επαλήθευση του τελικού αρχείου `out.md`. Στο τέλος θα μπορείτε να **μετατρέψετε εξισώσεις Word σε LaTeX** με μία μόνο κλήση μεθόδου, και θα κατανοήσετε τις μικρές λεπτομέρειες που κάνουν την μετατροπή αξιόπιστη. + +--- + +## Τι θα χρειαστείτε + +- **Java 8+** – ο κώδικας εκτελείται σε οποιοδήποτε πρόσφατο JDK. +- **Aspose.Words for Java** – είτε η εξάρτηση Maven/Gradle είτε το JAR αν προτιμάτε χειροκίνητη εγκατάσταση. +- Ένα έγγραφο Word (`math.docx`) που περιέχει τουλάχιστον μία εξίσωση Office Math. +- Ένα IDE ή απλή γραμμή εντολών `javac`/`java` – ό,τι σας βολεύει. + +Αν τα έχετε ήδη, υπέροχα. Αν όχι, η επόμενη ενότητα δείχνει ακριβώς πώς να προσθέσετε τη βιβλιοθήκη στο έργο σας. + +--- + +## Αποθήκευση Word ως markdown – Βήμα 1: Προσθήκη Aspose.Words στο Έργο σας + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose προσφέρει δωρεάν προσωρινή άδεια για δοκιμές. Τοποθετήστε το αρχείο `license.xml` στο φάκελο resources και καλέστε `License license = new License(); license.setLicense("license.xml");` πριν φορτώσετε οποιοδήποτε έγγραφο. + +Μόλις επιλυθεί η εξάρτηση, είστε έτοιμοι να γράψετε τον κώδικα μετατροπής. + +--- + +## Πώς να εξάγετε εξισώσεις μαθηματικών σε LaTeX + +Η βαριά δουλειά γίνεται από το `MarkdownSaveOptions`. Αλλάζοντας το `OfficeMathExportMode` του σε `LATEX`, κάθε αντικείμενο Office Math αποδίδεται ως ένα τμήμα LaTeX μέσα στην έξοδο Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Γιατί λειτουργεί αυτό + +- **`Document`** είναι το σημείο εισόδου της Aspose· αφαιρεί την αφηρημένη παρουσία του αρχείου `.docx` και σας δίνει πρόσβαση σε κάθε κόμβο, συμπεριλαμβανομένων των εξισώσεων. +- **`MarkdownSaveOptions`** λέει στη βιβλιοθήκη *πώς* θέλετε την έξοδο. Η προεπιλεγμένη συμπεριφορά είναι η απόδοση των εξισώσεων ως εικόνες, κάτι που αναιρεί τον σκοπό μιας μορφής βασισμένης σε κείμενο. +- **`OfficeMathExportMode.LATEX`** αναγκάζει τη μηχανή να μεταφράσει κάθε κόμβο `OfficeMath` στην ισοδύναμη LaTeX, την οποία οι αναλυτές Markdown (όπως GitHub ή Jekyll) μπορούν να αποδώσουν όταν συνδυαστούν με ένα πρόσθετο MathJax. + +--- + +## Μετατροπή εξισώσεων Word σε LaTeX – Βήμα 2: Επαλήθευση της εξόδου Markdown + +Αφού τρέξετε το πρόγραμμα, ανοίξτε το `out.md`. Θα πρέπει να δείτε κάτι σαν αυτό: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** Τα τμήματα LaTeX είναι τυλιγμένα σε `$…$` για ενσωματωμένα μαθηματικά και `$$…$$` για μπλοκ μαθηματικά. Αυτή είναι η τυπική σύνταξη που κατανοούν οι περισσότεροι στατικοί δημιουργοί ιστοσελίδων όταν είναι ενεργοποιημένο το MathJax. + +Αν προτιμάτε οι εξισώσεις να παραμένουν μόνο ενσωματωμένες, μπορείτε να προσαρμόσετε περαιτέρω το `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx σε markdown latex – Βήμα 3: Ακραίες Περιπτώσεις & Συνηθισμένα Πιθανά Σφάλματα + +| Κατάσταση | Τι πρέπει να προσέξετε | Διόρθωση | +|-----------|-------------------|-----| +| **Πολύπλοκες ένθετες εξισώσεις** | Το Aspose μπορεί να παράγει επιπλέον αγκύλες `{}` που ορισμένοι αναλυτές τις αντιμετωπίζουν κυριολεκτικά. | Μετά-επεξεργαστείτε το Markdown με ένα απλό regex για να συμπτύξετε `{{` → `{`. | +| **Απουσία MathJax στον προορισμό** | Οι εξισώσεις εμφανίζονται ως ακατέργαστος κώδικας LaTeX. | Προσθέστε `` στο πρότυπο HTML σας. | +| **Μεγάλα έγγραφα** | Η κατανάλωση μνήμης αυξάνεται επειδή ολόκληρο το έγγραφο φορτώνεται ταυτόχρονα. | Χρησιμοποιήστε `LoadOptions.setLoadFormat(LoadFormat.DOCX)` και σκεφτείτε την επεξεργασία σε παρτίδες αν αντιμετωπίσετε `OutOfMemoryError`. | +| **Άδεια δεν έχει οριστεί** | Θα λάβετε μια προειδοποίηση και η έξοδος μπορεί να έχει υδατογράφημα. | Φορτώστε την άδεια νωρίς στο `main` όπως φαίνεται στην παραπάνω συμβουλή Maven. | + +--- + +## Αποθήκευση Word ως markdown – Πλήρες Παράδειγμα Εργασίας + +Παρακάτω υπάρχει μια αυτόνομη κλάση που μπορείτε να αντιγράψετε‑επικολλήσετε σε οποιοδήποτε έργο Java. Απλώς αντικαταστήστε το `YOUR_DIRECTORY` με τη διαδρομή προς τα αρχεία σας. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Εκτελέστε το πρόγραμμα (`java MathToLatexMarkdown`) και θα δείτε το μήνυμα στην κονσόλα που επιβεβαιώνει την επιτυχία. Ανοίξτε το `out.md` σε οποιονδήποτε επεξεργαστή – οι εξισώσεις θα πρέπει να είναι καθαρά αποσπάσματα LaTeX έτοιμα για απόδοση. + +--- + +## Αναμενόμενη Στιγμιότυπο Εξόδου + +![Αποθήκευση Word ως markdown έξοδος με εξισώσεις LaTeX](https://example.com/images/markdown-latex-output.png "Αποθήκευση Word ως markdown έξοδος με εξισώσεις LaTeX") + +*Η εικόνα δείχνει ένα απόσπασμα του παραγόμενου Markdown όπου η εξίσωση `\int_{a}^{b} f(x)\,dx` είναι τυλιγμένη σε `$$`.* + +--- + +## Συμπέρασμα + +Μόλις δείξαμε πώς να **αποθηκεύσετε το Word ως markdown** διατηρώντας κάθε εξίσωση Office Math ως αυτόματο LaTeX. Το βασικό βήμα ήταν η διαμόρφωση του `MarkdownSaveOptions` με `OfficeMathExportMode.LATEX`, που μετατρέπει μια τυπική διαδικασία Word‑σε‑Markdown σε ένα πλήρως μαθηματικά‑συνεπές εργαλείο μετατροπής. + +Τώρα μπορείτε: + +1. **Πώς να εξάγετε μαθηματικά** από οποιοδήποτε `.docx` χωρίς απώλεια πιστότητας. +2. **Μετατροπή εξισώσεων Word σε LaTeX** για στατικούς δημιουργούς ιστοσελίδων, τεκμηρίωση ή ακαδημαϊκά blogs. +3. Επεκτείνετε την προσέγγιση για μαζική επεξεργασία πολλών αρχείων, ενσωμάτωση σε CI pipelines, ή ακόμη και δημιουργία μιας μικρής web υπηρεσίας. + +Αν είστε περίεργοι για το επόμενο βήμα, δοκιμάστε να συνδυάσετε αυτό με **docx to markdown latex** για έγγραφα με πολλές εικόνες, ή εξερευνήστε το `HtmlSaveOptions` της Aspose για μια έκδοση HTML έτοιμη για web. Οι δυνατότητες είναι ατελείωτες—πειραματιστείτε, σπάστε πράγματα, και στη συνέχεια μοιραστείτε τα ευρήματά σας με την κοινότητα. + +Έχετε ερωτήσεις ή μια δύσκολη εξίσωση που δεν αποδόθηκε όπως αναμενόταν; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +## Σχετικά Μαθήματα + +- [Πώς να εξάγετε LaTeX από το Word: Μετατροπή DOCX σε Markdown & Αποθήκευση ως PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Μετατροπή docx σε markdown – Εξαγωγή εξισώσεων μαθηματικών σε LaTeX με Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Πώς να μετατρέψετε το Word σε PDF χρησιμοποιώντας Aspose.Words για Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/greek/java/document-loading-and-saving/_index.md index cb4d0b97ca..bdf875b3f0 100644 --- a/words/greek/java/document-loading-and-saving/_index.md +++ b/words/greek/java/document-loading-and-saving/_index.md @@ -103,6 +103,7 @@ Aspose.Words for Java καθιστά απλό το **save images from Word** έ ### [Καθορισμός Μορφής Εγγράφου στο Aspose.Words for Java](./determining-document-format/) ### [Ανάκτηση κατεστραμμένου docx – Πλήρης Οδηγός για Διόρθωση και Επεξεργασία Εγγράφων](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) ### [Καταγραφή Προειδοποιήσεων Αντικατάστασης Γραμματοσειράς σε Java με Aspose.Words – Πλήρης Οδηγός](./capture-font-substitution-warnings-in-java-with-aspose-words/) +### [Άνοιγμα Κατεστραμμένου Εγγράφου Word – Ορισμός Λειτουργίας Ανάκτησης σε Java](./open-corrupted-word-document-set-recovery-mode-in-java/) ## Συχνές Ερωτήσεις diff --git a/words/greek/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/greek/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..62cc2b6f4a --- /dev/null +++ b/words/greek/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,193 @@ +--- +category: general +date: 2026-05-26 +description: Ανοίξτε κατεστραμμένο έγγραφο Word σε Java με το Aspose.Words. Μάθετε + πώς να ορίσετε τη λειτουργία ανάκτησης και να επαναφέρετε αξιόπιστα κατεστραμμένα + αρχεία Word. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: el +og_description: Ανοίξτε κατεστραμμένο έγγραφο Word σε Java χρησιμοποιώντας το Aspose.Words. + Αυτός ο οδηγός δείχνει πώς να ορίσετε τη λειτουργία ανάκτησης και να ανακτήσετε + αποδοτικά κατεστραμμένα αρχεία Word. +og_title: Άνοιγμα Κατεστραμμένου Εγγράφου Word – Ορισμός Λειτουργίας Ανάκτησης σε + Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Άνοιγμα Κατεστραμμένου Εγγράφου Word – Ορισμός Λειτουργίας Ανάκτησης σε Java +url: /el/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Άνοιγμα Κατεστραμμένου Εγγράφου Word – Ορισμός Λειτουργίας Ανάκτησης σε Java + +Ποτέ προσπαθήσατε να ανοίξετε ένα κατεστραμμένο έγγραφο Word και παρακολουθήσατε το πρόγραμμα να αποτυγχάνει με μια εξαίρεση; Δεν είστε μόνοι—αυτά τα σπασμένα .docx αρχεία μπορούν να γίνουν πραγματικό κεφάλι‑πυρήνα. Τα καλά νέα είναι ότι το Aspose.Words for Java σας δίνει λεπτομερή έλεγχο ώστε να μπορείτε να **open corrupted word document** χωρίς να καταρρεύσει η εφαρμογή, και ακόμη να αποφασίσετε αν θέλετε προειδοποιήσεις, σιωπηλή ανάκτηση ή σκληρή απόρριψη. + +Σε αυτό το tutorial θα περάσουμε από τη πλήρη διαδικασία: από τη δημιουργία του σωστού `LoadOptions`, μέχρι την επιλογή της κατάλληλης τιμής **set recovery mode**, και τέλος την επιβεβαίωση ότι το έγγραφο φορτώθηκε πράγματι. Στο τέλος θα γνωρίζετε **how to recover corrupted word file** προγραμματιστικά, χωρίς να χρειάζεται χειροκίνητη αντιγραφή‑επικόλληση. + +> **Τι θα χρειαστείτε** +> * Java 8 ή νεότερη (το API λειτουργεί επίσης με Java 11) +> * Aspose.Words for Java 23.9 (ή την πιο πρόσφατη έκδοση) +> * Ένα δείγμα κατεστραμμένου .docx αρχείου—απλώς μετονομάστε οποιοδήποτε έγκυρο αρχείο για να προσομοιώσετε τη ζημιά αν δεν έχετε κάποιο διαθέσιμο + +Ας βουτήξουμε. + +## Άνοιγμα Κατεστραμμένου Εγγράφου Word – Επισκόπηση Βήμα‑προς‑Βήμα + +Παρακάτω είναι η υψηλού επιπέδου ροή που θα υλοποιήσουμε: + +1. **Create `LoadOptions`** – αυτό το αντικείμενο λέει στο Aspose.Words πώς να συμπεριφέρεται όταν αντιμετωπίζει προβλήματα. +2. **Set recovery mode** – επιλέξτε `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, ή `REJECT_CORRUPTED`. +3. **Load the document** χρησιμοποιώντας τις ρυθμισμένες επιλογές. +4. **Verify** ότι η φόρτωση πέτυχε (π.χ., εκτυπώστε τον αριθμό σελίδων). + +Κάθε βήμα εξηγείται λεπτομερώς, με αποσπάσματα κώδικα που μπορείτε να αντιγράψετε‑επικολλήσετε απευθείας στο IDE σας. + +## Ορισμός Λειτουργίας Ανάκτησης για Διαφορετικά Σενάρια + +Το Aspose.Words ορίζει τρεις στρατηγικές ανάκτησης μέσα στο `LoadOptions.RecoveryMode`: + +| Λειτουργία | Συμπεριφορά | Πότε να χρησιμοποιηθεί | +|------------|--------------|------------------------| +| `RECOVER_WITH_WARNINGS` | Προσπαθεί να φορτώσει το έγγραφο, αλλά εμφανίζει τυχόν προβλήματα ως προειδοποιήσεις στην κονσόλα. | Θέλετε να δείτε *τι* πήγε στραβά χωρίς να διακόψετε. | +| `RECOVER_WITHOUT_WARNINGS` | Διορθώνει σιωπηλά ό,τι μπορεί και καταστέλλει τις προειδοποιήσεις. | Περιβάλλοντα παραγωγής όπου τα αρχεία καταγραφής πρέπει να παραμένουν καθαρά. | +| `REJECT_CORRUPTED` | Ρίχνει εξαίρεση τη στιγμή που εντοπίζεται η ζημιά. | Ασυστηρές γραμμές επικύρωσης που πρέπει να αποτυγχάνουν γρήγορα. | + +Η επιλογή της σωστής λειτουργίας είναι η ουσία του **set recovery mode** σωστά. Στις περισσότερες συνεδρίες εντοπισμού σφαλμάτων, το `RECOVER_WITH_WARNINGS` είναι η ιδανική επιλογή επειδή σας λέει ακριβώς ποια τμήματα διορθώθηκαν. + +## Πώς να Ανακτήσετε Κατεστραμμένο Αρχείο Word Χρησιμοποιώντας Aspose.Words + +Παρακάτω είναι ένα **πλήρες, εκτελέσιμο πρόγραμμα Java** που δείχνει όλη τη διαδικασία. Μη διστάσετε να το τοποθετήσετε σε ένα αρχείο `RecoveryModeDemo.java`, να προσαρμόσετε τη διαδρομή και να το εκτελέσετε. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Γιατί κάθε γραμμή είναι σημαντική + +* **`LoadOptions loadOptions = new LoadOptions();`** – χωρίς αυτό το αντικείμενο το Aspose.Words χρησιμοποιεί την προεπιλεγμένη ανάκτηση, η οποία *απορρίπτει* τα κατεστραμμένα αρχεία. Η δημιουργία του σας δίνει το σημείο για να αλλάξετε αυτή τη συμπεριφορά. +* **`setRecoveryMode(...)`** – αυτή είναι η κλήση **set recovery mode** που αποφασίζει αν εμφανίζονται προειδοποιήσεις, παραμένουν κρυφές, ή προκαλούν εξαίρεση. +* **`new Document(path, loadOptions);`** – ο κατασκευαστής δέχεται το `LoadOptions` που μόλις διαμορφώσαμε, ώστε η βιβλιοθήκη να ξέρει πώς να αντιμετωπίσει το κατεστραμμένο αρχείο από την αρχή. +* **`doc.getPageCount()`** – ένας γρήγορος έλεγχος λογικής. Αν το έγγραφο φορτωθεί και επιστρέψει αριθμό σελίδων, έχετε επιτυχώς **how to recover corrupted word file**. +* **`doc.save(...)`** – προαιρετικό αλλά χρήσιμο· μπορείτε να γράψετε την επισκευασμένη έκδοση ξανά στο δίσκο για μελλοντική χρήση. + +## Διαχείριση Συνηθισμένων Ακραίων Περιπτώσεων + +### 1. Αρχείο Δεν Βρέθηκε + +Αν η διαδρομή είναι λανθασμένη, το `Document` ρίχνει `FileNotFoundException`. Τυλίξτε τη φόρτωση σε μπλοκ try‑catch και καταγράψτε ένα φιλικό μήνυμα: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Μη Ανακτήσιμη Ζημιά + +Ακόμη και με `RECOVER_WITH_WARNINGS`, ορισμένες δομές είναι πέρα από την επισκευή. Σε αυτήν την περίπτωση το Aspose.Words φορτώνει ό,τι μπορεί, αλλά θα δείτε προειδοποιήσεις όπως «Cannot read paragraph properties». Δώστε προσοχή στην έξοδο της κονσόλας· αυτές οι προειδοποιήσεις συχνά δείχνουν σε ελλιπείς ενότητες που ίσως χρειαστεί να ανακατασκευάσετε χειροκίνητα. + +### 3. Μεγάλα Αρχεία και Απόδοση + +Η ανάκτηση προσθέτει μικρή επιβάρυνση επειδή η βιβλιοθήκη αναλύει το αρχείο δύο φορές—μία για την ανίχνευση προβλημάτων, άλλη για την επανακατασκευή. Για έγγραφα πολλαπλών γιγαμπάιτ, σκεφτείτε τη ροή του αρχείου ή την αύξηση του heap της JVM (`-Xmx2g`) για να αποφύγετε `OutOfMemoryError`. + +## Pro Συμβουλές – Κατασκευή Ανθεκτικής Ανάκτησης + +* **Log warnings to a file** – ανακατευθύνετε το `System.err` σε logger ώστε να έχετε ίχνος ελέγχου για ό,τι διορθώθηκε. +* **Validate after recovery** – εκτελέστε `doc.updatePageLayout();` και μετά ελέγξτε ξανά τον αριθμό σελίδων· μερικές φορές η διάταξη αλλάζει μετά την επισκευή των σπασμένων ενοτήτων. +* **Automate batch recovery** – τυλίξτε το demo σε βρόχο που επεξεργάζεται ένα φάκελο κατεστραμμένων αρχείων, χρησιμοποιώντας το ίδιο `LoadOptions` κάθε φορά. + +## Συμπέρασμα + +Τώρα γνωρίζετε ακριβώς **how to recover corrupted word file** χρησιμοποιώντας το Aspose.Words for Java. Δημιουργώντας μια παρουσία `LoadOptions`, **set recovery mode** στη στρατηγική που ταιριάζει στο σενάριό σας, και φορτώνοντας το έγγραφο με αυτές τις επιλογές, μπορείτε με ασφάλεια **open corrupted word document** χωρίς να καταρρεύσει η εφαρμογή σας. Ο παραπάνω κώδικας είναι μια πλήρης, έτοιμη‑για‑εκτέλεση λύση που εκτυπώνει τον αριθμό σελίδων και ακόμη αποθηκεύει ένα καθαρισμένο αντίγραφο. + +Τι ακολουθεί; Δοκιμάστε να αλλάξετε τη λειτουργία ανάκτησης σε `RECOVER_WITHOUT_WARNINGS` και συγκρίνετε την έξοδο της κονσόλας, ή πειραματιστείτε με τη φόρτωση κρυπτογραφημένων εγγράφων (θα χρειαστεί να παρέχετε έναν κωδικό πρόσβασης μέσω + +## Σχετικά Μαθήματα + +- [Aspose.Words Java: Ολοκληρωμένος Οδηγός Επεξεργασίας Εγγράφων Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Πώς να Μετατρέψετε Word σε PDF Χρησιμοποιώντας Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [Πώς να Συγκρίνετε Δύο Αρχεία Word με Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/greek/java/document-styling/_index.md index 3af4eb257c..73f9283df2 100644 --- a/words/greek/java/document-styling/_index.md +++ b/words/greek/java/document-styling/_index.md @@ -42,7 +42,9 @@ ### [Υδατογράφημα εγγράφου και διαμόρφωση σελίδας](./document-watermarking-page-setup/) Μάθετε πώς να εφαρμόζετε υδατογραφήματα και να ρυθμίζετε τις διαμορφώσεις σελίδας με το Aspose.Words για Java. Ένας ολοκληρωμένος οδηγός με πηγαίο κώδικα. ### [Στυλ κεφαλίδας και υποσέλιδου εγγράφου](./document-header-footer-styling/) -Μάθετε πώς να διαμορφώνετε κεφαλίδες και υποσέλιδα εγγράφων χρησιμοποιώντας το Aspose.Words για Java σε αυτόν τον λεπτομερή οδηγό. Περιλαμβάνονται οδηγίες βήμα προς βήμα και πηγαίος κώδικας. +Μάθετε πώς να διαμορφώνετε κεφαλίδες και υποσέλιδα εγγράφων χρησιμοποιώντας το Asp Aspose.Words για Java σε αυτόν τον λεπτομερή οδηγό. Περιλαμβάνονται οδηγίες βήμα προς βήμα και πηγαίος κώδικας. +### [Ορισμός προεπιλεγμένων ρυθμίσεων γραμματοσειράς στο Aspose.Words για Java – Πλήρης οδηγός](./set-default-font-settings-in-aspose-words-for-java-complete/) +Μάθετε πώς να ορίσετε προεπιλεγμένες ρυθμίσεις γραμματοσειράς σε έγγραφα Aspose.Words για Java. Οδηγός βήμα‑προς‑βήμα με κώδικα. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/greek/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..46d3722a32 --- /dev/null +++ b/words/greek/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-05-26 +description: Ορίστε τις προεπιλεγμένες ρυθμίσεις γραμματοσειράς στο Aspose.Words for + Java και μάθετε πώς να ορίζετε ρυθμίσεις γραμματοσειράς και να εντοπίζετε ελλιπείς + γραμματοσειρές με λίγες μόνο γραμμές κώδικα. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: el +og_description: Ορίστε τις προεπιλεγμένες ρυθμίσεις γραμματοσειράς στο Aspose.Words + for Java, μάθετε πώς να ορίζετε ρυθμίσεις γραμματοσειράς και να εντοπίζετε ελλιπείς + γραμματοσειρές γρήγορα και αξιόπιστα. +og_title: Ορισμός προεπιλεγμένων ρυθμίσεων γραμματοσειράς στο Aspose.Words για Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Ορισμός προεπιλεγμένων ρυθμίσεων γραμματοσειράς στο Aspose.Words για Java – + Πλήρης οδηγός +url: /el/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ορισμός Προεπιλεγμένων Ρυθμίσεων Γραμματοσειράς στο Aspose.Words for Java – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ πώς να **ορίσετε προεπιλεγμένες ρυθμίσεις γραμματοσειράς** κατά τη φόρτωση ενός εγγράφου Word με το Aspose.Words for Java; Δεν είστε μόνοι. Η έλλειψη γλυφών μπορεί να μετατρέψει μια επαγγελματική αναφορά σε ένα ακατάστατο μπερδεμένο κείμενο, και η έγκαιρη ανίχνευση των προειδοποιήσεων αντικατάστασης γραμματοσειράς εξοικονομεί ώρες εντοπισμού σφαλμάτων. + +Σε αυτό το tutorial θα περάσουμε από ένα σύντομο, ολοκληρωμένο παράδειγμα που **ορίζει προεπιλεγμένες ρυθμίσεις γραμματοσειράς**, σας δείχνει πώς να **ορίσετε ρυθμίσεις γραμματοσειράς** προγραμματιστικά, και παρουσιάζει έναν αξιόπιστο τρόπο για **να εντοπίσετε ελλιπείς γραμματοσειρές** πριν διαταράξουν τη διάταξή σας. + +--- + +## Τι Θα Μάθετε + +- Πώς να δημιουργήσετε ένα αντικείμενο `LoadOptions` με μια νέα παρουσία `FontSettings`. +- Πώς να συνδέσετε έναν ακροατή προειδοποιήσεων που θα **εντοπίσει ελλιπείς γραμματοσειρές** κατά τη φόρτωση του εγγράφου. +- Πώς να φορτώσετε ένα αρχείο DOCX ενώ ο ακροατής αναφέρει σιωπηλά τυχόν αντικαταστάσεις. +- Συμβουλές για προσαρμογή εναλλακτικών γραμματοσειρών και διαχείριση ειδικών περιπτώσεων σε παραγωγή. + +Χωρίς επιπλέον βιβλιοθήκες, χωρίς ασαφή αρχεία ρυθμίσεων — μόνο απλή Java και Aspose.Words. + +## Προαπαιτούμενα + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +1. **Aspose.Words for Java** (έκδοση 23.10 ή νεότερη) στο classpath σας. +2. Ένα Java 17 (ή νεότερο) development kit – οποιοδήποτε σύγχρονο JDK λειτουργεί. +3. Ένα αρχείο DOCX που σκόπιμα χρησιμοποιεί μια γραμματοσειρά που δεν έχετε εγκατεστημένη (π.χ., *“MissingFont.ttf”*). + +Αν λείπει το Aspose JAR, κατεβάστε το από το επίσημο αποθετήριο Maven: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Αυτό είναι όλο — δεν χρειάζεται να εγκαταστήσετε επιπλέον γραμματοσειρές για αυτή τη demo. + +## Βήμα 1: Δημιουργία LoadOptions και **Ορισμός Προεπιλεγμένων Ρυθμίσεων Γραμματοσειράς** + +Το πρώτο που χρειάζεται είναι ένα καθαρό αντικείμενο `LoadOptions` που λέει στο Aspose πώς να συμπεριφέρεται όταν συναντά άγνωστες γραμματοσειρές. Καλώντας το `setFontSettings(new FontSettings())` **ορίζουμε προεπιλεγμένες ρυθμίσεις γραμματοσειράς** που ξεκινούν με μια κενή λίστα εναλλακτικών. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Γιατί είναι σημαντικό:** +> Όταν δεν ρυθμίζετε ρητά τις γραμματοσειρές, το Aspose επιστρέφει στην προεπιλεγμένη συλλογή του συστήματος, η οποία μπορεί να κρύψει προβλήματα ελλιπών γραμματοσειρών. Ξεκινώντας από μια νέα παρουσία `FontSettings` αποκτάτε πλήρη έλεγχο πάνω στο ποιες γραμματοσειρές θεωρούνται έγκυρες. + +## Βήμα 2: Προσθήκη Ακροατή Προειδοποιήσεων για **Εντοπισμό Ελλιπών Γραμματοσειρών** + +Το Aspose δημιουργεί ένα αντικείμενο `WarningInfo` για κάθε αντικατάσταση που εκτελεί. Ακούγοντας για `WarningType.FONT_SUBSTITUTION` μπορούμε να **εντοπίσουμε ελλιπείς γραμματοσειρές** αμέσως μόλις το έγγραφο αναλυθεί. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Συμβουλή:** Ο ακροατής εκτελείται στο ίδιο νήμα που φορτώνει το έγγραφο, έτσι δεν υπάρχει σχεδόν καμία επιβάρυνση στην απόδοση. Αν χρειάζεται να συλλέξετε προειδοποιήσεις για μεταγενέστερη ανάλυση, τοποθετήστε τις σε μια `List` αντί να τις εκτυπώνετε απευθείας. + +## Βήμα 3: Φόρτωση του Εγγράφου Χρησιμοποιώντας τις Ρυθμισμένες Επιλογές + +Τώρα που έχουμε **ορίσει τις ρυθμίσεις γραμματοσειράς** και έχουμε προετοιμάσει έναν ακροατή, απλώς φορτώνουμε το αρχείο. Οποιαδήποτε ελλιπής γραμματοσειρά ενεργοποιεί αμέσως την κλήση μας. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Αν το πηγαίο αρχείο αναφέρει μια γραμματοσειρά που δεν είναι εγκατεστημένη, θα δείτε έξοδο παρόμοια με: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Αυτή η γραμμή σας λέει ακριβώς ποια γραμματοσειρά έλειπε και ποια εναλλακτική χρησιμοποιήθηκε — ιδανικό για καταγραφή ή ανατροφοδότηση χρήστη. + +## Βήμα 4: Συνέχεια Κανονικής Επεξεργασίας (Προαιρετικό) + +Σε αυτό το σημείο το έγγραφο είναι πλήρως φορτωμένο, και μπορείτε να προχωρήσετε με οποιαδήποτε επεξεργασία θέλετε — επεξεργασία, μετατροπή σε PDF ή εξαγωγή κειμένου. Ο ακροατής προειδοποιήσεων έχει ήδη ολοκληρώσει τη δουλειά του, οπότε δεν χρειάζονται επιπλέον έλεγχοι. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Τι γίνεται αν θέλετε μια προσαρμοσμένη εναλλακτική;** +> Αντί να αφήσετε το `FontSettings` κενό, μπορείτε να προσθέσετε συγκεκριμένες γραμματοσειρές: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Τώρα οποιαδήποτε ελλιπής γραμματοσειρά θα αντικατασταθεί με *Times New Roman* — μια αξιόπιστη επιλογή για τα περισσότερα δυτικά έγγραφα. + +## Οπτική Επισκόπηση + +![Διάγραμμα που δείχνει πώς να ορίσετε προεπιλεγμένες ρυθμίσεις γραμματοσειράς στο Aspose.Words for Java](image.png "Διάγραμμα ροής ορισμού προεπιλεγμένων ρυθμίσεων γραμματοσειράς") + +*Κείμενο εναλλακτικού: διάγραμμα ροής ορισμού προεπιλεγμένων ρυθμίσεων γραμματοσειράς στο Aspose.Words for Java.* + +## Συνηθισμένα Πιθανά Σφάλματα & Πώς να τα Αποφύγετε + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Ξεχάσατε να καλέσετε `setFontSettings`** | Το Aspose χρησιμοποιεί τις προεπιλεγμένες ρυθμίσεις του συστήματος, κρύβοντας τις ελλιπείς γραμματοσειρές. | Πάντα δημιουργήστε μια νέα παρουσία `FontSettings` και αντιστοιχίστε την στο `LoadOptions`. | +| **Ο ακροατής δεν ενεργοποιείται** | Ο ακροατής προστέθηκε μετά τη φόρτωση του εγγράφου. | Προσθέστε τον ακροατή προειδοποιήσεων *πριν* καλέσετε `new Document(...)`. | +| **Λάθος διαδρομή οδηγεί σε `FileNotFoundException`** | Η σκληρή κωδικοποίηση της διαδρομής δεν ταιριάζει με την ευαισθησία πεζών-κεφαλαίων του λειτουργικού συστήματος. | Χρησιμοποιήστε `Paths.get("...").toAbsolutePath()` ή ρυθμίστε μια σχετική διαδρομή από τη ρίζα του έργου. | +| **Πολλαπλές ελλιπείς γραμματοσειρές γεμίζουν τα αρχεία καταγραφής** | Μεγάλα έγγραφα μπορεί να δημιουργήσουν δεκάδες προειδοποιήσεις. | Φιλτράρετε τα διπλότυπα ή συγκεντρώστε τα μηνύματα σε ένα `Set` πριν την εκτύπωση. | + +## Επέκταση της Λύσης + +Αν χρειάζεται να **ορίσετε ρυθμίσεις γραμματοσειράς** για ολόκληρη την εφαρμογή, σκεφτείτε να δημιουργήσετε ένα singleton `FontSettings` και να το επαναχρησιμοποιήσετε σε όλα τα `LoadOptions`. Με αυτόν τον τρόπο διατηρείτε μια συνεπή στρατηγική εναλλακτικών και αποφεύγετε την επαναλαμβανόμενη δημιουργία αντικειμένων. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Τώρα οποιοδήποτε τμήμα του κώδικά σας μπορεί απλώς να καλέσει `FontConfig.getLoadOptions()` και άμεσα να επωφεληθεί από την ίδια λογική **ορισμού προεπιλεγμένων ρυθμίσεων γραμματοσειράς**. + +## Συμπέρασμα + +Μόλις καλύψαμε όλα όσα χρειάζεστε για να **ορίσετε προεπιλεγμένες ρυθμίσεις γραμματοσειράς** στο Aspose.Words for Java, να **ορίσετε ρυθμίσεις γραμματοσειράς** προγραμματιστικά, και να **εντοπίσετε ελλιπείς γραμματοσειρές** πριν καταστρέψουν το αποτέλεσμα. Το πλήρες, εκτελέσιμο παράδειγμα βρίσκεται στα αποσπάσματα κώδικα παραπάνω, και μπορείτε να το επικολλήσετε απευθείας στο IDE σας για να δείτε τις προειδοποιήσεις σε δράση. + +Επόμενα βήματα; Δοκιμάστε να αλλάξετε τη γραμματοσειρά εναλλακτική, πειραματιστείτε με διαφορετικές μορφές εγγράφων (DOC, RTF, HTML), ή ενσωματώστε τον συλλέκτη προειδοποιήσεων σε έναν πίνακα παρακολούθησης. Όσο περισσότερο παίζετε με το `FontSettings`, τόσο μεγαλύτερη θα είναι η εμπιστοσύνη ότι τα παραγόμενα έγγραφά σας εμφανίζονται ακριβώς όπως προβλέπεται — χωρίς εκπλήξεις, χωρίς σπασμένα γλυφά. + +Έχετε ερωτήσεις ή ένα δύσκολο σενάριο αντικατάστασης γραμματοσειράς; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +## Σχετικά Μαθήματα + +- [Ορισμός Ρυθμίσεων Εναλλακτικής Γραμματοσειράς](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Ορισμός Ρυθμίσεων Εναλλακτικής Γραμματοσειράς](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Ορισμός Ρυθμίσεων Εναλλακτικής Γραμματοσειράς](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/java/images-shapes/_index.md b/words/greek/java/images-shapes/_index.md index f766f2b5c0..cb4ad705d8 100644 --- a/words/greek/java/images-shapes/_index.md +++ b/words/greek/java/images-shapes/_index.md @@ -37,6 +37,9 @@ ### [Δημιουργία εγγράφου Word Java – Προσθήκη σχήματος ορθογωνίου με εφέ σκιάς](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Μάθετε πώς να προσθέσετε σχήμα ορθογωνίου με εφέ σκιάς σε έγγραφο Word χρησιμοποιώντας το Aspose.Words για Java. +### [Δημιουργία σχήματος ορθογωνίου σε έγγραφο Word Java – Πλήρης οδηγός βήμα‑βήμα](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Μάθετε πώς να δημιουργήσετε σχήμα ορθογωνίου σε έγγραφο Word χρησιμοποιώντας το Aspose.Words για Java, ακολουθώντας πλήρη βήμα‑βήμα οδηγίες. + ## Πρόσθετοι Πόροι - [Aspose.Words για τεκμηρίωση Java](https://reference.aspose.com/words/java/) diff --git a/words/greek/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/greek/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..b46d79bf90 --- /dev/null +++ b/words/greek/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Δημιουργήστε σχήμα ορθογωνίου σε ένα έγγραφο Word με Java και εφαρμόστε + εφέ σκιάς. Μάθετε πώς να προσθέσετε σκιά σε σχήμα, να ορίσετε την απόσταση της σκιάς + και να αποθηκεύσετε το αρχείο. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: el +og_description: Δημιουργήστε σχήμα ορθογωνίου σε ένα έγγραφο Word σε Java, εφαρμόστε + εφέ σκιάς, προσθέστε σκιά στο σχήμα και ορίστε την απόσταση σκιάς με το Aspose.Words. +og_title: Δημιουργία σχήματος ορθογωνίου σε έγγραφο Word με Java – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Δημιουργία σχήματος ορθογωνίου σε έγγραφο Word με Java – Πλήρης οδηγός βήμα‑βήμα +url: /el/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία Σχήματος Ορθογωνίου σε Έγγραφο Word Java – Πλήρης Οδηγός Βήμα‑βήμα + +Έχετε χρειαστεί ποτέ να **create rectangle shape** σε ένα έγγραφο Word Java αλλά δεν ήξερατε από πού να ξεκινήσετε; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν αυτό το πρόβλημα όταν δημιουργούν αναφορές ή τιμολόγια προγραμματιστικά. Σε αυτό το tutorial θα δούμε ακριβώς πώς να **create rectangle shape**, να εφαρμόσουμε μια κομψή σκιά και να ρυθμίσουμε τη απόσταση της σκιάς ώστε το αποτέλεσμα να φαίνεται επαγγελματικό. + +Θα χρησιμοποιήσουμε το Aspose.Words for Java, μια ισχυρή βιβλιοθήκη που σας επιτρέπει να χειρίζεστε αρχεία Word χωρίς να χρειάζεται εγκατεστημένο Microsoft Office. Στο τέλος αυτού του οδηγού θα μπορείτε να **create word document java** έργα που **add shape shadow**, **apply shadow effect**, και **set shadow distance** με μόνο λίγες γραμμές κώδικα. + +--- + +## What You’ll Build + +- Ένα νέο αρχείο `.docx` που περιέχει ένα κυανό ορθογώνιο. +- Μια ρεαλιστική σκιά που είναι θολή, κεκλιμένη και μερικώς διαφανής. +- Πλήρη έλεγχος της απόστασης της σκιάς από το σχήμα. +- Μια έτοιμη προς εκτέλεση κλάση Java που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο Maven ή Gradle. + +Χωρίς εξωτερικά εργαλεία, χωρίς χειροκίνητα βήματα UI—απλώς καθαρός κώδικας. + +--- + +## Prerequisites + +- Java 8 ή νεότερη (ο κώδικας λειτουργεί σε Java 11, Java 17 κ.λπ.). +- Βιβλιοθήκη Aspose.Words for Java (διαθέσιμη μέσω Maven Central). +- Ένα IDE ή κειμενογράφο που προτιμάτε (IntelliJ IDEA, Eclipse, VS Code…). +- Βασική εξοικείωση με τη σύνταξη της Java. + +Αν δεν έχετε προσθέσει ποτέ εξάρτηση Maven, εδώ είναι το γρήγορο απόσπασμα: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Τώρα, ας βουτήξουμε. + +--- + +## Step 1: Create Rectangle Shape in a Word Document + +Το πρώτο που χρειάζεται είναι ένα κενό έγγραφο και ένας `DocumentBuilder`. Σκεφτείτε τον builder ως ένα στυλό που γράφει στο έγγραφο. Μόλις το έχουμε, μπορούμε να **create rectangle shape** με μία μόνο κλήση μεθόδου. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Why this matters:** Η μέθοδος `insertShape` δεν δημιουργεί μόνο τη γεωμετρία αλλά προσθέτει επίσης το σχήμα στη εσωτερική συλλογή του εγγράφου, ώστε να μπορείτε αμέσως να αρχίσετε να το μορφοποιείτε. + +--- + +## Step 2: Apply Shadow Effect to the Shape + +Τώρα που το ορθογώνιο βρίσκεται στη σελίδα, θα **apply shadow effect**. Οι σκιές δίνουν βάθος, κάνοντας το σχήμα να φαίνεται σαν να αιωρείται πάνω από τη σελίδα—μια διακριτική βελτίωση UI που μπορεί να ενισχύσει την αναγνωσιμότητα σε αναφορές. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro tip:** Ένα blur των `5.0` φαίνεται φυσικό για τα περισσότερα έγγραφα που προβάλλονται σε οθόνη. Αν εκτυπώνετε, ίσως θέλετε μια ελαφρώς χαμηλότερη τιμή ώστε να αποφύγετε την ασαφή εμφάνιση. + +--- + +## Step 3: Set Shadow Distance – Fine‑Tuning Placement + +Οι σκιές δεν αφορούν μόνο το blur· χρειάζεται επίσης το σωστό offset. Εδώ **set shadow distance**. Μια απόσταση `7.0` points δημιουργεί ένα μέτριο offset που είναι εμφανές αλλά όχι υπερβολικό. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **What if you need a bigger offset?** Αυξήστε την τιμή· μειώστε την για πιο στενό αποτέλεσμα. Θυμηθείτε, η απόσταση λειτουργεί μαζί με τη γωνία για να τοποθετήσει σωστά τη σκιά. + +--- + +## Step 4: Save the Document – Persist Your Work + +Τέλος, γράφουμε το έγγραφο στο δίσκο. Αλλάξτε τη διαδρομή στο σημείο που θέλετε να αποθηκευτεί το αρχείο. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Η εκτέλεση της κλάσης δημιουργεί ένα αρχείο `shadow.docx` που, όταν ανοίξει στο Microsoft Word ή στο LibreOffice, εμφανίζει ένα κυανό ορθογώνιο με μια απαλή γκρι σκιά κεκλιμένη κατά 45° και offset κατά 7 points. + +--- + +## Full Working Example + +Παρακάτω είναι ο πλήρης, έτοιμος για αντιγραφή‑και‑επικόλληση κώδικας. Περιλαμβάνει όλες τις εισαγωγές, σχόλια και την τελική κλήση `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Expected output:** Ανοίξτε το `shadow.docx` → θα δείτε ένα κυανό ορθογώνιο κεντραρισμένο στην πρώτη σελίδα, ρίχνοντας μια διακριτική γκρι σκιά ελαφρώς μετατοπισμένη προς τα κάτω‑δεξιά. Το blur και η διαφάνεια της σκιάς το κάνουν να μοιάζει με φυσικό φωτισμό. + +--- + +## Common Questions & Edge Cases + +### “Can I use a different shape?” + +Απολύτως. Αντικαταστήστε το `ShapeType.RECTANGLE` με `ShapeType.OVAL`, `ShapeType.LINE` ή οποιοδήποτε άλλο υποστηριζόμενο enum. Ο υπόλοιπος κώδικας σκιάς παραμένει ίδιος. + +### “What if I need multiple shadows?” + +Το Aspose.Words υποστηρίζει μόνο μία σκιά ανά σχήμα. Για να προσομοιώσετε πολλαπλές σκιές, διπλασιάστε το σχήμα, μετατοπίστε κάθε αντίγραφο και ρυθμίστε τη διαφάνεια. + +### “Is the shadow visible in LibreOffice?” + +Ναι—το Aspose.Words γράφει τυπικό OOXML, το οποίο το LibreOffice ερμηνεύει σωστά. Η σκιά μπορεί να φαίνεται ελαφρώς διαφορετική λόγω των μηχανών απόδοσης, αλλά το εφέ παραμένει. + +### “How do I change the shadow color to match my brand?” + +Απλώς αντικαταστήστε το `java.awt.Color.GRAY` με οποιοδήποτε `java.awt.Color` προτιμάτε, π.χ. `new java.awt.Color(0, 120, 215)` για ένα εταιρικό μπλε. + +--- + +## Image Illustration + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** εικονογράφηση που δείχνει ένα κυανό ορθογώνιο με γκρι σκιά σε έγγραφο Word. + +--- + +## Recap & Next Steps + +Καλύψαμε πώς να **create rectangle shape**, **apply shadow effect**, **add shape shadow**, και **set shadow distance** χρησιμοποιώντας το Aspose.Words for Java. Ο κώδικας είναι αυτόνομος, τρέχει σε οποιοδήποτε σύγχρονο JDK και παράγει ένα επαγγελματικό αρχείο `.docx` έτοιμο για διανομή. + +Θέλετε να προχωρήσετε παραπέρα; Δοκιμάστε: + +- Προσθήκη κειμένου μέσα στο ορθογώνιο με `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Δημιουργία πίνακα σχημάτων για την κατασκευή διαγράμματος. +- Εξαγωγή του εγγράφου σε PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Κάθε μία από αυτές τις ενέργειες βασίζεται στα ίδια θεμέλια που μόλις εξερευνήσαμε, ώστε να αισθάνεστε άνετα να επεκτείνετε το παράδειγμα. + +--- + +## Final Thoughts + +Η εξοικείωση με εργασίες **create word document java** όπως η δημιουργία σχημάτων και η εφαρμογή σκιών σας δίνει τεράστια προβάδισμα όταν αυτοματοποιείτε αναφορές, συμβόλαια ή διαφημιστικό υλικό. Η προσέγγιση που παρουσιάστηκε εδώ είναι καθαρή, συντηρήσιμη και—το πιο σημαντικό—εύκολη στην προσαρμογή για οποιοδήποτε στυλ θέλετε. + +Δοκιμάστε τον κώδικα, πειραματιστείτε με το blur, τη γωνία και την απόσταση, και παρακολουθήστε τα έγγραφά σας να μετατρέπονται από απλά σε εντυπωσιακά. Αν αντιμετωπίσετε κάποιο πρόβλημα, αφήστε ένα σχόλιο παρακάτω· θα χαρώ να βοηθήσω. + +Happy coding! + +## Related Tutorials + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/hindi/java/document-conversion-and-export/_index.md index 36f51686b5..b5a88a9057 100644 --- a/words/hindi/java/document-conversion-and-export/_index.md +++ b/words/hindi/java/document-conversion-and-export/_index.md @@ -34,7 +34,7 @@ weight: 22 - **सर्वव्यापी फ़ॉर्मेट सपोर्ट** – DOCX, PDF, ODT से लेकर HTML तक। - **उच्च‑गुणवत्ता रूपांतरण** – लेआउट, फ़ॉन्ट और ग्राफ़िक्स को बरकरार रखता है। - **बिल्ट‑इन बारकोड और चार्ट जेनरेशन** – दस्तावेज़ ऑटोमेशन को सरल बनाता है। -- **शेप्स, टेबल्स और वॉटरमार्क के लिए मजबूत API** – सभी एक ही लाइब्रेरी में। +- **शेप्स, टेबल्स और वॉटरमार्क के लिए मजबूत API** – सभी एक ही लाइब्रेरी में हैं। ## पूर्वापेक्षाएँ - Java 8 या उससे ऊपर (Java 17 अनुशंसित)। @@ -86,16 +86,29 @@ Aspose.Words for Java का उपयोग करके DOCX फ़ाइल ### [Aspose.Words for Java में टेबल्स और टेबल स्टाइल्स को फ़ॉर्मेट करना](./formatting-tables-and-table-styles/) Aspose.Words for Java में टेबल्स को फ़ॉर्मेट करना और टेबल स्टाइल्स लागू करना सीखें। प्रभावी टेबल फ़ॉर्मेटिंग के लिए स्रोत कोड के साथ चरण‑दर‑स्टेप गाइड। Aspose.Words के साथ अपने दस्तावेज़ लेआउट को बेहतर बनाएं। +### [Aspose.Words for Java में Word को Markdown के रूप में सहेजें – Math को LaTeX में निर्यात करें](./save-word-as-markdown-export-math-to-latex-with-java/) +Aspose.Words for Java का उपयोग करके Word दस्तावेज़ को Markdown में बदलें और गणितीय समीकरणों को LaTeX स्वरूप में निर्यात करें। + ### [docx को markdown में बदलें – Aspose.Words के साथ गणितीय समीकरणों को LaTeX में निर्यात करें](./convert-docx-to-markdown-export-math-equations-to-latex-with/) ### [दस्तावेज़ को TXT के रूप में सहेजें – Word गणित निर्यात के लिए त्वरित गाइड](./save-document-as-txt-quick-guide-to-exporting-word-math/) Aspose.Words for Java का उपयोग करके Word दस्तावेज़ को TXT फ़ाइल में बदलें और गणितीय समीकरणों को निर्यात करने की प्रक्रिया सीखें। -### [DOCX को मार्कडाउन में बदलते समय छवियों को एम्बेड कैसे करें](./how-to-embed-images-in-markdown-when-converting-docx/) -DOCX को मार्कडाउन में बदलते समय छवियों को सही तरीके से एम्बेड करने की चरण‑दर‑स्टेप गाइड। +### [Java के साथ docx को txt में निर्यात – पूर्ण प्रोग्रामिंग गाइड](./export-docx-to-txt-with-java-complete-programming-guide/) +Aspose.Words for Java का उपयोग करके docx फ़ाइल को txt में बदलने की पूरी प्रक्रिया, कोड उदाहरण सहित। + +### [DOCX को markdown में बदलते समय छवियों को एम्बेड कैसे करें](./how-to-embed-images-in-markdown-when-converting-docx/) +DOCX को markdown में बदलते समय छवियों को सही तरीके से एम्बेड करने की चरण‑दर‑स्टेप गाइड। + +### [DOCX को मार्कडाउन में बदलते समय छवियों को Base64 के रूप में एम्बेड करें](./embed-images-as-base64-when-converting-docx-to-markdown/) +DOCX को markdown में परिवर्तित करते समय छवियों को Base64 एन्कोडेड रूप में एम्बेड करने की चरण‑दर‑स्टेप गाइड। ### [DOCX से एक्सेसिबल PDF बनाना – पूर्ण गाइड](./create-accessible-pdf-from-docx-complete-guide/) -DOCX फ़ाइल को एक्सेसिबल PDF में बदलने की पूरी प्रक्रिया, टैग, संरचना और अनुपालन सेटिंग्स के साथ। + +### [Aspose.Words for Java में एक्सेसिबल PDF बनाना – पूर्ण टैगिंग गाइड](./create-accessible-pdf-in-java-full-tagging-guide/) +Aspose.Words for Java का उपयोग करके एक्सेसिबल PDF बनाने के लिए टैगिंग चरण‑दर‑स्टेप गाइड। + +### [Aspose.Words Java के साथ दस्तावेज़ को PDF के रूप में सहेजें – पूर्ण एक्सेसिबिलिटी गाइड](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) ## अक्सर पूछे जाने वाले प्रश्न diff --git a/words/hindi/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/hindi/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..39a61913b9 --- /dev/null +++ b/words/hindi/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,226 @@ +--- +category: general +date: 2026-05-26 +description: जावा में चरण‑दर‑चरण कोड के साथ सुलभ PDF बनाएं। जानें कि कैसे PDF को एक्सेसिबिलिटी + के लिए टैग किया जाए और PdfSaveOptions का उपयोग करके PDF टैगिंग सक्षम करें। +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: hi +og_description: जावा में चरण‑दर‑चरण कोड के साथ सुलभ PDF बनाएं। जानें कि कैसे PDF को + एक्सेसेबिलिटी के लिए टैग किया जाए और PdfSaveOptions का उपयोग करके PDF टैगिंग सक्षम + की जाए। +og_title: जावा में एक्सेसिबल PDF बनाएं – पूर्ण टैगिंग गाइड +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: जावा में सुलभ पीडीएफ बनाएं – पूर्ण टैगिंग गाइड +url: /hi/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# जावा में एक्सेसिबल PDF बनाएं – पूर्ण टैगिंग गाइड + +क्या आपने कभी सोचा है कि **create accessible PDF** फ़ाइलों को सीधे जावा कोड से कैसे बनाया जाए? आप अकेले नहीं हैं। कई डेवलपर्स को उन उपयोगकर्ताओं की सेवा करनी होती है जो स्क्रीन रीडर पर निर्भर होते हैं, और एक साधारण PDF और एक एक्सेसिबल PDF के बीच का अंतर बहुत बड़ा हो सकता है। इस ट्यूटोरियल में हम **how to tag PDF for accessibility** को समझेंगे, आपको **how to create tagged PDF** Aspose PDF for Java के साथ दिखाएंगे, और **add accessibility tags to PDF** के सटीक कदम बताएंगे ताकि हर रीडर को समान जानकारी मिल सके। + +हम **enable PDF tagging** की सर्वोत्तम प्रैक्टिस, सामान्य pitfalls, और एक पूर्ण, runnable उदाहरण भी कवर करेंगे जिसे आप आज ही अपने प्रोजेक्ट में डाल सकते हैं। कोई अस्पष्ट संदर्भ नहीं—सिर्फ ठोस कोड, व्याख्याएँ, और एक अंतिम फ़ाइल जिसे आप Adobe Acrobat में खोलकर टैग्स की पुष्टि कर सकते हैं। + +## आप क्या सीखेंगे + +- PDF टैगिंग और एक्सेसिबिलिटी अनुपालन के पीछे का कारण। +- पूर्वापेक्षाएँ और लाइब्रेरी सेटअप (Aspose PDF for Java 23.10 या बाद का संस्करण)। +- **create accessible PDF** को शून्य से चरण‑बद्ध तरीके से कैसे बनाएं। +- बेसिक `setTagDocumentStructure` कॉल से आगे **add accessibility tags to PDF** करने के तरीके। +- आउटपुट का परीक्षण करने और सामान्य समस्याओं को हल करने के टिप्स। + +इस गाइड के अंत तक आप ऐसे PDFs जेनरेट कर पाएँगे जो WCAG 2.1 AA चेक पास करते हों और साथ ही प्रोफेशनल दिखें। + +--- + +## पूर्वापेक्षाएँ + +| आवश्यकता | कारण | +|----------|------| +| **Java 8+** | आधुनिक भाषा सुविधाएँ और बेहतर Unicode हैंडलिंग। | +| **Aspose PDF for Java** (v23.10 या नया) | `PdfSaveOptions` क्लास और टैगिंग सपोर्ट प्रदान करता है। | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, आदि) | आसान कंपाइलेशन और डिबगिंग के लिए। | +| **Write permission** उस फ़ोल्डर में जहाँ PDF सहेजा जाएगा | `doc.save` कॉल को लिखने योग्य पाथ चाहिए। | + +यदि आपने अभी तक अपने प्रोजेक्ट में Aspose PDF नहीं जोड़ा है, तो नीचे दिया गया Maven डिपेंडेंसी अपने `pom.xml` में डालें: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** नवीनतम संस्करण का उपयोग करें; नए रिलीज़ टैगिंग की सटीकता को सुधारते हैं और भाषा‑विशिष्ट एक्सेसिबिलिटी फीचर्स जोड़ते हैं। + +--- + +## चरण 1: डॉक्यूमेंट स्केलेटन सेट अप करें + +पहले, हम एक नया `Document` ऑब्जेक्ट बनाते हैं। इसे एक खाली कैनवास समझें जो बाद में एक्सेसिबिलिटी के लिए आवश्यक टैग्स रखेगा। + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**यह क्यों महत्वपूर्ण है:** बिना किसी कंटेंट के टैग करने के लिए कुछ नहीं रहता। एक साधारण `TextFragment` जोड़ने से टैगिंग इंजन को काम करने के लिए कुछ मिलता है, और जब हम बाद में स्ट्रक्चर टैगिंग सक्षम करेंगे तो यह स्वचालित रूप से एक `

` (पैराग्राफ) टैग बनाता है। + +## चरण 2: PDF सेव ऑप्शन बनाएं (टैगिंग का कोर) + +अब हम उन ऑप्शन्स को तैयार करते हैं जो Aspose PDF को फ़ाइल के अंदर एक लॉजिकल स्ट्रक्चर ट्री एम्बेड करने के लिए बताते हैं। + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +`setTagDocumentStructure(true)` कॉल **enable PDF tagging** स्विच है। जब यह `true` होता है, लाइब्रेरी एक टैग ट्री बनाती है जो विज़ुअल लेआउट को प्रतिबिंबित करता है, जिससे PDF सहायक तकनीकों द्वारा पढ़ी जा सकती है। + +> **Note:** यह **how to create tagged pdf** का सबसे सरल तरीका है। अधिक ग्रैन्युलर कंट्रोल (जैसे भाषा सेट करना या कस्टम टैग्स) के लिए आप `pdfOptions.setTagLanguage("en-US")` और `pdfOptions.setTagStructureTreeRoot(...)` का उपयोग कर सकते हैं। + +## चरण 3: एक्सेसिबल PDF सहेजें + +अंत में, हम कॉन्फ़िगर किए गए ऑप्शन्स का उपयोग करके डॉक्यूमेंट को डिस्क पर लिखते हैं। + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +जब `doc.save` समाप्त हो जाता है, तो आपको `output` फ़ोल्डर में `accessible.pdf` मिलेगा। इसे Adobe Acrobat में खोलें और **File → Properties → Description → Tags** देखें – आपको एक भरपूर टैग ट्री दिखना चाहिए। + +## How to Tag PDF for Accessibility – Beyond the Basics + +ऊपर दिया गया तीन‑स्टेप स्निपेट पहले से ही **adds accessibility tags to PDF** करता है, लेकिन वास्तविक दुनिया के दस्तावेज़ अक्सर थोड़ा और पॉलिश चाहते हैं। यहाँ कुछ सुधार हैं जिन्हें आप जोड़ सकते हैं: + +### 1. दस्तावेज़ की भाषा सेट करें + +स्क्रीन रीडर भाषा एट्रिब्यूट का उपयोग करके टेक्स्ट को सही ढंग से उच्चारित करते हैं। + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. शीर्षक और विषय प्रदान करें + +मेटाडाटा सहायक टूल्स को फ़ाइल खोलने से पहले संदर्भ देता है। + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. इमेजेज़ को वैकल्पिक टेक्स्ट के साथ टैग करें + +यदि आप चित्र एम्बेड करते हैं, तो उन्हें `alt` विवरण चाहिए। + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. टेबल हेडर्स को मार्क करें + +टेबल्स अक्सर रीडर्स को भ्रमित करते हैं जब तक आप हेडर रो को फ़्लैग न करें। + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +ये अतिरिक्त कदम आपके PDF को केवल *तकनीकी* रूप से टैग्ड नहीं, बल्कि विविध दर्शकों के लिए वास्तव में **accessible** बनाते हैं। + +## Common Pitfalls When You Enable PDF Tagging + +| लक्षण | संभावित कारण | समाधान | +|-------|--------------|--------| +| Acrobat में टैग्स नहीं दिख रहे | `setTagDocumentStructure` को `false` रखा गया | सुनिश्चित करें कि आपने `pdfOptions.setTagDocumentStructure(true)` कॉल किया है। | +| पढ़ने का क्रम गलत | स्पष्ट टैग्स के बिना जटिल लेआउट | कस्टम क्रम परिभाषित करने के लिए `pdfOptions.setTagStructureTreeRoot(...)` का उपयोग करें। | +| इमेजेज़ को “image” के रूप में पढ़ा जाता है, बिना विवरण के | वैकल्पिक टेक्स्ट सेट नहीं किया गया | `image.getAlternativeText().setValue("...")` कॉल करें। | +| भाषा पहचानी नहीं जा रही | `setTagLanguage` छोड़ा गया या गलत लोकेल | BCP‑47 भाषा कोड प्रदान करें (`en-US`, `fr-FR`)। | + +इन मुद्दों से परिचित रहना बाद में घंटों की डिबगिंग बचा सकता है। + +## Verify the Result – What to Expect + +प्रोग्राम चलाने के बाद, `output/accessible.pdf` को Adobe Acrobat Reader में खोलें: + +1. **Tags पैनल** (`View → Show/Hide → Navigation Panes → Tags`) में `/Document → /Part → /Sect → /Para` जैसा हायरार्की दिखना चाहिए। +2. **Reading order** विज़ुअल फ्लो का पालन करना चाहिए (पहले टेक्स्ट, फिर इमेजेज़)। +3. **Screen reader** (NVDA, VoiceOver) “Hello, accessible PDF!” पढ़ेगा, न कि सिर्फ “Page 1”। + +यदि इनमें से कोई भी आइटम गायब है, तो ऊपर बताए गए चरणों—विशेषकर `setTagDocumentStructure` कॉल—को दोबारा जांचें। + +## Full Working Example (Copy‑Paste Ready) + + + +## संबंधित ट्यूटोरियल + +- [वर्ड से एक्सेसिबल PDF बनाएं – PDF/UA में परिवर्तित करें](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [DOCX से एक्सेसिबल PDF बनाएं – पूर्ण गाइड](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Aspose.Words for Java के साथ दस्तावेज़ को PDF में सहेजें](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/hindi/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..2d8e168e3e --- /dev/null +++ b/words/hindi/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java का उपयोग करके docx को markdown में बदलते समय छवियों + को base64 के रूप में एम्बेड करें। शब्द को markdown में बदलना, शब्द को markdown के + रूप में सहेजना, और छवियों को संभालना सीखें। +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: hi +og_description: Aspose.Words for Java के साथ docx को markdown में परिवर्तित करते समय + छवियों को base64 के रूप में एम्बेड करें। Word दस्तावेज़ को markdown में बदलने और + Word को markdown के रूप में सहेजने के लिए पूर्ण गाइड। +og_title: DOCX को Markdown में परिवर्तित करते समय छवियों को Base64 के रूप में एम्बेड + करें +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: DOCX को Markdown में बदलते समय छवियों को Base64 के रूप में एम्बेड करें +url: /hi/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX को Markdown में बदलते समय छवियों को Base64 के रूप में एम्बेड करें + +क्या आपने कभी सोचा है कि **छवियों को Base64 के रूप में एम्बेड** कैसे किया जाए जबकि आप **docx को markdown में बदलते** हैं? आप अकेले नहीं हैं—डेवलपर्स लगातार पूछते रहते हैं कि अलग-अलग फ़ाइलों को संभाले बिना छवियों को इनलाइन कैसे रखें। अच्छी खबर यह है कि Aspose.Words for Java इसे बहुत आसान बना देता है: आप एक Word दस्तावेज़ को Markdown में बदल सकते हैं और हर चित्र को स्वचालित रूप से Base64 स्ट्रिंग के रूप में एम्बेड कर सकते हैं। + +इस ट्यूटोरियल में हम पूरी प्रक्रिया को चरण‑दर‑चरण देखेंगे—छवियों वाली `.docx` फ़ाइल लोड करने से लेकर `MarkdownSaveOptions` कॉलबैक को कॉन्फ़िगर करने तक जो यह काम करता है, और अंत में परिणाम को साफ़ `.md` फ़ाइल के रूप में सहेजेंगे। अंत तक आप बिल्कुल जान पाएँगे कि **convert word to markdown**, **convert images to base64**, और **save word as markdown** कैसे किया जाता है बिना किसी अतिरिक्त इमेज फ़ोल्डर के। कोई बाहरी टूल नहीं, कोई मैन्युअल पोस्ट‑प्रोसेसिंग नहीं—सिर्फ शुद्ध Java कोड जिसे आप किसी भी प्रोजेक्ट में डाल सकते हैं। + +## आपको क्या चाहिए + +- **Java 17** (या कोई भी नवीनतम JDK) – कोड लैम्ब्डा सिंटैक्स का उपयोग करता है, लेकिन आप इसे पुराने संस्करणों के लिए अनुकूलित कर सकते हैं। +- **Aspose.Words for Java** लाइब्रेरी (2026 तक का नवीनतम संस्करण)। Maven डिपेंडेंसी या JAR को अपने क्लासपाथ में जोड़ें। +- एक नमूना **DOCX** फ़ाइल जिसमें कम से कम एक छवि हो। +- एक IDE या साधारण टेक्स्ट एडिटर—Visual Studio Code, IntelliJ IDEA, या यहाँ तक कि `vim` भी चलेगा। + +यदि आपके पास ये सब है, तो चलिए सीधे शुरू करते हैं। + +## चरण 1: Word दस्तावेज़ लोड करें + +पहले हम एक `Document` इंस्टेंस बनाते हैं जो स्रोत फ़ाइल की ओर इशारा करता है। यह वही कदम है चाहे आप **convert docx to markdown** कर रहे हों या सिर्फ फ़ाइल को अन्य उद्देश्यों के लिए पढ़ रहे हों। + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **यह क्यों महत्वपूर्ण है:** `Document` ऑब्जेक्ट हर Aspose ऑपरेशन का प्रवेश बिंदु है। यह पूरे Word संरचना—छवियों, तालिकाओं और शैलियों सहित—को रखता है, ताकि बाद वाला कॉलबैक प्रत्येक संसाधन की जाँच कर सके। + +## चरण 2: Create MarkdownSaveOptions and Register a Resource‑Saving Callback + +जादू `MarkdownSaveOptions` में रहता है। `IResourceSavingCallback` को संलग्न करके हम प्रत्येक बाहरी संसाधन (जैसे छवि) के लिखने के तरीके पर नियंत्रण प्राप्त करते हैं। + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: `setSaveToMemory(true)` क्यों उपयोग करें? + +जब `saveToMemory` true होता है, तो Aspose छवि बाइट्स को फ़ाइल की बजाय मेमोरी स्ट्रीम में लिखता है। Markdown एक्सपोर्टर फिर उस स्ट्रीम को Base64 स्ट्रिंग में बदल देता है और सीधे Markdown इमेज टैग में डाल देता है: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +यही **embed images as base64** का मूल है। + +## चरण 3: Save the Document as Markdown + +अब कॉलबैक स्थापित हो गया है, अंतिम कदम बस `save` को कॉल करना है। यही वह जगह है जहाँ हम वास्तव में **convert word to markdown** करते हैं और कॉलबैक की वजह से **convert images to base64** भी हो जाता है। + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **परिणाम:** `out.md` में Markdown टेक्स्ट के साथ हर छवि `data:` URI के रूप में दर्शायी गई है। डिस्क पर कोई अतिरिक्त इमेज फ़ाइल नहीं बनती, इसलिए फ़ोल्डर साफ़ रहता है। + +## चरण 4: Verify the Output and Common Pitfalls + +जनरेटेड `out.md` को किसी भी Markdown व्यूअर (VS Code, GitHub, या स्टैटिक साइट जेनरेटर) में खोलें। आपको कुछ इस तरह दिखना चाहिए: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### समस्या निवारण जाँच सूची + +| समस्या | संभावित कारण | समाधान | +|-------|--------------|-----| +| छवि टूटे लिंक के रूप में दिखती है | `setSaveToMemory` छोड़ा गया था | सुनिश्चित करें कि `args.setSaveToMemory(true);` कॉलबैक के भीतर है | +| Base64 स्ट्रिंग कट गई है | आउटपुट फ़ाइल एन्कोडिंग मेल नहीं खा रही | Markdown को UTF‑8 (Aspose का डिफ़ॉल्ट) में सहेजें | +| अप्रत्याशित फ़ाइल नाम | `setKeepResourceOriginalName(true)` | कस्टम नेमिंग लॉजिक को लागू करने के लिए इसे `false` रखें | + +## चरण 5: Advanced Variations (Optional) + +### केवल चयनित छवियों को एम्बेड करें + +यदि आप केवल कुछ छवियों को एम्बेड करना चाहते हैं (जैसे 100 KB से बड़ी), तो आकार जाँच जोड़ें: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### अलग इमेज फ़ॉर्मेट उपयोग करें + +`ResourceSavingArgs` आपको कच्चे बाइट्स देता है, इसलिए आप JPEG को PNG में पुनः‑एन्कोड कर सकते हैं—जब लक्ष्य Markdown कंज्यूमर PNG पसंद करता हो तो उपयोगी। + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +ये बदलाव दिखाते हैं कि **embed images as base64** तरीका कितना लचीला है जब आप **convert docx to markdown** करते हैं। + +## निष्कर्ष + +आपने अभी सीखा कि Aspose.Words for Java का उपयोग करके **docx को markdown में बदलते** समय **छवियों को Base64 के रूप में एम्बेड** कैसे किया जाता है। एक सरल `IResourceSavingCallback` को जोड़कर, लाइब्रेरी सभी भारी काम कर देती है: यह **convert word to markdown**, **convert images to base64**, और अंत में **save word as markdown** को एक ही `save` कॉल से पूरा करता है। + +बिना झिझक प्रयोग करें—विभिन्न इमेज‑फ़िल्टरिंग नियम आज़माएँ, HTML आउटपुट पर स्विच करें, या इस चरण को स्टैटिक‑साइट जेनरेटर के साथ जोड़ें। वही पैटर्न अन्य फ़ॉर्मेट (HTML, EPUB) के लिए भी काम करता है, इसलिए आप जहाँ भी इनलाइन रिसोर्स की ज़रूरत हो, कॉलबैक को पुन: उपयोग कर सकते हैं। + +**अगले कदम:** +- HTML‑with‑Base64 छवियों के लिए `HtmlSaveOptions` का अन्वेषण करें। +- इसे CI पाइपलाइन के साथ जोड़ें ताकि दस्तावेज़ निर्माण स्वचालित हो सके। +- यदि आपको रूपांतरण प्रक्रिया पर और अधिक सूक्ष्म नियंत्रण चाहिए तो Aspose के `DocumentVisitor` में गहराई से देखें। + +कोडिंग का आनंद लें, और अपने साफ़, स्व‑समाहित Markdown फ़ाइलों का मज़ा लें! + +## संबंधित ट्यूटोरियल्स + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/hindi/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..df742988c6 --- /dev/null +++ b/words/hindi/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Java और Aspose.Words का उपयोग करके docx को txt में निर्यात करें। जानें + कि कैसे docx को टेक्स्ट में बदलें, Unicode को संरक्षित रखें, और कुछ ही चरणों में + वर्ड को txt के रूप में निर्यात करें। +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: hi +og_description: जावा में docx को txt में निर्यात करें। यह ट्यूटोरियल दिखाता है कि + कैसे docx को टेक्स्ट में बदलें, साधारण टेक्स्ट यूनिकोड को बनाए रखें, और शब्द को + प्रभावी ढंग से txt के रूप में निर्यात करें। +og_title: Java के साथ docx को txt में निर्यात करें – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Java के साथ docx को txt में निर्यात करें – पूर्ण प्रोग्रामिंग गाइड +url: /hi/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java के साथ docx को txt में निर्यात – पूर्ण प्रोग्रामिंग गाइड + +क्या आपको कभी **export docx to txt** करने की ज़रूरत पड़ी है लेकिन विशेष अक्षरों के खो जाने की चिंता रही है? आप अकेले नहीं हैं। जब आप Word दस्तावेज़ों को plain‑text फ़ाइलों में बदलते हैं, तो Unicode प्रतीक, तालिकाएँ, और यहाँ तक कि साधारण फ़ॉर्मेटिंग भी जादू की तरह गायब हो सकती हैं। + +इस गाइड में हम Aspose.Words for Java का उपयोग करके **export docx to txt** करने का भरोसेमंद तरीका दिखाएंगे, जिससे हर Unicode glyph बना रहे और तालिका लेआउट पढ़ने योग्य रहे। अंत तक आप यह भी जानेंगे कि **convert docx to text**, **convert word to text**, और **export word as txt** कैसे बिना किसी समस्या के किया जाए। + +## इस ट्यूटोरियल में क्या कवर किया गया है + +* Java प्रोजेक्ट में Aspose.Words सेटअप करना +* DOCX फ़ाइल लोड करना और plain‑text आउटपुट के लिए तैयार करना +* `TxtSaveOptions` के माध्यम से **plain text unicode** सपोर्ट कॉन्फ़िगर करना +* परिणामस्वरूप `.txt` फ़ाइल में तालिकाओं को पठनीय रखने के वैकल्पिक ट्रिक्स +* फ़ाइल सहेजना और आउटपुट की जाँच करना + +कोई बाहरी स्क्रिप्ट नहीं, कोई रहस्यमय कमांड‑लाइन टूल नहीं—सिर्फ शुद्ध Java कोड जिसे आप किसी भी Maven या Gradle प्रोजेक्ट में डाल सकते हैं। + +> **क्यों ध्यान दें?** Plain‑text फ़ाइलें हल्की, वर्ज़न‑कंट्रोल‑फ़्रेंडली, और सर्च‑इंडेक्सिंग या डाउनस्ट्रीम प्रोसेसिंग पाइपलाइन के लिए एकदम उपयुक्त होती हैं। अगर आपने कभी `cat` करके Word फ़ाइल को पढ़ने की कोशिश की और बकवास मिला, तो यह ट्यूटोरियल वही समस्या हल करता है। + +--- + +## Export docx to txt – अवलोकन + +कोड में डुबकी लगाने से पहले शब्दावली साफ़ कर लेते हैं। **Export docx to txt** का मतलब है Microsoft Word `.docx` पैकेज को लेकर उसका टेक्स्टुअल कंटेंट एक साधारण `.txt` फ़ाइल में लिखना। PDF रूपांतरण के विपरीत, टेक्स्ट निर्यात स्टाइलिंग को हटा देता है लेकिन लाइन ब्रेक, पैराग्राफ मार्कर, और—यदि सही तरीके से कॉन्फ़िगर किया जाए—Unicode अक्षर जैसे इमोजी, एक्सेंटेड लेटर, या एशियाई स्क्रिप्ट्स को रख सकता है। + +Aspose.Words इसे आसान बनाता है क्योंकि यह Word फ़ाइल फ़ॉर्मेट को एब्स्ट्रैक्ट करता है और `TxtSaveOptions` क्लास प्रदान करता है जहाँ आप एन्कोडिंग, तालिका हैंडलिंग, आदि निर्धारित कर सकते हैं। + +### पूर्वापेक्षाएँ + +* Java 11 या नया (API Java 8+ के साथ काम करता है, लेकिन हम हालिया JDK मानेंगे) +* Aspose.Words for Java JAR (Maven Central से उपलब्ध) +* एक नमूना `unicode.docx` फ़ाइल जिसमें विविध Unicode अक्षर हों—जैसे “こんにちは”, “😊”, और एक साधारण तालिका + +अगर आपके पास ये सब है, तो चलिए शुरू करते हैं। + +--- + +## चरण 1: DOCX फ़ाइल लोड करें (Convert docx to text) + +पहला काम है स्रोत दस्तावेज़ को मेमोरी में पढ़ना। यहीं से **convert docx to text** प्रक्रिया आधिकारिक रूप से शुरू होती है। + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*यह क्यों महत्वपूर्ण है:* `Document` Aspose.Words का Word फ़ाइल प्रतिनिधित्व है। इसे लोड करके आप सभी पैराग्राफ़, तालिकाएँ, और यहाँ तक कि छिपे हुए एलिमेंट्स तक पहुँच प्राप्त करते हैं। यदि फ़ाइल नहीं मिलती, तो Aspose स्पष्ट `FileNotFoundException` फेंकेगा, जिससे आपको तुरंत पता चल जाएगा क्या गड़बड़ है। + +--- + +## चरण 2: Unicode के लिए TxtSaveOptions कॉन्फ़िगर करें (Plain text unicode) + +Plain‑text फ़ाइलें केवल बाइट्स की स्ट्रीम होती हैं, इसलिए आपको Java को बताना होगा कि कौन सा कैरेक्टर सेट उपयोग करना है। UTF‑8 **plain text unicode** का डि‑फैक्टो मानक है क्योंकि यह हर Unicode कोड पॉइंट को एन्कोड कर सकता है। + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **प्रो टिप:** यदि आप `setEncoding` कॉल को छोड़ देते हैं, तो Aspose प्लेटफ़ॉर्म की डिफ़ॉल्ट charset का उपयोग करता है, जो कई Windows मशीनों पर Windows‑1252 होता है। यह डिफ़ॉल्ट “ß” या “—” जैसे अक्षरों को चुपचाप हटा देगा। + +--- + +## चरण 3: तालिका लेआउट सुरक्षित रखें (वैकल्पिक, लेकिन पठनीयता के लिए उपयोगी) + +जब आप **export word as txt** करते हैं, तो तालिकाएँ आमतौर पर एक ही पंक्ति में फ्लैट हो जाती हैं, जिससे पढ़ना मुश्किल हो जाता है। Aspose.Words एक सरल फ़्लैग प्रदान करता है जिससे दृश्य संरचना बनी रहती है। + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*इसे कब उपयोग करें:* यदि आपके स्रोत DOCX में इनवॉइस, शेड्यूल, या कोई ग्रिड‑जैसा डेटा है, तो `PreserveTableLayout` को सक्षम करने से टैब और लाइन ब्रेक डालकर फ़ाइल अभी भी तालिका जैसा दिखेगी। यदि आपको यह नहीं चाहिए, तो आप इस लाइन को छोड़ सकते हैं और अधिक कॉम्पैक्ट आउटपुट प्राप्त कर सकते हैं। + +--- + +## चरण 4: दस्तावेज़ को Plain‑Text के रूप में सहेजें (Export word as txt) + +अब भारी काम हो गया—सिर्फ बाइट्स को डिस्क पर लिखें। + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +प्रोग्राम चलाने पर उसी फ़ोल्डर में `plain.txt` बन जाएगा। इसे किसी भी टेक्स्ट एडिटर (Notepad++, VS Code, यहाँ तक कि टर्मिनल में `cat`) से खोलें और आप देखेंगे: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +ध्यान दें कि जापानी अभिवादन और स्माइली जीवित रहे, और तालिका ने `PreserveTableLayout` की वजह से अपने कॉलम बनाए रखे। यही साफ़ **export docx to txt** का सार है। + +--- + +## चरण 5: आउटपुट की जाँच करें (Convert word to text सत्यापन) + +एक त्वरित सत्यापन चुपचाप डेटा हानि को रोकता है। यहाँ कुछ तरीके हैं जिससे आप यह सुनिश्चित कर सकें कि आप सही ढंग से **convert word to text** कर रहे हैं: + +1. **Checksum तुलना** – `.txt` फ़ाइल का SHA‑256 हैश राउंड‑ट्रिप परिवर्तन (txt → docx → txt) से पहले और बाद में निकालें ताकि स्थिरता सुनिश्चित हो। +2. **Unicode मार्कर खोजें** – `grep` या IDE की फ़ाइल‑में‑खोज सुविधा से “😊” जैसे अक्षर खोजें। +3. **कई एडिटर में खोलें** – कुछ पुराने Windows Notepad संस्करण UTF‑8 बिना BOM के गलत पढ़ते हैं; VS Code में फ़ाइल खोलने से एन्कोडिंग सही है या नहीं पता चलता है। + +यदि इनमें से कोई भी जाँच विफल हो, तो दोबारा जांचें कि `saveOptions.setEncoding(StandardCharsets.UTF_8)` मौजूद है और आपका स्रोत DOCX वास्तव में Unicode टेक्स्ट रखता है। + +--- + +## सामान्य समस्याएँ और उनके समाधान + +| समस्या | क्यों होता है | समाधान | +|--------|--------------|--------| +| **अक्षर गायब** | डिफ़ॉल्ट सिस्टम charset (जैसे Windows‑1252) non‑ASCII glyphs को हटा देता है। | `saveOptions.setEncoding` के माध्यम से स्पष्ट रूप से UTF‑8 सेट करें। | +| **तालिकाएँ एक पंक्ति में बदल जाती हैं** | `PreserveTableLayout` डिफ़ॉल्ट `false` पर रहता है। | `saveOptions.setPreserveTableLayout(true)` कॉल करें। | +| **फ़ाइल नहीं मिली** | गलत पाथ या पढ़ने की अनुमति नहीं है। | पूर्ण पाथ उपयोग करें या `Paths.get(...)` के साथ उचित अपवाद हैंडलिंग करें। | +| **बड़ी दस्तावेज़ों पर प्रदर्शन धीमा** | पूरी दस्तावेज़ को मेमोरी में लोड करना। | यदि केवल विशिष्ट सेक्शन चाहिए तो `DocumentBuilder` से चंक्स में स्ट्रीम करें। | + +--- + +## बोनस: बैच में कई DOCX फ़ाइलें निर्यात करना + +यदि आपको पूरे फ़ोल्डर के लिए **convert docx to text** करना है, तो लॉजिक को लूप में रखें: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +यह स्निपेट डायरेक्टरी में प्रत्येक फ़ाइल के लिए **export docx to txt** करता है, जिससे आपके घंटे भर के मैनुअल काम बच जाते हैं। + +--- + +## निष्कर्ष + +आपने अभी Java के साथ **export docx to txt** करना सीख लिया है, जिससे हर Unicode अक्षर बना रहे, तालिकाएँ पठनीय रहें, और पूरी प्रक्रिया दोहराने योग्य हो। `TxtSaveOptions` को UTF‑8 के लिए कॉन्फ़िगर करके और वैकल्पिक रूप से तालिका लेआउट सुरक्षित रखकर आप भरोसेमंद रूप से **convert docx to text**, **convert word to text**, और **export word as txt** किसी भी डाउनस्ट्रीम वर्कफ़्लो के लिए कर सकते हैं। + +अगली चुनौती के लिए तैयार हैं? markdown (`.md`) या CSV जैसे अन्य plain‑text फ़ॉर्मेट में निर्यात करने की कोशिश करें, या Aspose.Words की PDF रूपांतरण क्षमताओं को एक्सप्लोर करें। वही सिद्धांत—स्पष्ट एन्कोडिंग, लेआउट संरक्षण, और पूरी जाँच—सभी मामलों में लागू होते हैं। + +कोडिंग का आनंद लें, और आपकी टेक्स्ट फ़ाइलें हमेशा Unicode‑समृद्ध रहें! + +--- + +![docx को txt में निर्यात पाइपलाइन दर्शाता आरेख](/images/export-docx-to-txt-pipeline.png){alt="docx को txt में निर्यात पाइपलाइन आरेख"} + +## संबंधित ट्यूटोरियल + +- [Docx को Txt में बदलें](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Java में DOCX को PDF में बदलें](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [docx को markdown में बदलें – Aspose.Words के साथ गणितीय समीकरणों को LaTeX में निर्यात करें](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/hindi/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..02b01a6fad --- /dev/null +++ b/words/hindi/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words Java का उपयोग करके दस्तावेज़ को PDF के रूप में सहेजें और + PDF में एक्सेसिबिलिटी जोड़ें। docx को PDF में बदलना सीखें, क्षैतिज रूल्स को टैग + करें, और PDF/UA‑2 अनुपालन सुनिश्चित करें। +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: hi +og_description: Aspose.Words Java का उपयोग करके दस्तावेज़ को PDF के रूप में सहेजें + और PDF में एक्सेसिबिलिटी जोड़ें। DOCX को PDF में बदलने और PDF/UA‑2 अनुपालन के लिए + क्षैतिज रूल्स को टैग करने की चरण‑दर‑चरण गाइड। +og_title: Aspose.Words Java के साथ दस्तावेज़ को PDF के रूप में सहेजें – एक्सेसिबिलिटी + आसान बन गई +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Aspose.Words Java के साथ दस्तावेज़ को PDF के रूप में सहेजें – पूर्ण पहुँच मार्गदर्शिका +url: /hi/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words Java के साथ दस्तावेज़ को PDF के रूप में सहेजें – पूर्ण पहुँच मार्गदर्शिका + +क्या आपने कभी सोचा है कि **दस्तावेज़ को PDF के रूप में सहेजें** जबकि स्क्रीन रीडर के लिए इसे सुलभ बनाए रखें? आप अकेले नहीं हैं। कई डेवलपर्स को *docx को pdf में बदलना* है और साथ ही PDF/UA‑2 मानकों को पूरा करना है, विशेष रूप से जब स्रोत में क्षैतिज रेखाएँ हों जिन्हें सही ढंग से टैग किया जाना चाहिए। इस ट्यूटोरियल में हम **Aspose.Words for Java** का उपयोग करके **दस्तावेज़ को PDF के रूप में सहेजें**, स्वचालित रूप से **PDF में पहुँच जोड़ें**, और सुनिश्चित करेंगे कि प्रत्येक क्षैतिज रेखा **आर्टिफैक्ट** के रूप में टैग हो। + +हम एक साफ़ Java प्रोजेक्ट से शुरू करेंगे, एक ऐसा DOCX लोड करेंगे जिसमें पहले से ही क्षैतिज रेखाएँ हों, PDF/UA‑2 अनुपालन के लिए PDF सहेजने के विकल्प कॉन्फ़िगर करेंगे, और अंत में पूरी तरह सुलभ PDF लिखेंगे। अंत तक, आप **दस्तावेज़ को pdf के रूप में सहेजें** इस भरोसे के साथ कर पाएँगे कि यह पहुँच जांच पास करता है। + +## आवश्यकताएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास हैं: + +- Java 8 या नया (ट्यूटोरियल JDK 17 पर परीक्षण किया गया था)। +- Maven 3.6+ (या यदि आप पसंद करें तो Gradle) निर्भरताओं को प्रबंधित करने के लिए। +- एक वैध Aspose.Words for Java लाइसेंस (फ्री ट्रायल काम करता है, लेकिन लाइसेंस मूल्यांकन वॉटरमार्क हटाता है)। +- एक DOCX फ़ाइल (`input.docx`) जिसमें कम से कम एक क्षैतिज रेखा हो—वर्ड में आप जो साधारण लाइन सेपरेटर डालते हैं, वही। + +> **Pro tip:** यदि आपके पास DOCX नहीं है, तो बस एक नया Word दस्तावेज़ बनाएँ, कुछ पैराग्राफ टाइप करें, *Insert → Horizontal Line* डालें, `input.docx` के रूप में सहेजें, और इसे अपनी पसंदीदा फ़ोल्डर में रखें। + +## चरण 1: Maven प्रोजेक्ट सेट अप करें + +पहले, एक नया Maven प्रोजेक्ट बनाएँ (या मौजूदा में जोड़ें)। `pom.xml` में Aspose.Words निर्भरता होनी चाहिए: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** `aspose-words` आर्टिफैक्ट जोड़ना *docx को pdf में बदलना* का पहला कदम है। इसके बिना कंपाइलर `Document`, `PdfSaveOptions` और अन्य महत्वपूर्ण क्लासेज़ को नहीं पहचान पाएगा। + +## चरण 2: क्षैतिज रेखाओं वाले स्रोत DOCX को लोड करें + +अब हम एक छोटा Java क्लास लिखेंगे जो DOCX को लोड करता है। यहाँ से **क्षैतिज रेखाओं को टैग करना** शुरू होता है—Aspose.Words स्वचालित रूप से क्षैतिज रेखा को बॉर्डर वाले पैराग्राफ के रूप में मानता है, लेकिन हम PDF/UA इंजन को टैगिंग संभालने देंगे। + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +ध्यान दें कि हमने अभी तक कुछ सहेजा नहीं है—हम केवल DOCX **लोड** कर रहे हैं, जो *docx को pdf में बदलना* का पहला आधा भाग है। `Document` ऑब्जेक्ट अब सभी Word सामग्री रखता है, जिसमें आपने डाली हुई क्षैतिज रेखाएँ भी शामिल हैं। + +## चरण 3: PDF/UA‑2 अनुपालन के लिए PDF सहेजने के विकल्प कॉन्फ़िगर करें + +**PDF में पहुँच जोड़ने** का जादू `PdfSaveOptions` में है। अनुपालन स्तर को `PDF_UA_2` सेट करके, Aspose.Words करेगा: + +1. संरचनात्मक तत्वों (हेडिंग, टेबल आदि) को टैग करना। +2. सजावटी तत्वों—जैसे क्षैतिज रेखाएँ—को *आर्टिफैक्ट* के रूप में चिह्नित करना, ताकि स्क्रीन रीडर उन्हें अनदेखा करें। +3. आवश्यक PDF/UA मेटाडेटा सम्मिलित करना। + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** `PDF_UA_2` के बिना उत्पन्न PDF पढ़ा जा सकता है, लेकिन स्वचालित पहुँच वैलिडेटर पास नहीं करेगा। **क्षैतिज रेखाओं को टैग करना** की आवश्यकता स्वचालित रूप से पूरी हो जाती है क्योंकि PDF/UA अनुपालन फ़्लैग ऑन होने पर उन्हें *आर्टिफैक्ट* माना जाता है। + +## चरण 4: दस्तावेज़ को PDF के रूप में सहेजें + +अब हम अंततः **दस्तावेज़ को pdf के रूप में सहेजें**। यह एक ही पंक्ति भारी काम करती है—DOCX को बदलना, पहुँच टैग लागू करना, और फ़ाइल को डिस्क पर लिखना। + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +क्लास चलाएँ (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) और आपको एक पुष्टि संदेश दिखाई देगा। उत्पन्न `ua_compliant.pdf` को Adobe Acrobat में खोलें और **File → Properties → Description → PDF/A, PDF/UA** देखें—आपको “PDF/UA‑2” सूचीबद्ध दिखना चाहिए। + +### अपेक्षित आउटपुट + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +PDF खोलें, और आप देखेंगे: + +- दस्तावेज़ का टेक्स्ट चयन योग्य और खोज योग्य है। +- क्षैतिज रेखा स्क्रीन रीडर के लिए अदृश्य है (आर्टिफैक्ट के रूप में ट्रीटेड)। +- PDF बुनियादी PDF/UA वैलिडेशन टूल्स (जैसे PAC 3) पास करता है। + +## चरण 5: पहुँच की जाँच – त्वरित चेकलिस्ट + +हालाँकि Aspose.Words अधिकांश काम करता है, आउटपुट की जाँच करना अच्छा अभ्यास है। + +| जाँच | कैसे सत्यापित करें | +|-------|----------------| +| **दस्तावेज़ शीर्षक** | Acrobat → File → Properties → Title फ़ील्ड (कोई `pdfOptions.setTitle` के साथ मेल होना चाहिए) | +| **आर्टिफैक्ट टैगिंग** | Acrobat के “Reading Order” टूल का उपयोग करें। क्षैतिज रेखाएँ *Artifact* (ग्रे) के रूप में दिखनी चाहिए | +| **तार्किक पढ़ने का क्रम** | Acrobat में “Accessibility Checker” चलाएँ; कोई संरचनात्मक त्रुटि नहीं होनी चाहिए | +| **टैग्ड PDF** | Acrobat में “Tags” पैनल देखें – आपको एक पदानुक्रम (Document → Section → Paragraph आदि) दिखना चाहिए | +| **PDF/UA अनुपालन** | Acrobat “Standards” टैब में “PDF/UA‑2” दिखेगा | + +यदि इनमें से कोई भी जाँच विफल होती है, तो सुनिश्चित करें कि आपने नवीनतम Aspose.Words संस्करण उपयोग किया है और `setCompliance(PdfCompliance.PDF_UA_2)` सही ढंग से लागू किया है। + +## सामान्य समस्याएँ एवं समाधान + +1. **लाइसेंस नहीं है** – ट्रायल संस्करण वॉटरमार्क जोड़ता है जो PDF/UA वैलिडेशन को तोड़ सकता है। `main` में जल्दी लाइसेंस लागू करें: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **गलत इनपुट पाथ** – `FileNotFoundException` परिवर्तन को रोक देगा। पूर्ण पाथ उपयोग करें या DOCX को प्रोजेक्ट रूट में रखें और `new File("input.docx").getAbsolutePath()` से संदर्भित करें। +3. **पुराना Aspose संस्करण** – PDF/UA समर्थन संस्करण 22.9 में जोड़ा गया था। नवीनतम रिलीज़ में अपग्रेड करें ताकि फीचर मिस न हों। +4. **क्षैतिज रेखा को इमेज के रूप में डालना** – यदि आपने लाइन को इमेज के रूप में डाला है, तो Aspose इसे सामान्य इमेज मानता है, आर्टिफैक्ट नहीं। सही टैगिंग के लिए Word की बिल्ट‑इन *Horizontal Line* का उपयोग करें। + +## समाधान का विस्तार – यदि आपको और चाहिए तो? + +- **कस्टम टैग**: यदि आपके पास अन्य सजावटी तत्व (जैसे डेकोरेटिव आइकन) हैं, तो आप `PdfSaveOptions.setArtifactTaggingEnabled(true)` से उन्हें मैन्युअल रूप से आर्टिफैक्ट के रूप में चिह्नित कर सकते हैं। +- **एकाधिक दस्तावेज़**: DOCX फ़ाइलों के फ़ोल्डर पर लूप चलाएँ और बैच‑कन्वर्ज़न करें, प्रदर्शन के लिए वही `PdfSaveOptions` इंस्टेंस पुन: उपयोग करें। +- **भाषा टैग जोड़ना**: बहुभाषी PDFs के लिए `pdfOptions.setLanguage("en-US")` सेट करें ताकि सहायक तकनीकें सही आवाज़ चुन सकें। + +## पूर्ण कार्यशील उदाहरण (सभी कोड एक साथ) + +नीचे पूरा, चलाने योग्य Java प्रोग्राम दिया गया है। इसे अपने IDE में कॉपी‑पेस्ट करें, पाथ समायोजित करें, और रन करें। + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +इसे चलाएँ, उत्पन्न PDF खोलें, और आपके पास वितरण के लिए एक साफ़, सुलभ फ़ाइल होगी। + +## निष्कर्ष + +हमने दिखाया कि कैसे **Aspose.Words for Java** के साथ **दस्तावेज़ को pdf के रूप में सहेजें** और स्वचालित रूप से **pdf में पहुँच जोड़ें** तथा **क्षैतिज रेखाओं को आर्टिफैक्ट के रूप में टैग करें**। मुख्य बिंदु: + +- पहुँच मानकों को पूरा करने के लिए `PdfSaveOptions` के साथ `PDF_UA_2` अनुपालन उपयोग करें। +- DOCX लोड करके `doc.save(..., pdfOptions)` कॉल करना ही **docx को pdf में बदलना** के लिए पर्याप्त है। +- क्षैतिज रेखाएँ आपके लिए संभाली जाती हैं—कोई अतिरिक्त कोड नहीं, जिससे **क्षैतिज रेखाओं को टैग करना** की आवश्यकता पूरी होती है। +- यह तरीका पूरी तरह **aspose convert docx pdf** अनुरूप है, नवीनतम लाइब्रेरी संस्करण के साथ काम करता है, और वैलिडेशन‑रेडी PDF उत्पन्न करता है। + +अगली चुनौती के लिए तैयार हैं? कस्टम मेटाडेटा जोड़ें, फ़ॉन्ट एम्बेड करें, या पूरे DOCX फ़ोल्डर को बैच‑प्रोसेस करें। इन सभी विस्तारों का आधार वही है जो हमने यहाँ स्थापित किया है। + +PDF/UA अनुपालन, लाइसेंसिंग, या अन्य Word तत्वों के बारे में प्रश्न हैं? टिप्पणी छोड़ें या Aspose की आधिकारिक दस्तावेज़ीकरण देखें—उदाहरणों की भरमार है। कोडिंग का आनंद लें, और सुलभ PDFs बनाते रहें! + +![Aspose.Words Java का उपयोग करके दस्तावेज़ को PDF के रूप में सहेजें – सुलभ PDF उदाहरण](placeholder-image.png "Aspose.Words Java का उपयोग करके दस्तावेज़ को PDF के रूप में सहेजें – सुलभ PDF उदाहरण") + + +## संबंधित ट्यूटोरियल + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/hindi/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..20dca352bf --- /dev/null +++ b/words/hindi/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Word को markdown के रूप में सहेजें और Aspose.Words for Java का उपयोग + करके गणितीय समीकरणों को LaTeX में निर्यात करने का तरीका जानें। केवल कुछ लाइनों में + Word समीकरणों को LaTeX में बदलें। +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: hi +og_description: Word को markdown के रूप में सहेजें और Aspose.Words for Java का उपयोग + करके गणितीय समीकरणों को LaTeX में निर्यात करना सीखें। एक पूर्ण, चलाने योग्य गाइड। +og_title: शब्द को मार्कडाउन के रूप में सहेजें – जावा के साथ गणित को LaTeX में निर्यात + करें +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: वर्ड को मार्कडाउन के रूप में सहेजें – जावा के साथ गणित को LaTeX में निर्यात + करें +url: /hi/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word को markdown के रूप में सहेजें – Java के साथ Math को LaTeX में निर्यात करें + +क्या आपको कभी **save word as markdown** करने की ज़रूरत पड़ी लेकिन आपके समीकरणों के गड़बड़ हो जाने की चिंता रही? आप अकेले नहीं हैं। इस गाइड में हम बताएँगे **how to export math** को `.docx` फ़ाइल से सीधे LaTeX में कैसे निर्यात करें जबकि दस्तावेज़ का बाकी हिस्सा साफ़ Markdown बन जाए। + +हम Aspose.Words लाइब्रेरी को सेटअप करने से लेकर अंतिम `out.md` फ़ाइल की पुष्टि तक सब कुछ कवर करेंगे। अंत तक आप एक ही मेथड कॉल में **convert word equations latex** कर पाएँगे, और आप उन छोटी‑छोटी बारीकियों को समझेंगे जो रूपांतरण को विश्वसनीय बनाती हैं। + +--- + +## आपको क्या चाहिए + +- **Java 8+** – कोड किसी भी नवीनतम JDK पर चलता है। +- **Aspose.Words for Java** – चाहे Maven/Gradle डिपेंडेंसी हो या JAR, यदि आप मैनुअल सेटअप पसंद करते हैं। +- एक Word दस्तावेज़ (`math.docx`) जिसमें कम से कम एक Office Math समीकरण हो। +- एक IDE या साधारण `javac`/`java` कमांड लाइन – जैसा भी आपको सुविधाजनक लगे। + +यदि आपके पास ये पहले से हैं, तो बढ़िया। यदि नहीं, तो अगला सेक्शन दिखाएगा कि लाइब्रेरी को अपने प्रोजेक्ट में कैसे जोड़ें। + +--- + +## Word को markdown के रूप में सहेजें – चरण 1: अपने प्रोजेक्ट में Aspose.Words जोड़ें + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose परीक्षण के लिए एक मुफ्त अस्थायी लाइसेंस प्रदान करता है। `license.xml` फ़ाइल को अपने resources फ़ोल्डर में रखें और किसी भी दस्तावेज़ को लोड करने से पहले `License license = new License(); license.setLicense("license.xml");` कॉल करें। + +डिपेंडेंसी हल हो जाने के बाद, आप रूपांतरण कोड लिखने के लिए तैयार हैं। + +--- + +## Math समीकरणों को LaTeX में निर्यात कैसे करें + +`MarkdownSaveOptions` द्वारा भारी काम किया जाता है। इसके `OfficeMathExportMode` को `LATEX` में बदलने से, प्रत्येक Office Math ऑब्जेक्ट Markdown आउटपुट के भीतर एक LaTeX अंश के रूप में रेंडर होता है। + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### यह क्यों काम करता है + +- **`Document`** Aspose का प्रवेश बिंदु है; यह `.docx` फ़ाइल को एब्स्ट्रैक्ट करता है और आपको प्रत्येक नोड, जिसमें समीकरण भी शामिल हैं, तक पहुँच देता है। +- **`MarkdownSaveOptions`** लाइब्रेरी को बताता है कि आप आउटपुट *कैसे* चाहते हैं। डिफ़ॉल्ट व्यवहार समीकरणों को इमेज़ के रूप में रेंडर करना है, जो टेक्स्ट‑आधारित फ़ॉर्मेट के उद्देश्य को नष्ट करता है। +- **`OfficeMathExportMode.LATEX`** इंजन को प्रत्येक `OfficeMath` नोड को उसके LaTeX समकक्ष में बदलने के लिए मजबूर करता है, जिसे Markdown पार्सर (जैसे GitHub या Jekyll) MathJax प्लगइन के साथ मिलाकर रेंडर कर सकते हैं। + +--- + +## Word समीकरणों को LaTeX में बदलें – चरण 2: Markdown आउटपुट की पुष्टि करें + +प्रोग्राम चलाने के बाद, `out.md` खोलें। आपको कुछ इस तरह दिखना चाहिए: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** LaTeX अंश को इनलाइन गणित के लिए `$…$` और ब्लॉक गणित के लिए `$$…$$` में लपेटा जाता है। यह मानक सिंटैक्स है जिसे अधिकांश स्थैतिक साइट जेनरेटर MathJax सक्षम होने पर समझते हैं। + +यदि आप चाहते हैं कि समीकरण केवल इनलाइन रहें, तो आप `MarkdownSaveOptions` को और समायोजित कर सकते हैं: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx को markdown latex – चरण 3: किनारे के केस और सामान्य जाल + +| स्थिति | ध्यान रखने योग्य बात | समाधान | +|-----------|-------------------|-----| +| **जटिल नेस्टेड समीकरण** | Aspose अतिरिक्त ब्रेसेस `{}` आउटपुट कर सकता है जिन्हें कुछ पार्सर शाब्दिक रूप से लेते हैं। | Markdown को एक सरल regex से पोस्ट‑प्रोसेस करें ताकि `{{` → `{` को संकुचित किया जा सके। | +| **लक्षित साइट पर MathJax की कमी** | समीकरण कच्चे LaTeX कोड के रूप में दिखते हैं। | अपने HTML टेम्पलेट में `` जोड़ें। | +| **बड़े दस्तावेज़** | स्मृति उपयोग बढ़ जाता है क्योंकि पूरा दस्तावेज़ एक साथ लोड होता है। | `LoadOptions.setLoadFormat(LoadFormat.DOCX)` का उपयोग करें और यदि `OutOfMemoryError` मिलता है तो पृष्ठों को बैच में प्रोसेस करने पर विचार करें। | +| **लाइसेंस सेट नहीं है** | आपको एक चेतावनी मिलेगी और आउटपुट पर वॉटरमार्क हो सकता है। | `main` में लाइसेंस को जल्दी लोड करें जैसा कि ऊपर Maven टिप में दिखाया गया है। | + +--- + +## Word को markdown के रूप में सहेजें – पूर्ण कार्यशील उदाहरण + +नीचे एक स्व-निहित क्लास है जिसे आप किसी भी Java प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। बस `YOUR_DIRECTORY` को अपनी फ़ाइलों के पथ से बदलें। + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +प्रोग्राम चलाएँ (`java MathToLatexMarkdown`) और आपको सफलता की पुष्टि करने वाला कंसोल संदेश मिलेगा। किसी भी एडिटर में `out.md` खोलें – समीकरण साफ़ LaTeX स्निपेट्स होने चाहिए जो रेंडरिंग के लिए तैयार हैं। + +--- + +## अपेक्षित आउटपुट स्नैपशॉट + +![save word as markdown output with LaTeX equations](https://example.com/images/markdown-latex-output.png "save word as markdown output with LaTeX equations") + +*छवि उत्पन्न किए गए Markdown का एक स्निपेट दिखाती है जहाँ समीकरण `\int_{a}^{b} f(x)\,dx` को `$$` में लपेटा गया है।* + +--- + +## निष्कर्ष + +हमने अभी दिखाया है कि कैसे **save word as markdown** करते हुए प्रत्येक Office Math समीकरण को मूल LaTeX के रूप में संरक्षित किया जा सकता है। मुख्य कदम `MarkdownSaveOptions` को `OfficeMathExportMode.LATEX` के साथ कॉन्फ़िगर करना था, जो सामान्य Word‑to‑Markdown पाइपलाइन को पूरी तरह से गणित‑सजग रूपांतरण टूल में बदल देता है। + +अब आप कर सकते हैं: + +1. **How to export math** को किसी भी `.docx` से बिना फ़िडेलिटी खोए निर्यात कर सकते हैं। +2. **Convert word equations latex** को स्थैतिक साइट जेनरेटर, दस्तावेज़ीकरण, या शैक्षणिक ब्लॉग के लिए उपयोग कर सकते हैं। +3. इस विधि को कई फ़ाइलों को बैच‑प्रोसेस करने, CI पाइपलाइन के साथ एकीकृत करने, या यहाँ तक कि एक छोटा वेब सर्विस बनाने के लिए विस्तारित करें। + +यदि आप अगले चरण के बारे में जिज्ञासु हैं, तो इसे **docx to markdown latex** के साथ मिलाकर इमेज‑भारी दस्तावेज़ों के लिए आज़माएँ, या वेब‑तैयार HTML संस्करण के लिए Aspose के `HtmlSaveOptions` का अन्वेषण करें। संभावनाएँ अनंत हैं—प्रयोग करें, चीज़ें तोड़ें, और फिर अपने निष्कर्ष समुदाय के साथ साझा करें। + +कोई प्रश्न या जटिल समीकरण जो अपेक्षित रूप से नहीं रेंडर हुआ? नीचे टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + +## संबंधित ट्यूटोरियल + +- [Word से LaTeX निर्यात कैसे करें: DOCX को Markdown में बदलें और PDF के रूप में सहेजें](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [docx को markdown में बदलें – Aspose.Words के साथ Math समीकरणों को LaTeX में निर्यात करें](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Aspose.Words for Java का उपयोग करके Word को PDF में कैसे बदलें](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/hindi/java/document-loading-and-saving/_index.md index 0fc7edcfcb..56e0cc4c6d 100644 --- a/words/hindi/java/document-loading-and-saving/_index.md +++ b/words/hindi/java/document-loading-and-saving/_index.md @@ -127,15 +127,9 @@ Aspose.Words for Java का उपयोग करके दस्तावे ### [Aspose.Words for Java में दस्तावेज़ों को टेक्स्ट फ़ाइलों के रूप में सेव करना](./saving-documents-as-text-files/) Aspose.Words for Java के साथ दस्तावेज़ों को टेक्स्ट फ़ाइलों के रूप में सेव करना सीखें। Java कोड उदाहरणों के साथ चरण‑दर‑चरण गाइड। -### [Aspose.Words for Java में दस्तावेज़ फ़ॉर्मेट निर्धारित करना](./determining-document-format/) -Aspose.Words के साथ Java में दस्तावेज़ फ़ॉर्मेट को पहचानना सीखें। DOC, DOCX आदि को पहचानें और फ़ाइलों को प्रभावी ढंग से व्यवस्थित करें। - -### [Corrupted docx को पुनर्प्राप्त करें – दस्तावेज़ ठीक करने और प्रोसेस करने की पूरी गाइड](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) - -Corrupted docx फ़ाइलों को ठीक करने, पुनर्स्थापित करने और आगे प्रोसेस करने के चरण‑दर‑चरण मार्गदर्शन। - ### [Aspose.Words के साथ जावा में फ़ॉन्ट प्रतिस्थापन चेतावनियों को कैप्चर करें – पूर्ण गाइड](./capture-font-substitution-warnings-in-java-with-aspose-words/) -Aspose.Words for Java में फ़ॉन्ट प्रतिस्थापन चेतावनियों को कैसे पकड़ें और संभालें, कोड उदाहरणों के साथ सीखें। + +### [Corrupted Word दस्तावेज़ खोलें – Java में रिकवरी मोड सेट करें](./open-corrupted-word-document-set-recovery-mode-in-java/) ## अक्सर पूछे जाने वाले प्रश्न diff --git a/words/hindi/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/hindi/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..50a14f40c9 --- /dev/null +++ b/words/hindi/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: जावा में Aspose.Words के साथ करप्टेड वर्ड दस्तावेज़ खोलें। सीखें कैसे + रिकवरी मोड सेट करें और करप्टेड वर्ड फ़ाइलों को विश्वसनीय रूप से पुनर्प्राप्त करें। +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: hi +og_description: Aspose.Words का उपयोग करके जावा में भ्रष्ट वर्ड दस्तावेज़ खोलें। यह + गाइड दिखाता है कि पुनर्प्राप्ति मोड कैसे सेट करें और भ्रष्ट वर्ड फ़ाइलों को प्रभावी + ढंग से पुनर्स्थापित करें। +og_title: दोषपूर्ण वर्ड दस्तावेज़ खोलें – जावा में रिकवरी मोड सेट करें +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: करप्टेड वर्ड दस्तावेज़ खोलें – जावा में रिकवरी मोड सेट करें +url: /hi/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# दोषपूर्ण Word दस्तावेज़ खोलें – Java में रिकवरी मोड सेट करें + +क्या आपने कभी एक दोषपूर्ण Word दस्तावेज़ खोलने की कोशिश की है और प्रोग्राम को अपवाद पर अटकते देखा है? आप अकेले नहीं हैं—वे टूटे .docx फ़ाइलें वास्तव में सिरदर्द बन सकती हैं। अच्छी खबर यह है कि Aspose.Words for Java आपको सूक्ष्म नियंत्रण देता है ताकि आप **open corrupted word document** बिना एप्लिकेशन के क्रैश हुए खोल सकें, और यह भी तय कर सकें कि आप चेतावनियाँ चाहते हैं, चुपचाप रिकवरी चाहते हैं, या कठोर अस्वीकृति। + +इस ट्यूटोरियल में हम पूरी प्रक्रिया को चरण-दर-चरण देखेंगे: सही `LoadOptions` बनाने से लेकर उपयुक्त **set recovery mode** मान चुनने तक, और अंत में यह पुष्टि करने तक कि दस्तावेज़ वास्तव में लोड हो गया है। अंत तक आप प्रोग्रामेटिक रूप से **how to recover corrupted word file** जान जाएंगे, बिना किसी मैन्युअल कॉपी‑पेस्ट के। + +> **आपको क्या चाहिए** +> * Java 8 या नया (API Java 11 के साथ भी काम करता है) +> * Aspose.Words for Java 23.9 (या नवीनतम संस्करण) +> * एक नमूना दोषपूर्ण .docx फ़ाइल—यदि आपके पास नहीं है तो किसी वैध फ़ाइल का नाम बदलकर भ्रष्टता का अनुकरण कर सकते हैं + +आइए शुरू करते हैं। + +## दोषपूर्ण Word दस्तावेज़ खोलें – चरण‑दर‑चरण अवलोकन + +नीचे वह उच्च‑स्तरीय प्रवाह है जिसे हम लागू करेंगे: + +1. **Create `LoadOptions`** – यह ऑब्जेक्ट Aspose.Words को बताता है कि समस्या मिलने पर कैसे व्यवहार करना है। +2. **Set recovery mode** – `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, या `REJECT_CORRUPTED` में से चुनें। +3. **Load the document** – कॉन्फ़िगर किए गए विकल्पों का उपयोग करके दस्तावेज़ लोड करें। +4. **Verify** – लोड सफल हुआ या नहीं, जाँचें (जैसे पेज काउंट प्रिंट करें)। + +प्रत्येक चरण को विस्तार से समझाया गया है, साथ ही कोड स्निपेट्स हैं जिन्हें आप सीधे अपने IDE में कॉपी‑पेस्ट कर सकते हैं। + +## विभिन्न परिदृश्यों के लिए रिकवरी मोड सेट करें + +Aspose.Words `LoadOptions.RecoveryMode` के भीतर तीन रिकवरी रणनीतियों को परिभाषित करता है: + +| मोड | व्यवहार | कब उपयोग करें | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | दस्तावेज़ लोड करने की कोशिश करता है, लेकिन किसी भी समस्या को कंसोल में चेतावनी के रूप में दिखाता है। | आप बिना रोकावट के *क्या* गलत हुआ, देखना चाहते हैं। | +| `RECOVER_WITHOUT_WARNINGS` | जो कुछ ठीक कर सकता है उसे चुपचाप ठीक करता है और चेतावनियों को दबा देता है। | उत्पादन वातावरण जहाँ लॉग साफ़ रहना चाहिए। | +| `REJECT_CORRUPTED` | जैसे ही भ्रष्टता का पता चलता है, अपवाद फेंकता है। | सख्त वैधता पाइपलाइन जो तेज़ी से विफल होना चाहिए। | + +सही मोड चुनना **set recovery mode** को सही ढंग से सेट करने का मूल है। अधिकांश डिबगिंग सत्रों में `RECOVER_WITH_WARNINGS` सबसे उपयुक्त होता है क्योंकि यह आपको ठीक किए गए भागों की सटीक जानकारी देता है। + +## Aspose.Words का उपयोग करके दोषपूर्ण Word फ़ाइल को कैसे रिकवर करें + +नीचे एक **पूर्ण, चलाने योग्य Java प्रोग्राम** है जो पूरी प्रक्रिया को दर्शाता है। इसे `RecoveryModeDemo.java` फ़ाइल में डालें, पथ समायोजित करें, और चलाएँ। + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### प्रत्येक पंक्ति का महत्व क्यों है + +* **`LoadOptions loadOptions = new LoadOptions();`** – इस ऑब्जेक्ट के बिना Aspose.Words डिफ़ॉल्ट रिकवरी उपयोग करता है, जो भ्रष्ट फ़ाइलों को *reject* करता है। इसे बनाने से आप व्यवहार बदलने का हुक प्राप्त करते हैं। +* **`setRecoveryMode(...)`** – यह **set recovery mode** कॉल है जो तय करता है कि चेतावनियाँ दिखें, छिपी रहें, या अपवाद उत्पन्न हो। +* **`new Document(path, loadOptions);`** – कंस्ट्रक्टर वह `LoadOptions` स्वीकार करता है जिसे हमने अभी कॉन्फ़िगर किया है, इसलिए लाइब्रेरी शुरू से ही टूटे फ़ाइल को कैसे संभालना है जानती है। +* **`doc.getPageCount()`** – एक त्वरित सत्यापन। यदि दस्तावेज़ लोड हो जाता है और पेज काउंट लौटाता है, तो आपने सफलतापूर्वक **how to recover corrupted word file** किया है। +* **`doc.save(...)`** – वैकल्पिक लेकिन उपयोगी; आप सुधारी गई संस्करण को बाद में उपयोग के लिए डिस्क पर लिख सकते हैं। + +## सामान्य किनारे के मामलों को संभालना + +### 1. फ़ाइल नहीं मिली + +यदि पथ गलत है, तो `Document` `FileNotFoundException` फेंकता है। लोड को try‑catch ब्लॉक में घेरें और एक मित्रवत संदेश लॉग करें: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. अपरिवर्तनीय भ्रष्टता + +`RECOVER_WITH_WARNINGS` के साथ भी, कुछ संरचनाएँ मरम्मत से बाहर होती हैं। ऐसे में Aspose.Words जो कुछ भी लोड कर सकता है, लोड करता है, लेकिन आपको “Cannot read paragraph properties” जैसी चेतावनियाँ दिखेंगी। कंसोल आउटपुट पर ध्यान दें; ये चेतावनियाँ अक्सर गायब सेक्शन की ओर संकेत करती हैं जिन्हें आपको मैन्युअल रूप से पुनर्निर्मित करना पड़ सकता है। + +### 3. बड़े फ़ाइलें और प्रदर्शन + +रिकवरी में थोड़ा ओवरहेड जुड़ता है क्योंकि लाइब्रेरी फ़ाइल को दो बार पार्स करती है—एक बार समस्याओं का पता लगाने के लिए, फिर पुनर्निर्माण के लिए। मल्टी‑गिगाबाइट दस्तावेज़ों के लिए, फ़ाइल को स्ट्रीम करने या JVM हीप (`-Xmx2g`) बढ़ाने पर विचार करें ताकि `OutOfMemoryError` से बचा जा सके। + +## प्रो टिप्स – रिकवरी को मजबूत बनाना + +* **चेतावनियों को फ़ाइल में लॉग करें** – `System.err` को एक लॉगर में रीडायरेक्ट करें ताकि आपको यह पता चल सके कि क्या ठीक किया गया। +* **रिकवरी के बाद वैधता जांचें** – `doc.updatePageLayout();` चलाएँ और फिर पेज काउंट को पुनः जाँचें; कभी‑कभी टूटे सेक्शन ठीक करने के बाद लेआउट बदल जाता है। +* **बैच रिकवरी को स्वचालित करें** – डेमो को एक लूप में रखें जो भ्रष्ट फ़ाइलों के फ़ोल्डर को प्रोसेस करे, हर बार समान `LoadOptions` का उपयोग करते हुए। + +## निष्कर्ष + +अब आप बिल्कुल जानते हैं कि Aspose.Words for Java का उपयोग करके **how to recover corrupted word file** कैसे किया जाता है। एक `LoadOptions` इंस्टेंस बनाकर, अपने परिदृश्य के अनुसार **set recovery mode** को सेट करके, और उन विकल्पों के साथ दस्तावेज़ लोड करके, आप सुरक्षित रूप से **open corrupted word document** कर सकते हैं बिना अपने एप्लिकेशन को क्रैश किए। ऊपर दिया गया नमूना कोड एक पूर्ण, तैयार‑चलाने योग्य समाधान है जो पेज काउंट प्रिंट करता है और यहाँ तक कि साफ़ किया गया प्रतिलिपि भी सहेजता है। + +अब आगे क्या? रिकवरी मोड को `RECOVER_WITHOUT_WARNINGS` में बदलें और कंसोल आउटपुट की तुलना करें, या एन्क्रिप्टेड दस्तावेज़ लोड करने के साथ प्रयोग करें (आपको पासवर्ड प्रदान करना होगा ... + +## संबंधित ट्यूटोरियल + +- [Aspose.Words Java: Word दस्तावेज़ प्रोसेसिंग के लिए व्यापक गाइड](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Aspose.Words for Java का उपयोग करके Word को PDF में कैसे बदलें](/words/english/java/document-converting/using-document-converting/) +- [Aspose.Words for Java के साथ दो Word फ़ाइलों की तुलना कैसे करें](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/hindi/java/document-styling/_index.md index 1511686b4d..65a11c4d6e 100644 --- a/words/hindi/java/document-styling/_index.md +++ b/words/hindi/java/document-styling/_index.md @@ -24,7 +24,7 @@ Aspose.Words for Java दस्तावेज़ स्टाइलिंग ## उन्नत स्टाइलिंग सुविधाओं का लाभ उठाना -एक बार जब आप आवश्यक दस्तावेज़ स्टाइलिंग कौशल हासिल कर लेते हैं, तो हम अधिक उन्नत तकनीकों पर आगे बढ़ेंगे। ये ट्यूटोरियल आपको परिष्कृत शैलियों और लेआउट बनाने के लिए जावा के लिए Aspose.Words का उपयोग करने के बारे में मार्गदर्शन करेंगे। जानें कि कस्टम हेडर और फ़ुटर को कैसे लागू किया जाए, विभिन्न पेज ओरिएंटेशन के साथ कई सेक्शन सेट करें और जटिल दस्तावेज़ों पर जटिल फ़ॉर्मेटिंग लागू करें। आप जानेंगे कि दस्तावेज़ थीम, शैलियों और टेम्प्लेट के साथ कैसे काम किया जाए, सुसंगत और पेशेवर दिखने वाले दस्तावेज़ बनाने की प्रक्रिया को सुव्यवस्थित किया जाए। ये उन्नत स्टाइलिंग सुविधाएँ आपको प्रभावशाली दस्तावेज़ प्रसंस्करण समाधान देने में सक्षम बनाती हैं जो लालित्य और व्यावसायिकता के साथ अलग दिखते हैं। +एक बार जब आप आवश्यक दस्तावेज़ स्टाइलिंग कौशल हासिल कर ले लेते हैं, तो हम अधिक उन्नत तकनीकों पर आगे बढ़ेंगे। ये ट्यूटोरियल आपको परिष्कृत शैलियों और लेआउट बनाने के लिए जावा के लिए Aspose.Words का उपयोग करने के बारे में मार्गदर्शन करेंगे। जानें कि कस्टम हेडर और फ़ुटर को कैसे लागू किया जाए, विभिन्न पेज ओरिएंटेशन के साथ कई सेक्शन सेट करें और जटिल दस्तावेज़ों पर जटिल फ़ॉर्मेटिंग लागू करें। आप जानेंगे कि दस्तावेज़ थीम, शैलियों और टेम्प्लेट के साथ कैसे काम किया जाए, सुसंगत और पेशेवर दिखने वाले दस्तावेज़ बनाने की प्रक्रिया को सुव्यवस्थित किया जाए। ये उन्नत स्टाइलिंग सुविधाएँ आपको प्रभावशाली दस्तावेज़ प्रसंस्करण समाधान देने में सक्षम बनाती हैं जो लालित्य और व्यावसायिकता के साथ अलग दिखते हैं। ## दस्तावेज़ स्टाइलिंग दक्षता का अनुकूलन @@ -43,6 +43,8 @@ Java के लिए Aspose.Words का उपयोग करके दस् Aspose.Words for Java के साथ वॉटरमार्क लगाना और पेज कॉन्फ़िगरेशन सेट करना सीखें। सोर्स कोड के साथ एक व्यापक गाइड। ### [दस्तावेज़ शीर्षलेख और पादलेख शैली](./document-header-footer-styling/) इस विस्तृत गाइड में जानें कि Aspose.Words for Java का उपयोग करके दस्तावेज़ हेडर और फ़ुटर को कैसे स्टाइल किया जाए। चरण-दर-चरण निर्देश और स्रोत कोड शामिल हैं। +### [Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करना – पूर्ण गाइड](./set-default-font-settings-in-aspose-words-for-java-complete/) +Java के लिए Aspose.Words में डिफ़ॉल्ट फ़ॉन्ट सेट करने की प्रक्रिया सीखें, कोड उदाहरणों के साथ पूर्ण गाइड। {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/hindi/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..13b8b40c1b --- /dev/null +++ b/words/hindi/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें और सीखें + कि केवल कुछ लाइनों के कोड में फ़ॉन्ट सेटिंग्स कैसे सेट करें और गायब फ़ॉन्ट्स का + पता कैसे लगाएँ। +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: hi +og_description: Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें, फ़ॉन्ट + सेटिंग्स कैसे सेट करें और लापता फ़ॉन्ट्स को तेज़ और भरोसेमंद तरीके से पहचानना सीखें। +og_title: Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें – पूर्ण गाइड +url: /hi/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें – पूर्ण गाइड + +क्या आपने कभी सोचा है कि Aspose.Words for Java के साथ Word दस्तावेज़ लोड करते समय **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें**? आप अकेले नहीं हैं। लापता glyphs एक परिपूर्ण रिपोर्ट को गड़बड़ में बदल सकते हैं, और फ़ॉन्ट‑सब्स्टिट्यूशन चेतावनियों को जल्दी पकड़ना डिबगिंग में घंटों बचा सकता है। + +इस ट्यूटोरियल में हम एक संक्षिप्त, अंत‑से‑अंत उदाहरण के माध्यम से चलेंगे जो **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करता है**, आपको दिखाता है कि प्रोग्रामेटिक रूप से **फ़ॉन्ट सेटिंग्स कैसे सेट करें**, और एक विश्वसनीय तरीका दर्शाता है जिससे **लापता फ़ॉन्ट्स का पता लगाया जा सके** इससे पहले कि वे आपके लेआउट को बिगाड़ें। + +--- + +## आप क्या सीखेंगे + +- कैसे एक नया `FontSettings` इंस्टेंस के साथ `LoadOptions` ऑब्जेक्ट बनाएं। +- कैसे एक warning listener संलग्न करें जो दस्तावेज़ लोड के दौरान **लापता फ़ॉन्ट्स का पता लगाए**। +- कैसे एक DOCX फ़ाइल लोड करें जबकि listener चुपचाप किसी भी सब्स्टिट्यूशन की रिपोर्ट करे। +- उत्पादन में fallback फ़ॉन्ट्स को कस्टमाइज़ करने और edge cases को संभालने के लिए टिप्स। + +कोई अतिरिक्त लाइब्रेरी नहीं, कोई अस्पष्ट कॉन्फ़िगरेशन फ़ाइल नहीं—सिर्फ साधारण Java और Aspose.Words। + +--- + +## पूर्वापेक्षाएँ + +शुरू करने से पहले, सुनिश्चित करें कि आपके पास है: + +1. **Aspose.Words for Java** (संस्करण 23.10 या नया) आपके classpath पर। +2. Java 17 (या बाद का) डेवलपमेंट किट – कोई भी आधुनिक JDK काम करेगा। +3. एक DOCX फ़ाइल जो जानबूझकर ऐसे फ़ॉन्ट का उपयोग करती है जो आपके सिस्टम में स्थापित नहीं है (उदाहरण के लिए *“MissingFont.ttf”*)। + +यदि आपके पास Aspose JAR नहीं है, तो इसे आधिकारिक Maven रिपॉजिटरी से प्राप्त करें: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +बस इतना ही—इस डेमो के लिए कोई अतिरिक्त फ़ॉन्ट स्थापित करने की आवश्यकता नहीं है। + +--- + +## चरण 1: LoadOptions बनाएं और **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करें** + +पहली बात जो हमें चाहिए वह एक साफ़ `LoadOptions` ऑब्जेक्ट है जो Aspose को बताता है कि जब वह अज्ञात टाइपफ़ेस का सामना करता है तो कैसे व्यवहार करे। `setFontSettings(new FontSettings())` को कॉल करके हम **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करते हैं** जो एक खाली fallback सूची से शुरू होती हैं। + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **यह क्यों महत्वपूर्ण है:** +> जब आप स्पष्ट रूप से फ़ॉन्ट कॉन्फ़िगर नहीं करते, तो Aspose सिस्टम की डिफ़ॉल्ट कलेक्शन पर fallback करता है, जिससे लापता‑फ़ॉन्ट समस्याएँ छिप सकती हैं। एक नई `FontSettings` इंस्टेंस से शुरू करके आप यह पूरी तरह नियंत्रित कर सकते हैं कि कौन से फ़ॉन्ट वैध माने जाएँ। + +--- + +## चरण 2: Warning Listener संलग्न करें ताकि **लापता फ़ॉन्ट्स का पता लगाया जा सके** + +Aspose प्रत्येक सब्स्टिट्यूशन के लिए एक `WarningInfo` ऑब्जेक्ट उठाता है। `WarningType.FONT_SUBSTITUTION` को सुनकर हम दस्तावेज़ पार्स होते ही **लापता फ़ॉन्ट्स का पता लगा सकते हैं**। + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **प्रो टिप:** Listener उसी थ्रेड पर चलता है जो दस्तावेज़ लोड करता है, इसलिए प्रदर्शन पर लगभग कोई असर नहीं पड़ता। यदि आपको बाद में विश्लेषण के लिए चेतावनियों को एकत्र करने की आवश्यकता है, तो उन्हें सीधे प्रिंट करने के बजाय `List` में पुश करें। + +--- + +## चरण 3: कॉन्फ़िगर किए गए विकल्पों का उपयोग करके दस्तावेज़ लोड करें + +अब जब हमने **फ़ॉन्ट सेटिंग्स सेट की** और एक listener तैयार कर लिया है, हम बस फ़ाइल लोड करते हैं। कोई भी लापता फ़ॉन्ट तुरंत हमारे कॉलबैक को ट्रिगर करेगा। + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +यदि स्रोत फ़ाइल ऐसे फ़ॉन्ट का संदर्भ देती है जो स्थापित नहीं है, तो आपको नीचे जैसा आउटपुट दिखेगा: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +यह पंक्ति आपको ठीक-ठीक बताती है कि कौन सा फ़ॉन्ट लापता था और कौन सा fallback उपयोग किया गया—लॉगिंग या उपयोगकर्ता फ़ीडबैक के लिए एकदम उपयुक्त। + +--- + +## चरण 4: सामान्य प्रोसेसिंग जारी रखें (वैकल्पिक) + +इस चरण पर दस्तावेज़ पूरी तरह लोड हो चुका है, और आप अपनी इच्छा के अनुसार कोई भी परिवर्तन कर सकते हैं—संपादन, PDF में बदलना, या टेक्स्ट निकालना। Warning listener ने अपना काम पहले ही कर लिया है, इसलिए अतिरिक्त जाँच की आवश्यकता नहीं है। + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **यदि आप एक कस्टम fallback चाहते हैं तो?** +> `FontSettings` को खाली छोड़ने के बजाय, आप विशिष्ट फ़ॉन्ट जोड़ सकते हैं: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +अब कोई भी लापता टाइपफ़ेस *Times New Roman* से बदल दिया जाएगा—अधिकांश पश्चिमी दस्तावेज़ों के लिए एक विश्वसनीय विकल्प। + +--- + +## दृश्य अवलोकन + +![Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करने का आरेख](image.png "डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स प्रवाह का आरेख") + +*Alt text: Aspose.Words for Java में डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स का फ्लोचार्ट.* + +यह आरेख `LoadOptions` को इनिशियलाइज़ करने से (जहाँ हम **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करते हैं**) warning listener को संलग्न करने तक (ताकि **लापता फ़ॉन्ट्स का पता लगाया जा सके**) और अंत में दस्तावेज़ लोड करने तक का प्रवाह दर्शाता है। + +--- + +## सामान्य समस्याएँ और उन्हें कैसे टालें + +| समस्या | क्यों होता है | समाधान | +|---------|----------------|-----| +| **`setFontSettings` कॉल करना भूल गए** | Aspose सिस्टम डिफ़ॉल्ट का उपयोग करता है, जिससे लापता फ़ॉन्ट छिप जाते हैं। | हमेशा एक नया `FontSettings` इंस्टेंस बनाएं और उसे `LoadOptions` को असाइन करें। | +| **Listener ट्रिगर नहीं हुआ** | दस्तावेज़ लोड होने के बाद Listener जोड़ा गया। | `new Document(...)` कॉल करने *से पहले* warning listener जोड़ें। | +| **पाथ टाइपो से `FileNotFoundException` आता है** | हार्ड‑कोडेड पाथ OS की केस‑सेंसिटिविटी से मेल नहीं खाता। | `Paths.get("...").toAbsolutePath()` का उपयोग करें या प्रोजेक्ट रूट से रिलेटिव पाथ कॉन्फ़िगर करें। | +| **एकाधिक लापता फ़ॉन्ट्स लॉग्स को भर देते हैं** | बड़े दस्तावेज़ कई चेतावनियाँ उत्पन्न कर सकते हैं। | प्रिंट करने से पहले डुप्लिकेट फ़िल्टर करें या संदेशों को `Set` में एकत्रित करें। | + +--- + +## समाधान का विस्तार + +यदि आपको पूरे एप्लिकेशन के लिए **फ़ॉन्ट सेटिंग्स सेट करनी** हैं, तो एक singleton `FontSettings` बनाकर उसे सभी `LoadOptions` में पुन: उपयोग करने पर विचार करें। इस तरह आप एक सुसंगत fallback रणनीति बनाए रखेंगे और ऑब्जेक्ट निर्माण की पुनरावृत्ति से बचेंगे। + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +अब आपके कोडबेस का कोई भी भाग बस `FontConfig.getLoadOptions()` को कॉल कर सकता है और तुरंत वही **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करने** लॉजिक का लाभ उठा सकता है। + +--- + +## निष्कर्ष + +हमने अभी-अभी वह सब कवर किया है जो आपको Aspose.Words for Java में **डिफ़ॉल्ट फ़ॉन्ट सेटिंग्स सेट करने**, प्रोग्रामेटिक रूप से **फ़ॉन्ट सेटिंग्स सेट करने**, और आपके आउटपुट को खराब करने से पहले **लापता फ़ॉन्ट्स का पता लगाने** के लिए चाहिए। पूर्ण, चलाने योग्य उदाहरण ऊपर दिए गए कोड स्निपेट्स में मौजूद है, और आप इसे सीधे अपने IDE में पेस्ट करके चेतावनियों को क्रिया में देख सकते हैं। + +अगले कदम? fallback फ़ॉन्ट बदलें, विभिन्न दस्तावेज़ फ़ॉर्मेट (DOC, RTF, HTML) के साथ प्रयोग करें, या warning collector को मॉनिटरिंग डैशबोर्ड में इंटीग्रेट करें। जितना अधिक आप `FontSettings` के साथ खेलेंगे, उतना ही भरोसा होगा कि आपके जेनरेटेड दस्तावेज़ बिल्कुल इच्छित रूप में दिखेंगे—कोई आश्चर्य नहीं, कोई टूटे हुए glyphs नहीं। + +कोई प्रश्न या जटिल फ़ॉन्ट‑सब्स्टिट्यूशन स्थिति है? नीचे टिप्पणी छोड़ें, और कोडिंग का आनंद लें! + +## संबंधित ट्यूटोरियल + +- [फ़ॉन्ट फ़ॉलबैक सेटिंग्स सेट करें](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [फ़ॉन्ट फ़ॉलबैक सेटिंग्स सेट करें](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [फ़ॉन्ट फ़ॉलबैक सेटिंग्स सेट करें](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/java/images-shapes/_index.md b/words/hindi/java/images-shapes/_index.md index 0a75bde9f4..6db23a94c5 100644 --- a/words/hindi/java/images-shapes/_index.md +++ b/words/hindi/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Java के लिए Aspose.Words के साथ Word दस्तावे ### [जावा में Word दस्तावेज़ बनाएं – आयताकार आकार को छाया प्रभाव के साथ जोड़ें](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) जावा में Aspose.Words का उपयोग करके Word दस्तावेज़ में आयताकार आकार को छाया प्रभाव के साथ जोड़ने का तरीका सीखें। +### [जावा वर्ड दस्तावेज़ में आयताकार आकार बनाएं – पूर्ण चरण‑दर‑चरण मार्गदर्शिका](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Aspose.Words for Java का उपयोग करके वर्ड दस्तावेज़ में आयताकार आकार जोड़ने की पूरी चरण‑दर‑चरण प्रक्रिया सीखें। + ## अतिरिक्त संसाधन - [जावा दस्तावेज़ीकरण के लिए Aspose.Words](https://reference.aspose.com/words/java/) diff --git a/words/hindi/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/hindi/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..a2d9b3e86c --- /dev/null +++ b/words/hindi/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-26 +description: जावा वर्ड दस्तावेज़ में आयताकार आकार बनाएं और शैडो इफ़ेक्ट लागू करें। + सीखें कि कैसे आकार में शैडो जोड़ें, शैडो की दूरी सेट करें, और फ़ाइल को सहेजें। +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: hi +og_description: जावा वर्ड दस्तावेज़ में आयताकार आकार बनाएं, छाया प्रभाव लागू करें, + आकार की छाया जोड़ें, और Aspose.Words के साथ छाया दूरी सेट करें। +og_title: जावा वर्ड दस्तावेज़ में आयताकार आकार बनाएं – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: जावा वर्ड दस्तावेज़ में आयत आकार बनाएं – पूर्ण चरण-दर-चरण गाइड +url: /hi/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java Word Document में आयताकार आकार बनाएं – पूर्ण चरण‑दर‑चरण मार्गदर्शिका + +क्या आपको कभी Java Word दस्तावेज़ में **आयताकार आकार बनाना** पड़ा है लेकिन शुरू करने का तरीका नहीं पता था? आप अकेले नहीं हैं—कई डेवलपर्स को रिपोर्ट या इनवॉइस प्रोग्रामेटिकली जनरेट करते समय यही समस्या आती है। इस ट्यूटोरियल में हम बिल्कुल बताएँगे कि **आयताकार आकार कैसे बनाएं**, एक परिष्कृत शैडो लागू करें, और शैडो की दूरी को फाइन‑ट्यून करें ताकि परिणाम पेशेवर दिखे। + +हम Aspose.Words for Java का उपयोग करेंगे, एक मजबूत लाइब्रेरी जो आपको Microsoft Office स्थापित किए बिना Word फ़ाइलों को मैनीपुलेट करने देती है। इस गाइड के अंत तक आप **create word document java** प्रोजेक्ट्स बना पाएँगे जो **add shape shadow**, **apply shadow effect**, और **set shadow distance** को कुछ ही कोड लाइनों से लागू कर सकेंगे। + +--- + +## आप क्या बनाएँगे + +- एक नई `.docx` फ़ाइल जिसमें सियान रंग का आयताकार हो। +- एक वास्तविक ड्रॉप शैडो जो धुंधला, कोणीय, और आंशिक रूप से पारदर्शी हो। +- शैडो की दूरी पर पूर्ण नियंत्रण। +- एक तैयार‑चलाने योग्य Java क्लास जिसे आप किसी भी Maven या Gradle प्रोजेक्ट में डाल सकते हैं। +- कोई बाहरी टूल नहीं, कोई मैनुअल UI कदम नहीं—सिर्फ शुद्ध कोड। + +--- + +## पूर्वापेक्षाएँ + +- Java 8 या उससे नया (कोड Java 11, Java 17 आदि पर काम करता है)। +- Aspose.Words for Java लाइब्रेरी (Maven Central के माध्यम से उपलब्ध)। +- आपका पसंदीदा IDE या टेक्स्ट एडिटर (IntelliJ IDEA, Eclipse, VS Code…)। +- Java सिंटैक्स की बुनियादी परिचितता। + +यदि आपने पहले कभी Maven डिपेंडेंसी नहीं जोड़ी है, तो यहाँ त्वरित स्निपेट है: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +अब, चलिए शुरू करते हैं। + +--- + +## चरण 1: Word दस्तावेज़ में आयताकार आकार बनाएं + +सबसे पहले हमें एक खाली दस्तावेज़ और एक `DocumentBuilder` चाहिए। बिल्डर को आप उस पेन की तरह सोचें जो दस्तावेज़ में लिखता है। एक बार यह मिल जाए, हम एक ही मेथड कॉल से **आयताकार आकार बना** सकते हैं। + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **यह क्यों महत्वपूर्ण है:** `insertShape` मेथड न केवल ज्यामिति बनाता है बल्कि आकार को दस्तावेज़ के आंतरिक संग्रह में भी जोड़ता है, जिससे आप तुरंत उसकी स्टाइलिंग शुरू कर सकते हैं। + +--- + +## चरण 2: आकार पर शैडो इफ़ेक्ट लागू करें + +अब जबकि आयताकार पेज पर मौजूद है, हम **शैडो इफ़ेक्ट लागू** करेंगे। शैडो गहराई देती है, जिससे आकार पेज से उठी हुई महसूस होती है—एक सूक्ष्म UI सुधार जो रिपोर्ट की पठनीयता बढ़ा सकता है। + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **प्रो टिप:** `5.0` का ब्लर अधिकांश स्क्रीन‑डिस्प्ले दस्तावेज़ों के लिए प्राकृतिक दिखता है। यदि आप प्रिंट कर रहे हैं, तो धुंधला दिखने से बचने के लिए थोड़ा कम मान चुन सकते हैं। + +--- + +## चरण 3: शैडो दूरी सेट करें – प्लेसमेंट का फाइन‑ट्यूनिंग + +शैडो केवल ब्लर नहीं होते; उन्हें सही ऑफ़सेट भी चाहिए। यहीं पर हम **शैडो दूरी सेट** करते हैं। `7.0` पॉइंट की दूरी एक मध्यम ऑफ़सेट बनाती है जो दिखने योग्य है लेकिन अधिक नहीं। + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **यदि आपको बड़ा ऑफ़सेट चाहिए?** मान बढ़ाएँ; कसा हुआ लुक पाने के लिए घटाएँ। याद रखें, दूरी एंगल के साथ मिलकर शैडो को सही ढंग से पोजिशन करती है। + +--- + +## चरण 4: दस्तावेज़ सहेजें – अपना काम सुरक्षित रखें + +अंत में, हम दस्तावेज़ को डिस्क पर लिखते हैं। पाथ को उस स्थान पर बदलें जहाँ आप फ़ाइल रखना चाहते हैं। + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +क्लास चलाने से एक `shadow.docx` फ़ाइल बनती है जो Microsoft Word या LibreOffice में खोलने पर 45° पर एंगल्ड और 7 पॉइंट ऑफ़सेट वाली सॉफ्ट ग्रे शैडो के साथ सियान आयताकार दिखाती है। + +--- + +## पूर्ण कार्यशील उदाहरण + +नीचे पूरा, कॉपी‑एंड‑पेस्ट‑तैयार कोड दिया गया है। इसमें सभी इम्पोर्ट्स, कमेंट्स, और अंतिम `save` कॉल शामिल है। + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**अपेक्षित आउटपुट:** `shadow.docx` खोलें → आपको पहला पेज के केंद्र में सियान आयताकार दिखेगा, जिसके नीचे‑दाएँ ओर हल्का ग्रे शैडो होगा। शैडो का ब्लर और पारदर्शिता इसे प्राकृतिक प्रकाश जैसा बनाते हैं। + +--- + +## सामान्य प्रश्न और किनारे के मामलों + +### “क्या मैं कोई अलग आकार उपयोग कर सकता हूँ?” + +बिल्कुल। `ShapeType.RECTANGLE` को `ShapeType.OVAL`, `ShapeType.LINE`, या किसी अन्य समर्थित एन्नुम से बदलें। शैडो कोड का बाकी हिस्सा समान रहता है। + +### “यदि मुझे कई शैडो चाहिए तो?” + +Aspose.Words प्रत्येक आकार के लिए केवल एक शैडो का समर्थन करता है। कई शैडो का सिमुलेशन करने के लिए, आकार को डुप्लिकेट करें, प्रत्येक कॉपी को ऑफ़सेट करें, और पारदर्शिता को समायोजित करें। + +### “क्या LibreOffice में शैडो दिखता है?” + +हां—Aspose.Words मानक OOXML लिखता है, जिसे LibreOffice सही ढंग से व्याख्या करता है। रेंडरिंग इंजन के कारण शैडो थोड़ा अलग दिख सकता है, लेकिन प्रभाव बना रहता है। + +### “मैं शैडो का रंग अपने ब्रांड के अनुसार कैसे बदलूँ?” + +सिर्फ `java.awt.Color.GRAY` को अपनी पसंद के किसी भी `java.awt.Color` से बदलें, जैसे कॉर्पोरेट ब्लू के लिए `new java.awt.Color(0, 120, 215)`। + +--- + +## चित्रात्मक उदाहरण + +![Java Word दस्तावेज़ में आयताकार आकार बनाना](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** चित्रण जिसमें Word दस्तावेज़ में सियान आयताकार और ग्रे ड्रॉप शैडो दिखाया गया है। + +--- + +## सारांश और अगले कदम + +हमने Aspose.Words for Java का उपयोग करके **आयताकार आकार बनाना**, **शैडो इफ़ेक्ट लागू करना**, **आकार शैडो जोड़ना**, और **शैडो दूरी सेट करना** कवर किया है। कोड स्व-निहित है, किसी भी आधुनिक JDK पर चलता है, और वितरण के लिए तैयार एक परिष्कृत `.docx` फ़ाइल बनाता है। + +और आगे बढ़ना चाहते हैं? कोशिश करें: + +- आयताकार के अंदर टेक्स्ट जोड़ना `builder.moveTo(rectangleShape.getAbsolutePosition())` के साथ। +- डायग्राम बनाने के लिए आकारों की एक टेबल बनाना। +- दस्तावेज़ को PDF में एक्सपोर्ट करना (`doc.save("output.pdf", SaveFormat.PDF);`)। + +इनमें से प्रत्येक उसी मूलभूत सिद्धांतों पर आधारित है जो हमने अभी खोजे हैं, इसलिए आप उदाहरण को विस्तारित करने में सहज महसूस करेंगे। + +--- + +## अंतिम विचार + +**create word document java** जैसे आकार बनाना और शैडो लागू करना में महारत हासिल करने से रिपोर्ट, कॉन्ट्रैक्ट या मार्केटिंग कोलैटरल को ऑटोमेट करने में आपको बड़ा लाभ मिलता है। यहाँ दिखाया गया तरीका साफ़, रखरखाव योग्य, और—सबसे महत्वपूर्ण—आपकी किसी भी विज़ुअल स्टाइल के लिए आसानी से समायोजित करने योग्य है। + +कोड को चलाएँ, ब्लर, एंगल, और दूरी को समायोजित करें, और देखें कि आपका दस्तावेज़ साधारण से परिष्कृत में बदलता है। यदि आपको कोई समस्या आती है, तो नीचे टिप्पणी छोड़ें; मैं मदद करने के लिए तैयार हूँ। + +कोडिंग का आनंद लें! + +## संबंधित ट्यूटोरियल + +- [Word Document Java बनाएं – शैडो इफ़ेक्ट के साथ आयताकार आकार जोड़ें](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Aspose.Words for Java में DocumentBuilder का उपयोग करके फ़ॉर्म फ़ील्ड बनाना और सामग्री जोड़ना](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Word से PDF बनाना बारकोड जेनरेशन के साथ – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/hongkong/java/document-conversion-and-export/_index.md index 6ae66f49ea..41f5869cbc 100644 --- a/words/hongkong/java/document-conversion-and-export/_index.md +++ b/words/hongkong/java/document-conversion-and-export/_index.md @@ -72,6 +72,8 @@ Aspose.Words for Java 的主要功能之一是能夠 **convert docx to pdf** 以 ### [將 docx 轉換為 markdown – 使用 Aspose.Words 匯出數學方程式至 LaTeX](./convert-docx-to-markdown-export-math-equations-to-latex-with/) +### [將 Word 儲存為 Markdown – 使用 Java 匯出數學至 LaTeX](./save-word-as-markdown-export-math-to-latex-with-java/) + ### [aspose word to pdf – Convert DOCX to PDF in Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) ### [Using Document Shapes in Aspose.Words for Java](./using-document-shapes/) @@ -84,8 +86,16 @@ Aspose.Words for Java 的主要功能之一是能夠 **convert docx to pdf** 以 ### [如何在將 DOCX 轉換為 Markdown 時嵌入圖像](./how-to-embed-images-in-markdown-when-converting-docx/) +### [在將 DOCX 轉換為 Markdown 時以 Base64 嵌入圖像](./embed-images-as-base64-when-converting-docx-to-markdown/) + ### [從 DOCX 建立可存取 PDF – 完整指南](./create-accessible-pdf-from-docx-complete-guide/) +### [將文件另存為 PDF – Aspose.Words Java 完整可存取指南](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) + +### [在 Java 中建立可存取 PDF – 完整標記指南](./create-accessible-pdf-in-java-full-tagging-guide/) + +### [Export docx to txt with Java – Complete Programming Guide](./export-docx-to-txt-with-java-complete-programming-guide/) + ## 常見問題 **Q: How do I add a watermark to an existing PDF using Aspose.Words?** diff --git a/words/hongkong/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/hongkong/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..500dc3dae9 --- /dev/null +++ b/words/hongkong/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: 在 Java 中使用逐步程式碼建立可存取的 PDF。學習如何為 PDF 加上可存取標籤,並使用 PdfSaveOptions 啟用 PDF + 標籤功能。 +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: zh-hant +og_description: 使用逐步程式碼在 Java 中建立可存取的 PDF。了解如何為可及性標記 PDF,並使用 PdfSaveOptions 啟用 PDF + 標記。 +og_title: 在 Java 中建立無障礙 PDF – 完整標記指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: 使用 Java 建立無障礙 PDF – 完整標籤指南 +url: /zh-hant/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Java 中建立可存取的 PDF – 完整標記指南 + +有沒有想過如何直接從 Java 程式碼**建立可存取的 PDF**檔案?你並不孤單。許多開發者需要為依賴螢幕閱讀器的使用者提供服務,而普通 PDF 與可存取 PDF 之間的差異可能相當巨大。在本教學中,我們將逐步說明**如何為可存取性標記 PDF**,示範如何使用 Aspose PDF for Java **建立已標記的 PDF**,並揭示**將可存取性標籤加入 PDF**的具體步驟,讓每位讀者都能取得相同資訊。 + +我們還會涵蓋**啟用 PDF 標記**的最佳實踐、常見陷阱,以及一個完整、可直接執行的範例,讓你今天就能將其放入專案中。沒有模糊的參考——只有具體的程式碼、說明,以及一個可在 Adobe Acrobat 中開啟以驗證標記的最終檔案。 + +## 你將學到什麼 + +- 為何需要 PDF 標記以及可存取性合規性。 +- 前置條件與函式庫設定(Aspose PDF for Java 23.10 或更新版本)。 +- 如何從頭開始**建立可存取的 PDF**,一步一步說明。 +- 超越基本 `setTagDocumentStructure` 呼叫的**將可存取性標籤加入 PDF**的方法。 +- 測試輸出與排除常見問題的技巧。 + +完成本指南後,你將能產生符合 WCAG 2.1 AA 檢測且同時具備專業外觀的 PDF。 + +--- + +## 前置條件 + +在深入之前,請確保你已具備以下條件: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | 現代語言功能與更佳的 Unicode 處理。 | +| **Aspose PDF for Java** (v23.10 or newer) | 提供 `PdfSaveOptions` 類別與標記支援。 | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | 方便編譯與除錯。 | +| **Write permission** to a folder where the PDF will be saved | `doc.save` 呼叫需要可寫入的路徑。 | + +如果尚未將 Aspose PDF 加入專案,請在 `pom.xml` 中加入以下 Maven 依賴: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **專業提示:** 使用最新版本;較新的發行版可提升標記準確度並加入語言特定的可存取功能。 + +--- + +## 步驟 1:建立文件骨架 + +首先,我們建立一個全新的 `Document` 物件。可將其視為一張空白畫布,稍後會在上面放入可存取性所需的標記。 + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**為何重要:** 若沒有任何內容,就無法進行標記。即使加入一個簡單的 `TextFragment`,也能讓標記引擎有可處理的對象,且在之後啟用結構標記時,它會自動產生 `

`(段落)標記。 + +--- + +## 步驟 2:建立 PDF 儲存選項(標記核心) + +現在,我們準備選項,告訴 Aspose PDF 在檔案中嵌入邏輯結構樹。 + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +呼叫 `setTagDocumentStructure(true)` 即是**啟用 PDF 標記**的開關。設定為 true 時,函式庫會建立一個與視覺版面相對應的標記樹,使輔助技術能讀取 PDF。 + +> **注意:** 這是**如何建立已標記的 PDF**的最簡單方式。若需更細緻的控制(例如設定語言或自訂標記),可探索 `pdfOptions.setTagLanguage("en-US")` 與 `pdfOptions.setTagStructureTreeRoot(...)`。 + +--- + +## 步驟 3:儲存可存取的 PDF + +最後,我們使用剛剛設定的選項將文件寫入磁碟。 + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +當 `doc.save` 完成後,你會在 `output` 資料夾中找到 `accessible.pdf`。在 Adobe Acrobat 中開啟,前往 **File → Properties → Description → Tags**,即可看到已填充的標記樹。 + +--- + +## 如何為 PDF 加上可存取性標記 – 超越基礎 + +上述的三步程式碼已**將可存取性標記加入 PDF**,但實務文件通常需要更多精緻的處理。以下列出幾項可加入的增強功能: + +### 1. 設定文件語言 + +螢幕閱讀器會使用語言屬性正確發音文字。 + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. 提供標題與主旨 + +中繼資料可協助輔助工具在使用者開啟檔案前提供上下文資訊。 + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. 為圖片加入替代文字標記 + +若嵌入圖片,必須提供 `alt` 描述。 + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. 標記表格標頭 + +表格若未標記標頭列,常會讓讀者感到困惑。 + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +這些額外步驟讓你的 PDF 不僅在*技術上*已標記,更真正對多元讀者**可存取**。 + +--- + +## 啟用 PDF 標記時的常見陷阱 + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Acrobat 中缺少標記 | `setTagDocumentStructure` 保持為 `false` | 確保呼叫 `pdfOptions.setTagDocumentStructure(true)`。 | +| 閱讀順序錯誤 | 複雜版面未明確標記 | 使用 `pdfOptions.setTagStructureTreeRoot(...)` 定義自訂順序。 | +| 圖片被讀為「image」且無說明 | 未設定替代文字 | 呼叫 `image.getAlternativeText().setValue("...")`。 | +| 語言未被辨識 | 未設定 `setTagLanguage` 或語系錯誤 | 提供 BCP‑47 語言代碼(例如 `en-US`、`fr-FR`)。 | + +--- + +## 驗證結果 – 期待的情況 + +執行程式後,於 Adobe Acrobat Reader 開啟 `output/accessible.pdf`: + +1. **標記面板** (`View → Show/Hide → Navigation Panes → Tags`) 應顯示類似 `/Document → /Part → /Sect → /Para` 的層級結構。 +2. **閱讀順序** 應符合視覺流程(先是文字,接著是圖片)。 +3. **螢幕閱讀器**(NVDA、VoiceOver)會朗讀「Hello, accessible PDF!」而非僅「Page 1」。 + +若上述任一項缺失,請再次檢查上述步驟——尤其是 `setTagDocumentStructure` 的呼叫。 + +--- + +## 完整可執行範例(直接複製貼上) + + + +## 相關教學 + +- [從 Word 建立可存取 PDF – 轉換為 PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [從 DOCX 建立可存取 PDF – 完整指南](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [如何使用 Aspose.Words for Java 將文件另存為 PDF](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/hongkong/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..0eaa99f696 --- /dev/null +++ b/words/hongkong/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-26 +description: 在使用 Aspose.Words for Java 將 docx 轉換為 markdown 時,將圖片嵌入為 base64。學習如何將 Word + 轉換為 markdown、將 Word 儲存為 markdown,以及處理圖片。 +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: zh-hant +og_description: 在使用 Aspose.Words for Java 將 docx 轉換為 markdown 時,將圖片嵌入為 base64。完整指南教您將 + Word 轉換為 markdown 並將 Word 儲存為 markdown。 +og_title: 將 DOCX 轉換為 Markdown 時以 Base64 嵌入圖片 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: 將圖像以 Base64 嵌入於 DOCX 轉換為 Markdown 時 +url: /zh-hant/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在將 DOCX 轉換為 Markdown 時以 Base64 嵌入圖像 + +有沒有想過在 **將 docx 轉換為 markdown** 時 **以 base64 嵌入圖像**?你並不是唯一有此疑問的人——開發者常常詢問如何在不處理分離檔案的情況下,將圖像直接內嵌。好消息是 Aspose.Words for Java 讓這變得非常簡單:你可以將 Word 文件轉換為 Markdown,並自動將每張圖片以 Base64 字串嵌入。 + +在本教學中,我們將完整示範整個流程——從載入包含圖片的 `.docx`、設定負責處理的 `MarkdownSaveOptions` 回呼,到最後將結果儲存為乾淨的 `.md` 檔案。完成後,你將清楚知道如何 **convert word to markdown**、**convert images to base64**,以及 **save word as markdown**,且不會留下零散的圖片資料夾。全程不需外部工具或手動後處理,只要一段純 Java 程式碼即可直接套用於任何專案。 + +## 您需要的條件 + +- **Java 17**(或任何較新的 JDK)——程式碼使用 lambda 語法,若使用較舊版本可自行調整。 +- **Aspose.Words for Java** 函式庫(截至 2026 年的最新版本)。將 Maven 依賴或 JAR 加入 classpath。 +- 一個包含至少一張圖片的 **DOCX** 範例檔案。 +- 任意 IDE 或簡易文字編輯器——Visual Studio Code、IntelliJ IDEA,甚至 `vim` 都可以。 + +如果你已經備妥上述環境,太好了——直接進入下一步吧。 + +## Step 1: Load the Word Document + +首先,我們建立指向來源檔案的 `Document` 實例。無論是 **convert docx to markdown**,或是僅僅讀取檔案做其他用途,這一步都是相同的。 + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **為什麼這很重要:** `Document` 物件是所有 Aspose 操作的入口點。它保存了完整的 Word 結構——包括圖片、表格與樣式——因此稍後的回呼才能檢查每一個資源。 + +## Step 2: Create MarkdownSaveOptions and Register a Resource‑Saving Callback + +魔法就藏在 `MarkdownSaveOptions` 裡。透過掛載 `IResourceSavingCallback`,我們即可自行決定每個外部資源(例如圖片)如何寫出。 + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### 為什麼使用 `setSaveToMemory(true)`? + +當 `saveToMemory` 為 true 時,Aspose 會將圖片位元組寫入記憶體串流,而不是寫入檔案。Markdown 匯出器隨後會將該串流轉換為 Base64 字串,直接插入 Markdown 圖片標籤中: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +這就是 **embed images as base64** 的核心。 + +## Step 3: Save the Document as Markdown + +現在回呼已設定完畢,最後只要呼叫 `save` 即可。此時我們真正執行 **convert word to markdown**,同時因為回呼的緣故,也完成 **convert images to base64**。 + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **結果:** `out.md` 內的 Markdown 文字每張圖片皆以 `data:` URI 形式呈現。磁碟上不會產生額外的圖片檔案,資料夾保持整潔。 + +## Step 4: Verify the Output and Common Pitfalls + +在任意 Markdown 檢視器(VS Code、GitHub,或靜態網站產生器)中開啟產生的 `out.md`,你應該會看到類似以下的內容: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Troubleshooting Checklist + +| 問題 | 可能原因 | 解決方法 | +|------|----------|----------| +| 圖像顯示為斷開的連結 | `setSaveToMemory` 被遺漏 | 確保在回呼中加入 `args.setSaveToMemory(true);` | +| Base64 字串被截斷 | 輸出檔案編碼不匹配 | 使用 UTF‑8(Aspose 的預設)儲存 Markdown | +| 檔名不符合預期 | `setKeepResourceOriginalName(true)` | 將其設為 `false` 以強制使用自訂命名邏輯 | + +## Step 5: Advanced Variations (Optional) + +### Convert Only Selected Images + +如果只想嵌入特定圖片(例如大於 100 KB 的),可以加入大小檢查: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Use a Different Image Format + +`ResourceSavingArgs` 會提供原始位元組,你可以在嵌入前將 JPEG 重新編碼為 PNG——當目標 Markdown 讀者偏好 PNG 時相當有用。 + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +這些調整說明了在 **convert docx to markdown** 時,**embed images as base64** 方法的彈性與可擴充性。 + +## Conclusion + +你剛剛學會了如何在使用 Aspose.Words for Java 時 **embed images as base64**,同時 **convert docx to markdown**。只要簡單掛載一個 `IResourceSavingCallback`,函式庫就會完成所有繁重工作:它 **convert word to markdown**、**convert images to base64**,最後只需一次 `save` 呼叫即可 **save word as markdown**。 + +隨意嘗試不同的圖片過濾規則、切換為 HTML 輸出,或將此步驟與靜態網站產生器串接。相同的模式同樣適用於其他格式(HTML、EPUB),因此只要需要內嵌資源的地方,都可以重複使用此回呼。 + +**接下來的步驟:** +- 探索 `HtmlSaveOptions`,實作 HTML‑with‑Base64 圖片。 +- 結合 CI 流程,自動化文件產生。 +- 若需要更細緻的轉換控制,可深入研究 Aspose 的 `DocumentVisitor`。 + +祝開發順利,享受乾淨、完整的 Markdown 檔案吧! + +## 相關教學 + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/hongkong/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..7463d7c511 --- /dev/null +++ b/words/hongkong/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: 使用 Java 與 Aspose.Words 匯出 docx 為 txt。了解如何將 docx 轉換成文字、保留 Unicode,並在幾個步驟內將 + Word 匯出為 txt。 +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: zh-hant +og_description: 在 Java 中將 docx 匯出為 txt。本教學示範如何將 docx 轉換為文字,保留純文字 Unicode,並高效地將 Word + 匯出為 txt。 +og_title: 使用 Java 將 docx 匯出為 txt – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: 使用 Java 將 docx 匯出為 txt – 完整程式設計指南 +url: /zh-hant/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Java 匯出 docx 為 txt – 完整程式指南 + +曾經需要 **export docx to txt** 但擔心會遺失特殊字元嗎?你並非唯一遇到此問題的人。當你將 Word 文件轉換為純文字檔時,Unicode 符號、表格,甚至簡單的格式都可能像魔法般消失。 + +在本指南中,我們將示範如何使用 Aspose.Words for Java 可靠地 **export docx to txt**,保留每個 Unicode 字形並讓表格版面保持可讀。完成後,你還會知道如何 **convert docx to text**、**convert word to text**,甚至 **export word as txt**,全程順暢無礙。 + +## 本教學涵蓋內容 + +* 在 Java 專案中設定 Aspose.Words +* 載入 DOCX 檔案並為純文字輸出做準備 +* 透過 `TxtSaveOptions` 設定 **plain text unicode** 支援 +* 可選的技巧讓表格在產生的 `.txt` 檔中仍保持可讀性 +* 儲存檔案並驗證輸出結果 + +不需要外部腳本,也不需要神祕的指令列工具——只要純 Java 程式碼,就能直接放入任何 Maven 或 Gradle 專案。 + +> **為何在意?** 純文字檔輕量、適合版本控制,且非常適合搜尋索引或下游處理流程。如果你曾嘗試 `cat` 一個 Word 檔卻只得到亂碼,這篇教學將解決這個問題。 + +--- + +## Export docx to txt – 概觀 + +在深入程式碼之前,我們先釐清術語。**Export docx to txt** 指的是將 Microsoft Word 的 `.docx` 套件內容寫入簡單的 `.txt` 檔案。與 PDF 轉換不同,文字匯出會去除樣式,但仍可保留換行、段落標記,且只要設定得當,還能保留 Unicode 字元(例如表情符號、重音字母或亞洲文字)。 + +Aspose.Words 讓這件事變得輕鬆,因為它抽象化了 Word 檔案格式,並提供 `TxtSaveOptions` 類別讓你自行決定編碼、表格處理方式等。 + +### 前置條件 + +* Java 11 或更新版本(API 亦支援 Java 8+,但此處假設使用較新的 JDK) +* Aspose.Words for Java JAR(可從 Maven Central 取得) +* 一個包含多種 Unicode 字元的範例 `unicode.docx` 檔案,例如「こんにちは」、「😊」以及一個簡易表格 + +只要具備上述條件,就可以開始了。 + +--- + +## Step 1: Load the DOCX File (Convert docx to text) + +首先必須將來源文件讀入記憶體。這就是 **convert docx to text** 流程正式開始的地方。 + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*為何重要:* `Document` 是 Aspose.Words 對 Word 檔案的表示。載入後即可存取所有段落、表格,甚至隱藏元素。如果找不到檔案,Aspose 會拋出明確的 `FileNotFoundException`,讓你立即知道問題所在。 + +--- + +## Step 2: Configure TxtSaveOptions for Unicode (Plain text unicode) + +純文字檔只是位元組串流,因此必須告訴 Java 使用哪種字元集。UTF‑8 是 **plain text unicode** 的事實標準,因為它能編碼所有 Unicode 代碼點。 + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **小技巧:** 若省略 `setEncoding` 呼叫,Aspose 會預設使用平台的預設字元集,在許多 Windows 機器上是 Windows‑1252。該預設會悄悄丟棄「ß」或「—」等字元。 + +--- + +## Step 3: Preserve Table Layout (Optional, but handy for readability) + +當你 **export word as txt** 時,表格通常會被壓平成單行文字,導致難以閱讀。Aspose.Words 提供簡單的旗標來保留視覺結構。 + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*何時使用:* 若來源 DOCX 包含發票、排程或任何格狀資料,啟用 `PreserveTableLayout` 會插入 Tab 與換行,使產生的檔案仍類似表格。若不需要此功能,可省略該行以取得更緊湊的輸出。 + +--- + +## Step 4: Save the Document as Plain‑Text (Export word as txt) + +現在重任已完成——只要把位元組寫入磁碟即可。 + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +執行程式後會在同一資料夾產生 `plain.txt`。使用任何文字編輯器(Notepad++、VS Code,甚至終端機的 `cat`)開啟,你會看到: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +注意日文問候語與笑臉表情仍然存活,且表格因 `PreserveTableLayout` 而保有欄位。這就是一次乾淨的 **export docx to txt**。 + +--- + +## Step 5: Verify the Output (Convert word to text sanity check) + +快速的驗證可防止靜默的資料遺失。以下提供幾種確認你確實 **convert word to text** 正確的方法: + +1. **Checksum 比對** – 計算 `.txt` 檔在往返轉換(txt → docx → txt)前後的 SHA‑256 雜湊,確保內容穩定。 +2. **搜尋 Unicode 標記** – 使用 `grep` 或 IDE 的全域搜尋,找出「😊」等字元。 +3. **在多個編輯器中開啟** – 某些舊版 Windows Notepad 仍會在沒有 BOM 的情況下誤讀 UTF‑8;在 VS Code 中開啟即可驗證編碼正確。 + +若上述任一檢查失敗,請再次確認已加入 `saveOptions.setEncoding(StandardCharsets.UTF_8)`,且來源 DOCX 確實包含 Unicode 文字。 + +--- + +## Common Pitfalls & How to Avoid Them + +| 問題 | 為何會發生 | 解決方式 | +|------|------------|----------| +| **字元遺失** | 系統預設字元集(例如 Windows‑1252)會捨棄非 ASCII 符號。 | 透過 `saveOptions.setEncoding` 明確設定 UTF‑8。 | +| **表格變成單行** | `PreserveTableLayout` 預設為 `false`。 | 呼叫 `saveOptions.setPreserveTableLayout(true)`。 | +| **找不到檔案** | 路徑錯誤或缺乏讀取權限。 | 使用絕對路徑或 `Paths.get(...)`,並加入適當的例外處理。 | +| **大型文件效能下降** | 整個文件一次載入記憶體。 | 若只需特定區段,可使用 `DocumentBuilder` 以分段方式串流處理。 | + +--- + +## Bonus: Exporting Multiple DOCX Files in a Batch + +如果需要為整個資料夾 **convert docx to text**,只要將邏輯包在迴圈中: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +此程式碼片段會為目錄下的每個檔案 **export docx to txt**,為你省下大量手動操作的時間。 + +--- + +## Conclusion + +你已學會如何使用 Java **export docx to txt**,確保每個 Unicode 字元完整保留,表格保持可讀,且整個流程可重複執行。只要為 `TxtSaveOptions` 設定 UTF‑8,並視需求啟用表格版面保留,即可可靠地 **convert docx to text**、**convert word to text**,以及 **export word as txt**,供任何下游工作流程使用。 + +準備好接受下一個挑戰了嗎?試著匯出為其他純文字格式,如 markdown(`.md`)或 CSV,或探索 Aspose.Words 的 PDF 轉換功能。明確的編碼設定、版面保留與徹底的驗證,這些原則在所有情境下皆適用。 + +祝程式開發順利,願你的文字檔永遠保持 Unicode 豐富! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="匯出 docx 為 txt 流程圖"} + +## Related Tutorials + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/hongkong/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..b6266eac64 --- /dev/null +++ b/words/hongkong/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-05-26 +description: 使用 Aspose.Words Java 將文件儲存為 PDF 並為 PDF 加入可及性。學習將 docx 轉換為 PDF、標記水平線,並確保符合 + PDF/UA‑2 標準。 +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: zh-hant +og_description: 使用 Aspose.Words Java 將文件另存為 PDF,並為 PDF 加入可存取性。逐步教學,將 docx 轉換為 PDF,並為水平線加上標記,以符合 + PDF/UA‑2 標準。 +og_title: 使用 Aspose.Words Java 將文件儲存為 PDF – 輕鬆實現無障礙 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: 使用 Aspose.Words Java 將文件另存為 PDF – 完整的無障礙指南 +url: /zh-hant/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將文件另存為 PDF(使用 Aspose.Words Java)– 完整無障礙指南 + +有沒有想過如何 **save document as PDF** 同時保持對螢幕閱讀器的可及性?你並不孤單。許多開發者需要 *convert docx to pdf*,且仍須符合 PDF/UA‑2 標準,特別是當來源文件包含必須正確標記的水平線時。在本教學中,我們將逐步說明如何使用 Aspose.Words for Java **save document as PDF**,自動 **add accessibility to PDF**,並確保每條水平線都 **tagged** 為 artifact。 + +我們將從一個全新的 Java 專案開始,載入已包含水平線的 DOCX,設定 PDF 儲存選項以符合 PDF/UA‑2 標準,最後輸出完整的可及性 PDF。完成後,你將能夠 **save document as pdf**,且有信心通過可及性檢查。 + +## 前置條件 + +- 安裝 Java 8 或更新版本(本教學在 JDK 17 上測試)。 +- Maven 3.6+(或你偏好的 Gradle)用於管理相依性。 +- 有效的 Aspose.Words for Java 授權(免費試用版可用,但授權可移除評估浮水印)。 +- 一個 DOCX 檔案(`input.docx`),其中至少包含一條水平線——想像在 Word 中加入的簡單分隔線。 + +> **專業提示:** 若手頭沒有 DOCX,只需建立一個新的 Word 文件,輸入幾段文字,插入 *Insert → Horizontal Line*,另存為 `input.docx`,並放置於你選擇的資料夾中。 + +## 步驟 1:設定 Maven 專案 + +首先,建立一個新的 Maven 專案(或在現有專案中加入)。`pom.xml` 需要加入 Aspose.Words 的相依性: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **為什麼這很重要:** 加入 `aspose-words` 套件是 *convert docx to pdf* 的第一步。若未加入,編譯器將無法辨識 `Document`、`PdfSaveOptions` 以及其他關鍵類別。 + +## 步驟 2:載入包含水平線的來源 DOCX + +現在我們將編寫一個小型的 Java 類別來載入 DOCX。這正是 **tag horizontal rules** 的起點——Aspose.Words 會自動將水平線視為帶有邊框的段落,但我們會讓 PDF/UA 引擎負責標記。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +請注意,我們尚未儲存任何內容——我們僅 **loading** 這個 DOCX,這是 *convert docx to pdf* 的前半段。`Document` 物件現在已包含所有 Word 內容,包括你插入的任何水平線。 + +## 步驟 3:設定 PDF 儲存選項以符合 PDF/UA‑2 標準 + +**add accessibility to PDF** 的關鍵在於 `PdfSaveOptions`。將相容等級設為 `PDF_UA_2` 後,Aspose.Words 會: + +1. 標記結構元素(標題、表格等)。 +2. 標記裝飾性元素——例如水平線——為 *artifacts*,使螢幕閱讀器忽略它們。 +3. 插入必要的 PDF/UA 中繼資料。 + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **為什麼要設定相容性?** 若未使用 `PDF_UA_2`,產生的 PDF 仍可能可閱讀,但無法通過自動化的可及性驗證工具。**tag horizontal rules** 的需求會自動滿足,因為在開啟相容性旗標時,PDF/UA 會將其視為 *artifacts*。 + +## 步驟 4:將文件另存為 PDF + +現在我們終於 **save document as pdf**。這一行程式碼完成了繁重的工作——將 DOCX 轉換、套用可及性標記,並寫入磁碟。 + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +執行此類別(`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`),你會看到確認訊息。於 Adobe Acrobat 開啟產生的 `ua_compliant.pdf`,檢查 **File → Properties → Description → PDF/A, PDF/UA**——應會顯示 “PDF/UA‑2”。 + +### 預期輸出 + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +開啟 PDF,你會注意到: + +- 文件文字可選取且可搜尋。 +- 水平線對螢幕閱讀器是不可見的(被視為 artifact)。 +- PDF 通過基本的 PDF/UA 驗證工具(例如 PAC 3)。 + +## 步驟 5:驗證可及性 – 快速檢查清單 + +即使 Aspose.Words 已完成大部分工作,驗證輸出仍是良好實踐。 + +| 檢查項目 | 驗證方式 | +|-------|----------------| +| **Document title** | Open Acrobat → File → Properties → Title field (should match `pdfOptions.setTitle`). | +| **Artifact tagging** | Use Acrobat’s “Reading Order” tool. Horizontal rules should appear as *Artifact* (gray). | +| **Logical reading order** | Run the “Accessibility Checker” in Acrobat; ensure no structural errors. | +| **Tagged PDF** | In Acrobat, look under “Tags” panel – you should see a hierarchy (Document → Section → Paragraph, etc.). | +| **PDF/UA compliance** | Acrobat will display “PDF/UA‑2” under the “Standards” tab. | + +如果上述任一檢查失敗,請再次確認你使用的是最新的 Aspose.Words 版本,且已正確套用 `setCompliance(PdfCompliance.PDF_UA_2)`。 + +## 常見陷阱與避免方法 + +1. **Missing License** – 試用版會加入浮水印,可能破壞 PDF/UA 驗證。請在 `main` 中盡早套用授權: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` 會中止轉換。請使用絕對路徑,或將 DOCX 放在專案根目錄,並以 `new File("input.docx").getAbsolutePath()` 參照。 +3. **Using Older Aspose Version** – PDF/UA 支援於 22.9 版加入。請升級至最新版本以避免缺少功能。 +4. **Horizontal Rule as Image** – 若你將線條插入為圖片而非 Word 原生水平線,Aspose 會將其視為普通圖片,而非 artifact。請改用 Word 內建的 *Horizontal Line* 以正確標記。 + +## 擴充解決方案 – 若需要更多功能? + +- **Custom Tags**:若有其他裝飾性元素(例如裝飾圖示),可使用 `PdfSaveOptions.setArtifactTaggingEnabled(true)` 手動將其標記為 artifact。 +- **Multiple Documents**:遍歷資料夾中的 DOCX 檔案並批次轉換,為提升效能可重複使用相同的 `PdfSaveOptions` 實例。 +- **Adding a Language Tag**:對於多語言 PDF,設定 `pdfOptions.setLanguage("en-US")` 可協助輔助技術選擇正確的語音。 + +## 完整範例(全部程式碼) + +以下是完整、可執行的 Java 程式。將其複製貼上至 IDE,調整路徑後執行。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +執行程式,開啟產生的 PDF,即可得到乾淨且具可及性的檔案,適合發佈。 + +## 結論 + +我們剛剛示範了如何使用 Aspose.Words for Java **save document as pdf**,同時自動 **add accessibility to pdf** 並將 **tag horizontal rules** 為 artifact。重點如下: + +- 使用 `PdfSaveOptions` 並設定 `PDF_UA_2` 相容性,以符合可及性標準。 +- 載入 DOCX 後呼叫 `doc.save(..., pdfOptions)` 即可完成 **convert docx to pdf**。 +- 水平線會自動處理——不需額外程式碼,即滿足 **tag horizontal rules** 的需求。 +- 此方法完全符合 **aspose convert docx pdf**,使用最新的函式庫版本,並產生可驗證的 PDF。 + +準備好迎接下一個挑戰了嗎?試著加入自訂中繼資料、嵌入字型,或批次處理整個 DOCX 資料夾。這些延伸功能皆建立在此基礎之上。 + +對 PDF/UA 相容性、授權或處理其他 Word 元素有任何問題嗎?留下評論或查閱 Aspose 官方文件——裡面有豐富的範例可供參考。祝開發愉快,盡情打造可及性的 PDF! + +![使用 Aspose.Words Java 儲存文件為 PDF – 可及性 PDF 範例](placeholder-image.png "使用 Aspose.Words Java 儲存文件為 PDF – 可及性 PDF 範例") + +## 相關教學 + +- [如何使用 Aspose.Words for Java 儲存文件為 PDF](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [如何使用 Aspose.Words for Java 將 Word 轉換為 PDF](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – 在 Java 中將 DOCX 轉換為 PDF](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/hongkong/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..88479ed9ca --- /dev/null +++ b/words/hongkong/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-26 +description: 將 Word 儲存為 Markdown,並探索如何使用 Aspose.Words for Java 將數學方程式匯出為 LaTeX。只需幾行程式碼即可將 + Word 方程式轉換為 LaTeX。 +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: zh-hant +og_description: 將 Word 另存為 Markdown,並學習如何使用 Aspose.Words for Java 將數學公式匯出為 LaTeX。完整且可執行的指南。 +og_title: 將 Word 另存為 Markdown – 用 Java 匯出數學為 LaTeX +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: 將 Word 另存為 Markdown – 使用 Java 匯出數學至 LaTeX +url: /zh-hant/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 Word 儲存為 Markdown – 使用 Java 匯出數學為 LaTeX + +曾經需要 **將 Word 儲存為 Markdown**,但擔心你的公式會變成一團亂碼嗎?你並不孤單。在本指南中,我們將一步步說明 **如何匯出數學**,從 `.docx` 檔案直接匯出數學為 LaTeX,同時讓文件的其餘部分保持乾淨的 Markdown。 + +我們將涵蓋從設定 Aspose.Words 函式庫到驗證最終 `out.md` 檔案的全部內容。完成後,你將能夠在一次方法呼叫中 **將 Word 公式轉換為 LaTeX**,並了解使轉換可靠的細微差異。 + +--- + +## 需要的工具 + +- **Java 8+** – 程式碼可在任何近期的 JDK 上執行。 +- **Aspose.Words for Java** – 可使用 Maven/Gradle 依賴或自行下載 JAR 進行手動設定。 +- 一個包含至少一個 Office Math 公式的 Word 文件(`math.docx`)。 +- 任意 IDE 或純粹使用 `javac`/`java` 命令列皆可,依你習慣而定。 + +如果你已經具備上述條件,太好了。若尚未安裝,下一節將說明如何將函式庫加入你的專案。 + +--- + +## 將 Word 儲存為 Markdown – 步驟 1:將 Aspose.Words 加入專案 + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose 提供免費的臨時測試授權。將 `license.xml` 檔案放入 resources 資料夾,並在載入任何文件前呼叫 `License license = new License(); license.setLicense("license.xml");`。 + +依賴解決後,即可開始撰寫轉換程式碼。 + +--- + +## 如何將數學公式匯出為 LaTeX + +`MarkdownSaveOptions` 負責主要工作。將其 `OfficeMathExportMode` 設為 `LATEX` 後,所有 Office Math 物件都會以 LaTeX 片段的形式呈現在 Markdown 輸出中。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### 為什麼這樣可行 + +- **`Document`** 為 Aspose 的入口點;它抽象化 `.docx` 檔案,讓你能存取每個節點,包括公式。 +- **`MarkdownSaveOptions`** 告訴函式庫 *如何* 輸出。預設行為是將公式渲染為圖片,這與文字為本的格式目的相違背。 +- **`OfficeMathExportMode.LATEX`** 強制引擎將每個 `OfficeMath` 節點轉換為相應的 LaTeX,Markdown 解析器(如 GitHub 或 Jekyll)結合 MathJax 外掛即可正確渲染。 + +--- + +## 將 Word 公式轉換為 LaTeX – 步驟 2:驗證 Markdown 輸出 + +執行程式後,開啟 `out.md`。你應該會看到類似以下內容: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** LaTeX 片段會以 `$…$` 包住以表示行內數學,或以 `$$…$$` 包住以表示區塊數學。這是大多數靜態網站生成器在啟用 MathJax 時所支援的標準語法。 + +如果你希望公式僅以行內形式呈現,可進一步調整 `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx 轉 markdown LaTeX – 步驟 3:邊緣案例與常見陷阱 + +| 情況 | 需注意事項 | 解決方式 | +|-----------|-------------------|-----| +| **複雜的巢狀公式** | Aspose 可能會輸出多餘的 `{}`,而某些解析器會將其視為字面字符。 | 使用簡單的正則表達式將 `{{` 合併為 `{` 以後處理 Markdown。 | +| **目標網站缺少 MathJax** | 公式會以原始 LaTeX 代碼顯示。 | 在 HTML 模板中加入 ``。 | +| **大型文件** | 因一次載入整個文件,記憶體使用量會急升。 | 使用 `LoadOptions.setLoadFormat(LoadFormat.DOCX)`,若遇到 `OutOfMemoryError`,可考慮分批處理頁面。 | +| **未設定授權** | 會收到警告,且輸出可能會有浮水印。 | 如同上述 Maven 小技巧,在 `main` 早期載入授權。 | + +--- + +## 將 Word 儲存為 Markdown – 完整範例程式 + +以下是一個獨立的類別,你可以直接複製貼上到任何 Java 專案中。只需將 `YOUR_DIRECTORY` 替換為你的檔案路徑。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +執行程式 (`java MathToLatexMarkdown`) 後,你會在主控台看到成功訊息。於任意編輯器開啟 `out.md`——公式應為乾淨的 LaTeX 片段,已可直接渲染。 + +--- + +## 預期輸出快照 + +![使用 LaTeX 公式的 Word 儲存為 Markdown 輸出](https://example.com/images/markdown-latex-output.png "使用 LaTeX 公式的 Word 儲存為 Markdown 輸出") + +*此圖片顯示產生的 Markdown 片段,其中公式 `\int_{a}^{b} f(x)\,dx` 被包在 `$$` 中。* + +--- + +## 結論 + +我們剛剛示範了如何 **將 Word 儲存為 Markdown**,同時保留每個 Office Math 公式為原生 LaTeX。關鍵步驟是使用 `OfficeMathExportMode.LATEX` 設定 `MarkdownSaveOptions`,這使得一般的 Word 轉 Markdown 流程變成完整支援數學的轉換工具。 + +現在你可以: + +1. **如何匯出數學**:從任何 `.docx` 檔案匯出而不失真。 +2. **將 Word 公式轉換為 LaTeX**:適用於靜態網站生成器、文件或學術部落格。 +3. 將此方法擴展至批次處理多個檔案、整合 CI 流程,或甚至構建小型 Web 服務。 + +如果你對下一步感到好奇,可以嘗試將此與 **docx to markdown latex** 結合,以處理大量圖片的文件,或探索 Aspose 的 `HtmlSaveOptions` 以產生適合 Web 的 HTML 版本。可能性無窮無盡——盡情實驗、挑戰極限,然後與社群分享你的發現。 + +有任何問題或遇到無法正確渲染的複雜公式嗎?在下方留言,我們祝你編程愉快! + +## 相關教學 + +- [如何從 Word 匯出 LaTeX:將 DOCX 轉為 Markdown 並儲存為 PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [將 docx 轉為 markdown – 使用 Aspose.Words 匯出數學公式為 LaTeX](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [如何使用 Aspose.Words for Java 將 Word 轉換為 PDF](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/hongkong/java/document-loading-and-saving/_index.md index 5b26b8e3d1..8edc2f3e7f 100644 --- a/words/hongkong/java/document-loading-and-saving/_index.md +++ b/words/hongkong/java/document-loading-and-saving/_index.md @@ -115,6 +115,8 @@ Aspose.Words for Java 讓您輕鬆 **從 Word 儲存圖像**,同時提供強 ### [修復損壞的 docx – 完整指南:修復與處理文件](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [開啟損壞的 Word 文件 – 在 Java 中設定復原模式](./open-corrupted-word-document-set-recovery-mode-in-java/) + ### [使用 Aspose.Words for Java 捕獲字體替換警告 – 完整指南](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## 常見問題 diff --git a/words/hongkong/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/hongkong/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..eb3fbdd9cd --- /dev/null +++ b/words/hongkong/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: 使用 Aspose.Words 在 Java 中開啟受損的 Word 檔案。了解如何設定復原模式,並可靠地修復受損的 Word 檔案。 +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: zh-hant +og_description: 使用 Aspose.Words 在 Java 中開啟受損的 Word 文件。本指南說明如何設定復原模式,並有效修復受損的 Word + 檔案。 +og_title: 開啟損壞的 Word 文件 – 在 Java 中設定復原模式 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: 開啟損毀的 Word 文件 – 在 Java 中設定復原模式 +url: /zh-hant/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 開啟損毀的 Word 文件 – 在 Java 中設定復原模式 + +有沒有試過開啟損毀的 Word 文件,結果程式因例外而當機?你並不孤單——那些損壞的 .docx 檔案真的會讓人頭疼。好消息是 Aspose.Words for Java 提供了細緻的控制,讓你 **開啟損毀的 Word 文件** 時不會讓應用程式崩潰,甚至可以自行決定是顯示警告、靜默復原,或是直接拒絕。 + +在本教學中,我們將逐步說明完整流程:從建立正確的 `LoadOptions`、選擇適當的 **設定復原模式** 值,最後確認文件確實已載入。完成後,你將知道 **如何以程式方式復原損毀的 Word 檔案**,不需要手動複製貼上。 + +> **你需要的環境** +> * Java 8 或更新版本(API 亦支援 Java 11) +> * Aspose.Words for Java 23.9(或最新版本) +> * 一個範例損毀的 .docx 檔案——如果手頭沒有,可將任何有效檔案重新命名來模擬損毀 + +讓我們開始吧。 + +## 開啟損毀的 Word 文件 – 步驟概覽 + +以下是我們將實作的高階流程: + +1. **建立 `LoadOptions`** – 這個物件告訴 Aspose.Words 在遇到問題時的行為。 +2. **設定復原模式** – 選擇 `RECOVER_WITH_WARNINGS`、`RECOVER_WITHOUT_WARNINGS` 或 `REJECT_CORRUPTED`。 +3. **使用已設定的選項載入文件**。 +4. **驗證** 載入是否成功(例如,印出頁數)。 + +每個步驟都會詳細說明,並提供可直接複製貼上到 IDE 的程式碼片段。 + +## 為不同情境設定復原模式 + +Aspose.Words 在 `LoadOptions.RecoveryMode` 中定義了三種復原策略: + +| 模式 | 行為說明 | 使用時機 | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | 嘗試載入文件,並在主控台顯示任何問題的警告。 | 想要了解 *發生了什麼* 而不立即中止時。 | +| `RECOVER_WITHOUT_WARNINGS` | 靜默修復可修復的部分,且不顯示警告。 | 需要保持日誌乾淨的正式環境。 | +| `REJECT_CORRUPTED` | 一旦偵測到損毀即拋出例外。 | 必須快速失敗的嚴格驗證流程。 | + +正確選擇模式即是 **設定復原模式** 的核心。在大多除錯情境下,`RECOVER_WITH_WARNINGS` 是最佳選擇,因為它會告訴你哪些部分被修復了。 + +## 使用 Aspose.Words 復原損毀的 Word 檔案 + +以下是一個 **完整、可執行的 Java 程式**,示範整個流程。只要將它放入 `RecoveryModeDemo.java`,調整路徑後執行即可。 + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### 為什麼每一行都很重要 + +* **`LoadOptions loadOptions = new LoadOptions();`** – 若沒有這個物件,Aspose.Words 會使用預設的復原行為,預設會 *拒絕* 損毀的檔案。建立它即可掛鉤自訂行為。 +* **`setRecoveryMode(...)`** – 這就是 **設定復原模式** 的呼叫,決定警告是否顯示、是否隱藏,或是否拋出例外。 +* **`new Document(path, loadOptions);`** – 建構子接受我們剛剛配置好的 `LoadOptions`,因此程式庫從一開始就知道要如何處理損毀的檔案。 +* **`doc.getPageCount()`** – 快速的合理性檢查。如果文件成功載入並回傳頁數,代表你已成功 **如何復原損毀的 Word 檔案**。 +* **`doc.save(...)`** – 雖非必要,但相當實用;你可以將修復後的版本寫回磁碟,以便日後使用。 + +## 處理常見的邊緣案例 + +### 1. 找不到檔案 + +如果路徑錯誤,`Document` 會拋出 `FileNotFoundException`。將載入程式碼包在 try‑catch 區塊,並記錄友善訊息: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. 無法復原的損毀 + +即使使用 `RECOVER_WITH_WARNINGS`,某些結構仍可能無法修復。此時 Aspose.Words 仍會載入可用的部分,但會在主控台顯示類似「Cannot read paragraph properties」的警告。請留意這些訊息,因為它們通常指向需要手動重建的遺失段落或區段。 + +### 3. 大檔案與效能 + +復原會產生少量額外開銷,因為程式庫會先檢測問題一次,再重建一次。對於多 GB 的文件,建議使用串流方式讀取,或提升 JVM 記憶體上限(例如 `-Xmx2g`),以避免 `OutOfMemoryError`。 + +## 專業小技巧 – 讓復原更穩健 + +* **將警告寫入檔案** – 把 `System.err` 重新導向至日誌系統,保留修復紀錄。 +* **復原後再次驗證** – 呼叫 `doc.updatePageLayout();` 後重新檢查頁數;有時版面會在修復斷裂區段後變更。 +* **批次自動復原** – 把示範程式包在迴圈中,處理整個資料夾的損毀檔案,並重複使用相同的 `LoadOptions`。 + +## 結論 + +現在你已完全掌握 **如何以 Aspose.Words for Java 復原損毀的 Word 檔案**。只要建立 `LoadOptions` 實例、將 **設定復原模式** 為符合情境的策略,然後以該選項載入文件,即可安全地 **開啟損毀的 Word 文件** 而不會讓應用程式崩潰。上方的範例程式碼是一個完整、即時可執行的解決方案,會印出頁數,甚至可以儲存清理過的副本。 + +接下來可以嘗試將復原模式改為 `RECOVER_WITHOUT_WARNINGS`,比較主控台輸出,或是實驗載入加密文件(需要透過密碼提供)。 + + +## 相關教學 + +- [Aspose.Words Java:完整的 Word 文件處理指南](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [如何使用 Aspose.Words for Java 將 Word 轉換為 PDF](/words/english/java/document-converting/using-document-converting/) +- [如何使用 Aspose.Words for Java 比較兩個 Word 檔案](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/hongkong/java/document-styling/_index.md index 208128415c..71cdb6c0eb 100644 --- a/words/hongkong/java/document-styling/_index.md +++ b/words/hongkong/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aspose.Words for Java 提供了強大的文件樣式工具,讓開發人員可 了解如何使用 Aspose.Words for Java 套用浮水印和設定頁面配置。帶有原始程式碼的綜合指南。 ### [文檔頁首和頁尾樣式](./document-header-footer-styling/) 在本詳細指南中了解如何使用 Aspose.Words for Java 設定文件頁首和頁尾的樣式。包含逐步說明和原始程式碼。 +### [在 Aspose.Words for Java 中設定預設字體 – 完整指南](./set-default-font-settings-in-aspose-words-for-java-complete/) +了解如何在 Aspose.Words for Java 中設定預設字體,以程式方式統一文件字型樣式。提供原始程式碼範例與步驟說明。 {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hongkong/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/hongkong/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..b696f94fa3 --- /dev/null +++ b/words/hongkong/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: 在 Aspose.Words for Java 中設定預設字型設定,並學習如何僅用幾行程式碼設定字型以及偵測缺少的字型。 +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: zh-hant +og_description: 在 Aspose.Words for Java 中設定預設字型,學習如何設定字型並快速、可靠地偵測缺少的字型。 +og_title: 在 Aspose.Words for Java 中設定預設字型設定 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: 在 Aspose.Words for Java 中設定預設字型設定 – 完整指南 +url: /zh-hant/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Aspose.Words for Java 中設定預設字型設定 – 完整指南 + +有沒有想過在使用 Aspose.Words for Java 載入 Word 文件時,如何 **設定預設字型設定**?你並不孤單。缺少字形會把精緻的報告變成亂碼,及早捕捉字型替換警告可以節省數小時的除錯時間。 + +在本教學中,我們將逐步說明一個簡潔、端到端的範例,**設定預設字型設定**、示範如何以程式方式 **設定字型設定**,以及展示一種可靠的方式在字型缺失導致版面錯亂前 **偵測缺少的字型**。 + +--- + +## 您將學會 + +- 如何使用全新的 `FontSettings` 實例建立 `LoadOptions` 物件。 +- 如何附加一個警告監聽器,以在文件載入期間 **偵測缺少的字型**。 +- 如何載入 DOCX 檔案,同時讓監聽器靜默回報任何替換。 +- 在正式環境中自訂備援字型與處理邊緣案例的技巧。 + +不需要額外的函式庫,也不需要晦澀的設定檔——只要純粹的 Java 與 Aspose.Words 即可。 + +--- + +## 前置條件 + +在開始之前,請確保您已具備: + +1. **Aspose.Words for Java**(版本 23.10 或更新)已加入 classpath。 +2. Java 17(或更新)開發套件——任何現代 JDK 都可。 +3. 一個特意使用您未安裝字型的 DOCX 檔案(例如 *“MissingFont.ttf”*)。 + +如果缺少 Aspose JAR,請從官方 Maven 套件庫取得: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +就這樣——此示範不需要額外安裝字型。 + +--- + +## 步驟 1:建立 LoadOptions 並 **設定預設字型設定** + +我們首先需要一個乾淨的 `LoadOptions` 物件,告訴 Aspose 在遇到未知字型時的行為。透過呼叫 `setFontSettings(new FontSettings())`,我們 **設定預設字型設定**,其起始為空的備援字型清單。 + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **為什麼這很重要:** +> 若未明確設定字型,Aspose 會退回使用系統的預設字型集合,這可能隱藏缺少字型的問題。從全新的 `FontSettings` 實例開始,您即可完整掌控哪些字型被視為有效。 + +--- + +## 步驟 2:附加警告監聽器以 **偵測缺少的字型** + +Aspose 會為每一次的字型替換拋出 `WarningInfo` 物件。透過監聽 `WarningType.FONT_SUBSTITUTION`,我們即可在文件解析時 **偵測缺少的字型**。 + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **專業提示:** 監聽器與載入文件的執行緒相同,幾乎不會產生效能損耗。若需稍後分析警告,可將它們加入 `List`,而非直接印出。 + +--- + +## 步驟 3:使用已設定的選項載入文件 + +現在我們已 **設定字型設定** 並準備好監聽器,只需直接載入檔案。任何缺少的字型都會立即觸發回呼。 + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +如果來源檔案引用了未安裝的字型,您會看到類似以下的輸出: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +該行會精確指出缺少哪個字型以及使用了哪個備援字型——非常適合用於記錄或使用者回饋。 + +--- + +## 步驟 4:繼續正常處理(可選) + +此時文件已完整載入,您可以進行任何想要的操作——編輯、轉換為 PDF,或擷取文字。警告監聽器已完成任務,無需額外檢查。 + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **如果想要自訂備援字型呢?** +> 不必讓 `FontSettings` 為空,您可以加入特定字型: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +現在任何缺少的字型都會被 *Times New Roman* 取代——對大多數西文文件而言是一個可靠的選擇。 + +--- + +## 視覺概覽 + +![說明如何在 Aspose.Words for Java 中設定預設字型設定的圖表](image.png "設定預設字型設定流程圖") + +*Alt text: Aspose.Words for Java 中設定預設字型設定的流程圖。* + +圖表說明了從初始化 `LoadOptions`(我們在此 **設定預設字型設定**)到附加警告監聽器(以 **偵測缺少的字型**),最後載入文件的流程。 + +--- + +## 常見陷阱與避免方法 + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **忘記呼叫 `setFontSettings`** | Aspose 使用系統預設字型,會隱藏缺少的字型。 | 始終建立新的 `FontSettings` 實例並指派給 `LoadOptions`。 | +| **監聽器未觸發** | 在載入文件之後才加入監聽器。 | 在呼叫 `new Document(...)` 之前 *加入* 警告監聽器。 | +| **路徑拼寫錯誤導致 `FileNotFoundException`** | 硬編碼的路徑與作業系統的大小寫敏感性不符。 | 使用 `Paths.get("...").toAbsolutePath()`,或從專案根目錄設定相對路徑。 | +| **多個缺少字型淹沒日誌** | 大型文件可能產生數十條警告。 | 在列印前過濾重複或將訊息彙總至 `Set`。 | + +--- + +## 擴充解決方案 + +若需為整個應用程式 **設定字型設定**,可考慮建立單例 `FontSettings`,並在所有 `LoadOptions` 中重複使用。如此即可維持一致的備援策略,避免重複建立物件。 + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +現在程式碼的任何部分只要呼叫 `FontConfig.getLoadOptions()`,即可立即受惠於相同的 **設定預設字型設定** 邏輯。 + +--- + +## 結論 + +我們已完整說明在 Aspose.Words for Java 中 **設定預設字型設定**、以程式方式 **設定字型設定**,以及在字型破壞輸出前 **偵測缺少的字型** 的所有必要步驟。完整且可執行的範例位於上述程式碼片段,您只需直接貼入 IDE 即可看到警告的實際效果。 + +接下來的步驟?嘗試更換備援字型、實驗不同的文件格式(DOC、RTF、HTML),或將警告收集器整合至監控儀表板。您對 `FontSettings` 操作得越熟練,對產生的文件能精確呈現預期樣貌的信心就越高——不會有意外,也不會出現破碎的字形。 + +有任何問題或遇到棘手的字型替換情況嗎?在下方留下評論,我們會協助您。祝編程愉快! + +## 相關教學 + +- [設定字型備援設定](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [設定字型備援設定](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [設定字型備援設定](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/java/images-shapes/_index.md b/words/hongkong/java/images-shapes/_index.md index 0e07d16680..f0b9e816fa 100644 --- a/words/hongkong/java/images-shapes/_index.md +++ b/words/hongkong/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aspose.Words Java 程式碼教程 ### [建立 Word 文件 Java – 添加帶陰影效果的矩形形狀](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) 示範如何在 Java 中使用 Aspose.Words 建立 Word 文件,並向文件中加入帶陰影效果的矩形形狀。 +### [在 Java Word 文件中建立矩形形狀 – 完整步驟指南](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +提供在 Java 中使用 Aspose.Words 建立矩形形狀的完整步驟說明,涵蓋屬性設定與範例程式碼。 + ## 其他資源 - [Aspose.Words for Java 文檔](https://reference.aspose.com/words/java/) diff --git a/words/hongkong/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/hongkong/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..e13c300dc7 --- /dev/null +++ b/words/hongkong/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,260 @@ +--- +category: general +date: 2026-05-26 +description: 在 Java Word 文件中建立矩形形狀並套用陰影效果。了解如何新增形狀陰影、設定陰影距離,以及儲存檔案。 +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: zh-hant +og_description: 在 Java Word 文件中建立矩形形狀,套用陰影效果,新增形狀陰影,並使用 Aspose.Words 設定陰影距離。 +og_title: 在 Java Word 文件中創建矩形形狀 – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: 在 Java Word 文件中建立矩形形狀 – 完整逐步指南 +url: /zh-hant/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 Java Word 文件中建立矩形形狀 – 完整步驟指南 + +是否曾需要在 Java Word 文件中 **建立矩形形狀**,卻不知從何下手?你並不孤單——許多開發者在程式化產生報表或發票時都會碰到這個問題。在本教學中,我們將一步步說明如何 **建立矩形形狀**、套用精緻的陰影,並微調陰影距離,讓最終效果看起來更專業。 + +我們將使用 Aspose.Words for Java,這是一套功能強大的函式庫,讓你在未安裝 Microsoft Office 的環境下操作 Word 檔案。完成本指南後,你將能在 **create word document java** 專案中 **add shape shadow**、**apply shadow effect**,以及 **set shadow distance**,僅需幾行程式碼。 + +--- + +## 你將建立的內容 + +- 一個包含青色矩形的全新 `.docx` 檔案。 +- 一個模擬真實投影的陰影,具備模糊、角度與部分透明度。 +- 完全可自行調整的陰影與形狀之間的距離。 +- 一個可直接放入任何 Maven 或 Gradle 專案的可執行 Java 類別。 + +不需要外部工具,也不需要手動 UI 操作——全程純程式碼。 + +--- + +## 前置條件 + +- Java 8 或更新版本(程式碼同樣適用於 Java 11、Java 17 等)。 +- Aspose.Words for Java 函式庫(可透過 Maven Central 取得)。 +- 你慣用的 IDE 或文字編輯器(IntelliJ IDEA、Eclipse、VS Code…)。 +- 基本的 Java 語法概念。 + +如果你從未加入過 Maven 相依性,以下提供快速範例: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +現在,讓我們開始吧。 + +--- + +## 步驟 1:在 Word 文件中建立矩形形狀 + +首先,我們需要一個空白文件與 `DocumentBuilder`。把 builder 想像成寫入文件的筆。取得它之後,只要呼叫一次方法即可 **create rectangle shape**。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **為什麼重要:** `insertShape` 方法不只會建立幾何圖形,還會把形狀加入文件的內部集合,讓你可以立即對它進行樣式設定。 + +--- + +## 步驟 2:為形狀套用陰影效果 + +矩形已經出現在頁面上,接下來我們要 **apply shadow effect**。陰影能增加深度,讓形狀看起來像是從頁面上浮起——這種細微的 UI 改善能提升報表的可讀性。 + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **小技巧:** `5.0` 的模糊值在大多數螢幕顯示的文件中看起來最自然。若是列印文件,建議稍微降低數值,以免出現模糊感。 + +--- + +## 步驟 3:設定陰影距離 – 微調位置 + +陰影不只需要模糊,還需要正確的偏移量。這就是我們 **set shadow distance** 的地方。`7.0` 點的距離會產生適度的偏移,既明顯又不會過於突兀。 + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **如果需要更大的偏移該怎麼辦?** 增加數值;想要更緊密的效果則減少。記得距離會與角度共同決定陰影的最終位置。 + +--- + +## 步驟 4:儲存文件 – 永久保存你的成果 + +最後,我們把文件寫入磁碟。將路徑改成你想要存放檔案的位置即可。 + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +執行此類別後會產生 `shadow.docx`,在 Microsoft Word 或 LibreOffice 開啟時,會看到一個青色矩形,帶有 45° 角、偏移 7 點的柔和灰色陰影。 + +--- + +## 完整範例程式碼 + +以下是可直接複製貼上的完整程式碼,已包含所有匯入、註解與最終的 `save` 呼叫。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**預期結果:** 開啟 `shadow.docx` → 你會看到第一頁正中央有一個青色矩形,投射出微妙的灰色陰影,稍微向右下方偏移。陰影的模糊與透明度讓它看起來像自然光照射的效果。 + +--- + +## 常見問題與特殊情況 + +### 「可以使用其他形狀嗎?」 + +當然可以。只要把 `ShapeType.RECTANGLE` 換成 `ShapeType.OVAL`、`ShapeType.LINE` 或其他支援的列舉值,陰影程式碼皆保持不變。 + +### 「如果需要多重陰影怎麼辦?」 + +Aspose.Words 只支援每個形狀單一陰影。若想模擬多重陰影,可複製形狀、分別調整偏移與透明度。 + +### 「LibreOffice 會顯示陰影嗎?」 + +會的——Aspose.Words 產生的是標準 OOXML,LibreOffice 能正確解析。因為渲染引擎不同,陰影外觀可能略有差異,但效果仍會保留。 + +### 「如何把陰影顏色改成符合品牌色調?」 + +只要把 `java.awt.Color.GRAY` 換成任意 `java.awt.Color`,例如 `new java.awt.Color(0, 120, 215)` 即可得到企業藍。 + +--- + +## 圖示說明 + +![在 Java Word 文件中建立矩形形狀的示意圖](https://example.com/images/rectangle-shadow.png) + +*替代文字:**create rectangle shape** 示意圖,顯示在 Word 文件中帶有灰色投影的青色矩形。 + +--- + +## 重點回顧與後續步驟 + +我們已說明如何使用 Aspose.Words for Java **create rectangle shape**、**apply shadow effect**、**add shape shadow**,以及 **set shadow distance**。此程式碼獨立、可在任何現代 JDK 上執行,並產生一個可直接發佈的 `.docx` 檔案。 + +想更進一步嗎?試試以下方向: + +- 使用 `builder.moveTo(rectangleShape.getAbsolutePosition())` 在矩形內加入文字。 +- 建立形狀表格以構築圖解。 +- 將文件匯出為 PDF(`doc.save("output.pdf", SaveFormat.PDF);`)。 + +上述皆是以本教學的基礎為出發點,讓你能輕鬆擴充範例。 + +--- + +## 結語 + +精通 **create word document java** 相關的形狀與陰影操作,能讓你在自動化報表、合約或行銷素材時,擁有巨大的優勢。此方法簡潔、易於維護,且最重要的是——可以輕鬆調整任何視覺風格。 + +快把程式碼跑起來,調整模糊度、角度與距離,讓你的文件從平淡變得精緻。若遇到任何問題,歡迎在下方留言,我很樂意協助。 + +祝 coding 愉快! + + +## 相關教學 + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/hungarian/java/document-conversion-and-export/_index.md index 6e108d591e..ad62792e42 100644 --- a/words/hungarian/java/document-conversion-and-export/_index.md +++ b/words/hungarian/java/document-conversion-and-export/_index.md @@ -80,6 +80,9 @@ Használd ki a matematikai egyenletek erejét a dokumentumokban az Aspose.Words ### [Dokumentum mentése TXT‑ként – Gyors útmutató a Word‑matematika exportálásához](./save-document-as-txt-quick-guide-to-exporting-word-math/) Ismerje meg, hogyan menthet Word‑dokumentumot TXT formátumba, miközben a beágyazott matematikai egyenleteket is exportálja. +### [DOCX exportálása TXT-be Java‑val – Teljes programozási útmutató](./export-docx-to-txt-with-java-complete-programming-guide/) +Ismerje meg, hogyan konvertálhatja a DOCX fájlokat egyszerűen TXT formátumba Java‑val az Aspose.Words segítségével. + ### [Using Document Shapes in Aspose.Words for Java](./using-document-shapes/) Használd ki a dokumentumalakzatok erejét az Aspose.Words for Java‑ban. Tanuld meg, hogyan hozz létre vizuálisan vonzó dokumentumokat lépésről‑lépésre példákkal. @@ -92,6 +95,9 @@ Tanuld meg, hogyan formázd a táblázatokat és alkalmazz táblázatstílusokat ### [DOCX konvertálása markdownra – Matematikai egyenletek exportálása LaTeX-be az Aspose.Words segítségével](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Tanuld meg, hogyan konvertálj DOCX fájlokat markdown formátumba, és exportáld a matematikai egyenleteket LaTeX kódra az Aspose.Words használatával. +### [Word mentése markdownként – Matematikai egyenletek exportálása LaTeX-be Java-val](./save-word-as-markdown-export-math-to-latex-with-java/) +Tanulja meg, hogyan menthet Word dokumentumot markdown formátumba, miközben a beágyazott matematikai egyenleteket LaTeX kóddá exportálja Java-val. + ### [Hogyan ágyazzunk be képeket a Markdownba a DOCX konvertálásakor](./how-to-embed-images-in-markdown-when-converting-docx/) Tanulja meg, hogyan ágyazhat be képeket a Markdownba a DOCX konvertálásakor az Aspose.Words for Java használatával. @@ -101,6 +107,15 @@ Tanulja meg, hogyan konvertálja a DOCX fájlokat PDF‑be Java‑val az Aspose. ### [Hozzon létre akadálymentes PDF-et DOCX‑ből – Teljes útmutató](./create-accessible-pdf-from-docx-complete-guide/) Tanulja meg, hogyan konvertáljon DOCX fájlokat teljesen hozzáférhető PDF‑be az Aspose.Words for Java segítségével. +### [Képek beágyazása Base64-ként a DOCX Markdownra konvertálásakor](./embed-images-as-base64-when-converting-docx-to-markdown/) +Tanulja meg, hogyan ágyazhat be képeket Base64 kódolással a DOCX fájlok Markdownba konvertálásakor az Aspose.Words for Java használatával. + +### [Dokumentum mentése PDF‑ként Aspose.Words Java‑val – Teljes akadálymentes útmutató](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Ismerje meg, hogyan menthet PDF‑t teljesen hozzáférhető módon az Aspose.Words for Java segítségével. + +### [Akadálymentes PDF létrehozása Java‑ban – Teljes címkézési útmutató](./create-accessible-pdf-in-java-full-tagging-guide/) +Tanulja meg, hogyan hozhat létre teljesen címkézett, hozzáférhető PDF‑eket Java‑val az Aspose.Words segítségével. + ## Gyakran Ismételt Kérdések **K:** Hogyan adhatok hozzá vízjelet egy meglévő PDF-hez az Aspose.Words használatával? diff --git a/words/hungarian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/hungarian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..80a442f4ff --- /dev/null +++ b/words/hungarian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-05-26 +description: Hozzon létre hozzáférhető PDF-et Java-ban lépésről‑lépésre kóddal. Tanulja + meg, hogyan címkézze meg a PDF-et a hozzáférhetőség érdekében, és hogyan engedélyezze + a PDF‑címkézést a PdfSaveOptions használatával. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: hu +og_description: Készítsen akadálymentes PDF-et Java-ban lépésről‑lépésre kódolva. + Tanulja meg, hogyan címkézze meg a PDF-et az akadálymentesség érdekében, és hogyan + engedélyezze a PDF‑címkézést a PdfSaveOptions használatával. +og_title: Akadálymentes PDF létrehozása Java-ban – Teljes címkézési útmutató +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Akadálymentes PDF létrehozása Java-ban – Teljes címkézési útmutató +url: /hu/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hozzon létre hozzáférhető PDF-et Java-ban – Teljes címkézési útmutató + +Gondolkodott már azon, hogyan **hozzon létre hozzáférhető PDF** fájlokat közvetlenül Java kódból? Nem egyedül van. Sok fejlesztőnek kell kiszolgálnia a képernyőolvasókat használó felhasználókat, és a különbség egy egyszerű PDF és egy hozzáférhető PDF között óriási lehet. Ebben az útmutatóban végigvezetjük Önt a **PDF címkézésének a hozzáférhetőség érdekében** folyamatán, megmutatjuk, hogyan **hozzon létre címkézett PDF-et** az Aspose PDF for Java-val, és bemutatjuk a pontos lépéseket a **hozzáférhetőségi címkék PDF-hez adásához**, hogy minden olvasó ugyanazt az információt kapja. + +Továbbá bemutatjuk a **PDF címkézés engedélyezésének** legjobb gyakorlatait, a gyakori buktatókat, és egy teljes, futtatható példát, amelyet még ma beilleszthet a projektjébe. Nincsenek homályos hivatkozások – csak konkrét kód, magyarázatok, és egy végső fájl, amelyet megnyithat az Adobe Acrobatban a címkék ellenőrzéséhez. + +## Mit fog megtanulni + +- A PDF címkézés és a hozzáférhetőségi megfelelés mögötti indokok. +- Előkövetelmények és könyvtár beállítása (Aspose PDF for Java 23.10 vagy újabb). +- Hogyan **hozzon létre hozzáférhető PDF-et** a semmiből, lépésről lépésre. +- Módszerek a **hozzáférhetőségi címkék PDF-hez adására** az alap `setTagDocumentStructure` híváson túl. +- Tippek a kimenet teszteléséhez és a gyakori problémák hibakereséséhez. + +A útmutató végére képes lesz olyan PDF-eket generálni, amelyek megfelelnek a WCAG 2.1 AA ellenőrzéseknek, és közben professzionális megjelenést biztosítanak. + +--- + +## Előkövetelmények + +Mielőtt belemerülnénk, győződjön meg róla, hogy rendelkezik a következőkkel: + +| Követelmény | Indok | +|-------------|--------| +| **Java 8+** | Modern nyelvi funkciók és jobb Unicode kezelés. | +| **Aspose PDF for Java** (v23.10 or newer) | Biztosítja a `PdfSaveOptions` osztályt és a címkézés támogatását. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Az egyszerű fordítás és hibakeresés érdekében. | +| **Write permission** to a folder where the PDF will be saved | A `doc.save` hívásnak írható útvonalra van szüksége. | + +Ha még nem adta hozzá az Aspose PDF-et a projektjéhez, illessze be a következő Maven függőséget a `pom.xml`-be: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** Használja a legújabb verziót; az újabb kiadások javítják a címkézés pontosságát és nyelvspecifikus hozzáférhetőségi funkciókat adnak hozzá. + +## 1. lépés: A dokumentum vázának beállítása + +Először létrehozunk egy új `Document` objektumot. Tekintse ezt egy üres vászonnak, amely később a hozzáférhetőséghez szükséges címkéket fogja tartalmazni. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Miért fontos:** Tartalom nélkül nincs mit címkézni. Még egy egyszerű `TextFragment` hozzáadása is ad valamit a címkéző motor számára, és automatikusan létrehozza a `

` (bekezdés) címkét, amikor később engedélyezzük a struktúra címkézést. + +## 2. lépés: PDF mentési beállítások létrehozása (a címkézés központja) + +Most előkészítjük az opciókat, amelyek azt mondják az Aspose PDF-nek, hogy ágyazzon be egy logikai struktúrafát a fájlba. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +A `setTagDocumentStructure(true)` hívás a **PDF címkézés engedélyezése** kapcsoló. Ha igaz, a könyvtár egy címkefát épít fel, amely tükrözi a vizuális elrendezést, így a PDF olvashatóvá válik a segítő technológiák számára. + +> **Megjegyzés:** Ez a legegyszerűbb mód a **hogyan kell címkézett pdf-et létrehozni**. Finomabb vezérléshez (például nyelv vagy egyedi címkék beállítása) felfedezheti a `pdfOptions.setTagLanguage("en-US")` és a `pdfOptions.setTagStructureTreeRoot(...)` metódusokat. + +## 3. lépés: A hozzáférhető PDF mentése + +Végül a dokumentumot a lemezre írjuk a most konfigurált opciók segítségével. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Amikor a `doc.save` befejeződik, megtalálja az `accessible.pdf` fájlt az `output` mappában. Nyissa meg az Adobe Acrobatban, és nézze meg a **File → Properties → Description → Tags** részt – egy kitöltött címkefát kell látnia. + +## Hogyan címkézzük a PDF-et a hozzáférhetőség érdekében – az alapokon túl + +A fenti háromlépéses kódrészlet már **hozzáadja a hozzáférhetőségi címkéket a PDF-hez**, de a valós dokumentumok gyakran igényelnek egy kis extra finomítást. Íme néhány fejlesztés, amelyet beilleszthet: + +### 1. Dokumentum nyelvének beállítása + +A képernyőolvasók a nyelvi attribútumot használják a szöveg helyes kiejtéséhez. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Cím és tárgy megadása + +A metaadatok segítik a segítő eszközöket, hogy a felhasználó még a fájl megnyitása előtt kontextust biztosítsanak. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Képek címkézése alternatív szöveggel + +Ha képeket ágyaz be, azoknak `alt` leírásra van szükségük. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Táblázatfejlécek megjelölése + +A táblázatok híresen összezavarják az olvasókat, hacsak nem jelöli meg a fejlécsorokat. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Ezek a további lépések nem csak *technikai* értelemben címkézik a PDF-et, hanem valóban **hozzáférhetővé** teszik egy változatos közönség számára. + +## Gyakori buktatók a PDF címkézés engedélyezésekor + +| Tünet | Valószínű ok | Megoldás | +|-------|--------------|----------| +| Címkék hiányoznak az Acrobatban | `setTagDocumentStructure` left as `false` | Győződjön meg róla, hogy meghívja a `pdfOptions.setTagDocumentStructure(true)`-t. | +| Helytelen olvasási sorrend | Complex layout without explicit tags | Használja a `pdfOptions.setTagStructureTreeRoot(...)`-t egy egyedi sorrend meghatározásához. | +| A képek leírás nélkül „image”ként olvasódnak | No alternative text set | Hívja meg a `image.getAlternativeText().setValue("...")`-t. | +| A nyelv nem felismerhető | `setTagLanguage` omitted or wrong locale | Adjon meg egy BCP‑47 nyelvkódot (`en-US`, `fr-FR`). | + +Ezeknek a problémáknak a tudatában lenni órákat takarít meg a későbbi hibakeresés során. + +## Az eredmény ellenőrzése – Mit várhat + +A program futtatása után nyissa meg az `output/accessible.pdf` fájlt az Adobe Acrobat Readerben: + +1. **Címkék panel** (`View → Show/Hide → Navigation Panes → Tags`) hierarchiát kell, hogy mutasson, például `/Document → /Part → /Sect → /Para`. +2. **Olvasási sorrend** a vizuális áramlást kell, hogy kövesse (először szöveg, majd képek). +3. **Képernyőolvasó** (NVDA, VoiceOver) a „Hello, accessible PDF!” szöveget fogja olvasni a „Page 1” helyett. + +Ha bármelyik elem hiányzik, ellenőrizze újra a fenti lépéseket – különösen a `setTagDocumentStructure` hívást. + +## Teljes működő példa (másolás-beillesztés kész) + + + +## Kapcsolódó útmutatók + +- [Hozzon létre hozzáférhető PDF-et Word-ből – PDF/UA konvertálás](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Hozzon létre hozzáférhető PDF-et DOCX-ből – Teljes útmutató](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Hogyan mentse a dokumentumot PDF-ként az Aspose.Words for Java segítségével](/words/english/java/document-loading-and-saving/saving-documents-as-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/hungarian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/hungarian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..4531846a45 --- /dev/null +++ b/words/hungarian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Ágyazz be képeket base64 formátumban, miközben docx-et konvertálsz markdownra + az Aspose.Words for Java-val. Tanulj meg Word-et markdownra konvertálni, Word-et + markdownként menteni, és a képeket kezelni. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: hu +og_description: Ágyazz be képeket base64 formátumban a docx markdown formátumba konvertálása + során az Aspose.Words for Java használatával. Teljes útmutató a Word markdown formátumba + konvertálásához és a Word markdownként való mentéséhez. +og_title: Képek beágyazása Base64 formátumban a DOCX Markdownra konvertálásakor +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Képek beágyazása Base64 formátumban DOCX konvertálásakor Markdownba +url: /hu/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Képek beágyazása Base64-ként DOCX Markdown formátumba konvertálásakor + +Gondoltad már, hogyan **ágyazhatók be a képek Base64-ként**, miközben **docx‑et markdown‑ra konvertálsz**? Nem vagy egyedül – a fejlesztők gyakran kérdezik, hogyan tarthatók a képek beágyazva anélkül, hogy külön fájlokkal kellene bajlódni. A jó hír, hogy az Aspose.Words for Java ezt gyerekjátékká teszi: egy Word dokumentumot konvertálhatsz Markdown‑ra, és automatikusan beágyaz minden képet Base64 karakterláncként. + +Ebben az oktatóanyagban végigvezetünk a teljes folyamaton – a képeket tartalmazó `.docx` betöltésétől, a `MarkdownSaveOptions` callback konfigurálásáig, amely elvégzi a nehéz munkát, egészen a végeredmény tiszta `.md` fájlba mentéséig. A végére pontosan tudni fogod, hogyan **convert word to markdown**, **convert images to base64**, és **save word as markdown**, anélkül, hogy elhagyott képmappák maradnának. Nincs szükség külső eszközökre, nincs manuális utófeldolgozás – csak tiszta Java kód, amelyet bármely projektbe beilleszthetsz. + +## Amire szükséged lesz + +- **Java 17** (vagy bármely friss JDK) – a kód lambda szintaxist használ, de régebbi verziókra is adaptálható. +- **Aspose.Words for Java** könyvtár (2026‑os legújabb verzió). Add hozzá a Maven függőséget vagy a JAR‑t az osztályútvonalhoz. +- Egy minta **DOCX** fájl, amely legalább egy képet tartalmaz. +- Egy IDE vagy egyszerű szövegszerkesztő – a Visual Studio Code, az IntelliJ IDEA vagy akár a `vim` is megfelel. + +Ha már megvannak ezek, nagyszerű – vágjunk bele. + +## 1. lépés: Word dokumentum betöltése + +Először létrehozunk egy `Document` példányt, amely a forrásfájlra mutat. Ez ugyanaz a lépés, akár **convert docx to markdown**, akár csak más célra olvasod a fájlt. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Miért fontos:** A `Document` objektum minden Aspose művelet belépési pontja. Tartalmazza a teljes Word struktúrát – beleértve a képeket, táblázatokat és stílusokat – így a későbbi callback minden erőforrást meg tud vizsgálni. + +## 2. lépés: MarkdownSaveOptions létrehozása és Resource‑Saving callback regisztrálása + +A varázslat a `MarkdownSaveOptions`-ben rejlik. Egy `IResourceSavingCallback` csatolásával irányíthatjuk, hogy minden külső erőforrás (például egy kép) hogyan legyen kiírva. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Miért használjuk a `setSaveToMemory(true)`‑t? + +Ha a `saveToMemory` igaz, az Aspose a képadatokat egy memóriafolyamra írja a fájl helyett. A Markdown exportáló ezután a folyamot Base64 karakterlánccá alakítja, és közvetlenül a Markdown kép címkébe illeszti: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Ez a **embed images as base64** lényege. + +## 3. lépés: Dokumentum mentése Markdown formátumba + +Miután a callback be van állítva, az utolsó lépés egyszerűen a `save` meghívása. Itt történik a tényleges **convert word to markdown**, és a callbacknek köszönhetően a **convert images to base64** is. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Eredmény:** az `out.md` Markdown szöveget tartalmaz, ahol minden kép egy `data:` URI‑ként jelenik meg. Nem jönnek létre extra képfájlok a lemezen, így a mappa rendezett marad. + +## 4. lépés: Kimenet ellenőrzése és gyakori buktatók + +Nyisd meg a generált `out.md`‑t bármely Markdown megjelenítőben (VS Code, GitHub vagy egy statikus weboldalgenerátor). Valami ilyesmit kell látnod: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Hibaelhárítási ellenőrzőlista + +| Probléma | Valószínű ok | Megoldás | +|----------|--------------|----------| +| A kép törött hivatkozásként jelenik meg | `setSaveToMemory` hiányzott | Győződj meg róla, hogy a `args.setSaveToMemory(true);` a callbackben van | +| A Base64 karakterlánc csonkolva van | A kimeneti fájl kódolása nem egyezik | Mentsd a Markdown-t UTF‑8 kódolással (az Aspose alapértelmezettje) | +| Váratlan fájlnevek | `setKeepResourceOriginalName(true)` | Hagyd `false` értéken, hogy a saját névadási logika érvényesüljön | + +## 5. lépés: Haladó variációk (opcionális) + +### Csak kiválasztott képek konvertálása + +Ha csak bizonyos képeket szeretnél beágyazni (például 100 KB-nál nagyobbakat), adj hozzá egy méretellenőrzést: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Más képformátum használata + +A `ResourceSavingArgs` nyers bájtokat ad, így a JPEG‑eket PNG‑re kódolhatod beágyazás előtt – hasznos, ha a célzott Markdown fogyasztó a PNG‑t részesíti előnyben. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Ezek a finomhangolások azt mutatják, mennyire rugalmas a **embed images as base64** megközelítés, amikor **convert docx to markdown**. + +## Összegzés + +Most megtanultad, hogyan **embed images as base64**, miközben **convert docx to markdown** az Aspose.Words for Java segítségével. Egy egyszerű `IResourceSavingCallback` csatlakoztatásával a könyvtár elvégzi a nehéz munkát: **convert word to markdown**, **convert images to base64**, és végül **save word as markdown** egyetlen `save` hívással. + +Nyugodtan kísérletezz – próbálj ki különböző kép‑szűrési szabályokat, váltás HTML kimenetre, vagy láncolj ezt a lépést egy statikus weboldalgenerátorral. Ugyanez a minta más formátumokra (HTML, EPUB) is működik, így újra felhasználhatod a callbacket, ahol csak beágyazott erőforrásokra van szükség. + +**Következő lépések:** +- Fedezd fel a `HtmlSaveOptions`‑t a Base64 képekkel ellátott HTML‑hez. +- Kombináld ezt egy CI pipeline‑nal a dokumentáció automatikus generálásához. +- Merülj el az Aspose `DocumentVisitor`‑ben, ha még finomabb irányítást szeretnél a konverziós folyamat felett. + +Boldog kódolást, és élvezd a tiszta, önálló Markdown fájlokat! + +## Kapcsolódó oktatóanyagok + +- [Hogyan ágyazzunk be képeket Markdownba DOCX konvertálásakor](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [DOCX konvertálása markdownra – Matematikai egyenletek exportálása LaTeX-be az Aspose.Words segítségével](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Képek mentése Word‑ből – Aspose.Words for Java útmutató](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/hungarian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..7087d64f81 --- /dev/null +++ b/words/hungarian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Exportálja a docx-et txt-be Java és Aspose.Words segítségével. Tudja + meg, hogyan konvertálja a docx-et szöveggé, őrizze meg a Unicode-ot, és exportálja + a Word dokumentumot txt formátumba néhány lépésben. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: hu +og_description: Docx exportálása txt-be Java-ban. Ez az útmutató bemutatja, hogyan + konvertáljuk a docx-et szöveggé, megőrizve a sima szöveg Unicode-át, és hatékonyan + exportáljuk a Word dokumentumot txt-be. +og_title: DOCX exportálása TXT-be Java-val – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: DOCX exportálása TXT-be Java-val – Teljes programozási útmutató +url: /hu/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Export docx txt-be Java-val – Teljes programozási útmutató + +Ever needed to **export docx to txt** but worried about losing special characters? You're not the only one. When you convert Word documents to plain‑text files, Unicode symbols, tables, and even simple formatting can vanish like magic. + +In this guide we’ll walk through a reliable way to **export docx to txt** using Aspose.Words for Java, preserving every Unicode glyph and keeping table layouts readable. By the end you’ll also know how to **convert docx to text**, **convert word to text**, and even **export word as txt** without a hitch. + +## What This Tutorial Covers + +* Aspose.Words beállítása Java projektben +* DOCX fájl betöltése és előkészítése egyszerű szöveges kimenethez +* A **plain text unicode** támogatás konfigurálása a `TxtSaveOptions` segítségével +* Opcionális trükkök a táblázatok olvashatóvá tételéhez a keletkező `.txt` fájlban +* A fájl mentése és a kimenet ellenőrzése + +No external scripts, no mysterious command‑line tools—just pure Java code you can drop into any Maven or Gradle project. + +> **Why care?** Plain‑text files are lightweight, version‑control friendly, and perfect for search‑indexing or downstream processing pipelines. If you’ve ever tried to `cat` a Word file and got gibberish, this tutorial solves that problem. + +--- + +## Export docx to txt – Overview + +Before we dive into code, let’s clear up the terminology. **Export docx to txt** means taking a Microsoft Word `.docx` package and writing its textual content to a simple `.txt` file. Unlike a PDF conversion, a text export strips away styling but can keep line breaks, paragraph markers, and—if you configure it right—Unicode characters such as emojis, accented letters, or Asian scripts. + +Aspose.Words makes this painless because it abstracts the Word file format and offers a `TxtSaveOptions` class where you can dictate encoding, table handling, and more. + +### Prerequisites + +* Java 11 vagy újabb (az API működik Java 8+-al is, de feltételezzük, hogy egy friss JDK-t használunk) +* Aspose.Words for Java JAR (elérhető a Maven Centralból) +* Egy minta `unicode.docx` fájl, amely változatos Unicode karaktereket tartalmaz – például “こんにちは”, “😊”, és egy egyszerű táblázat + +If you’ve got those, let’s get started. + +--- + +## Step 1: Load the DOCX File (Convert docx to text) + +The first thing you need to do is read the source document into memory. This is where the **convert docx to text** process officially begins. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Why this matters:* `Document` is Aspose.Words’ representation of a Word file. By loading it, you gain access to all its paragraphs, tables, and even hidden elements. If the file isn’t found, Aspose throws a clear `FileNotFoundException`, so you’ll know immediately what went wrong. + +--- + +## Step 2: Configure TxtSaveOptions for Unicode (Plain text unicode) + +Plain‑text files are just streams of bytes, so you must tell Java which character set to use. UTF‑8 is the de‑facto standard for **plain text unicode** because it can encode every Unicode code point. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro tip:** If you skip the `setEncoding` call, Aspose defaults to the platform’s default charset, which on many Windows machines is Windows‑1252. That default will silently drop characters like “ß” or “—”. + +--- + +## Step 3: Preserve Table Layout (Optional, but handy for readability) + +When you **export word as txt**, tables usually flatten into a single line of text, making them unreadable. Aspose.Words offers a simple flag to keep the visual structure. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*When to use it:* If your source DOCX contains invoices, schedules, or any grid‑like data, enabling `PreserveTableLayout` will insert tabs and line breaks so the resulting file still resembles a table. If you don’t need this, you can omit the line and get a more compact output. + +--- + +## Step 4: Save the Document as Plain‑Text (Export word as txt) + +Now the heavy lifting is done—just write the bytes to disk. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Running the program produces `plain.txt` in the same folder. Open it with any text editor (Notepad++, VS Code, even `cat` in a terminal) and you’ll see: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Notice how the Japanese greeting and smiley survived, and the table kept its columns thanks to `PreserveTableLayout`. That’s the essence of a clean **export docx to txt**. + +--- + +## Step 5: Verify the Output (Convert word to text sanity check) + +A quick sanity check prevents silent data loss. Here are a few ways to confirm you truly **convert word to text** correctly: + +1. **Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before and after a round‑trip conversion (txt → docx → txt) to ensure stability. +2. **Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate characters like “😊”. +3. **Open in multiple editors** – some old Windows Notepad versions still misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper encoding. + +If any of these checks fail, double‑check that `saveOptions.setEncoding(StandardCharsets.UTF_8)` is present and that your source DOCX truly contains Unicode text. + +--- + +## Common Pitfalls & How to Avoid Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Missing characters** | Default system charset (e.g., Windows‑1252) drops non‑ASCII glyphs. | Explicitly set UTF‑8 via `saveOptions.setEncoding`. | +| **Tables become a single line** | `PreserveTableLayout` left at default `false`. | Call `saveOptions.setPreserveTableLayout(true)`. | +| **File not found** | Wrong path or missing read permissions. | Use absolute paths or `Paths.get(...)` with proper exception handling. | +| **Performance slowdown on huge docs** | Loading the entire document into memory. | Stream the document in chunks using `DocumentBuilder` if you only need specific sections. | + +--- + +## Bonus: Exporting Multiple DOCX Files in a Batch + +If you need to **convert docx to text** for a whole folder, wrap the logic in a loop: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +This snippet **export docx to txt** for every file in the directory, saving you hours of manual work. + +--- + +## Conclusion + +You’ve just learned how to **export docx to txt** with Java, ensuring that every Unicode character stays intact, tables stay readable, and the whole process is repeatable. By configuring `TxtSaveOptions` for UTF‑8 and optionally preserving table layouts, you can reliably **convert docx to text**, **convert word to text**, and **export word as txt** for any downstream workflow. + +Ready for the next challenge? Try exporting to other plain‑text formats like markdown (`.md`) or CSV, or explore Aspose.Words’ PDF conversion capabilities. The same principles—explicit encoding, layout preservation, and thorough verification—apply across the board. + +Happy coding, and may your text files always stay Unicode‑rich! + +--- + +![Diagram a docx txt export pipeline-ról](/images/export-docx-to-txt-pipeline.png){alt="docx txt export pipeline diagram"} + +## Related Tutorials + +- [Docx konvertálása Txt-re](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – DOCX konvertálása PDF-re Java-ban](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Docx konvertálása markdownra – Matematikai egyenletek exportálása LaTeX-be az Aspose.Words segítségével](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/hungarian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..34a4891f2b --- /dev/null +++ b/words/hungarian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-05-26 +description: Mentse a dokumentumot PDF-ként az Aspose.Words Java használatával, és + adjon hozzá akadálymentességet a PDF-hez. Tanulja meg, hogyan konvertáljon docx-et + PDF-be, címkézze a vízszintes vonalakat, és biztosítsa a PDF/UA‑2 megfelelőséget. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: hu +og_description: Dokumentum mentése PDF‑ként az Aspose.Words Java segítségével, miközben + hozzáadja a hozzáférhetőséget a PDF‑hez. Lépésről‑lépésre útmutató a docx PDF‑re + konvertálásához és a vízszintes vonalak címkézéséhez a PDF/UA‑2 megfelelés érdekében. +og_title: Dokumentum mentése PDF formátumba az Aspose.Words Java-val – Az akadálymentesség + egyszerűen +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Dokumentum mentése PDF‑ként az Aspose.Words Java‑val – Teljes hozzáférhetőségi + útmutató +url: /hu/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Dokumentum mentése PDF-ként Aspose.Words Java használatával – Teljes hozzáférhetőségi útmutató + +Gondolkodtál már azon, hogyan **mentheted a dokumentumot PDF‑ként**, miközben a képernyőolvasók számára is hozzáférhető marad? Nem vagy egyedül. Sok fejlesztőnek szüksége van a *convert docx to pdf* feladatra, és még a PDF/UA‑2 szabványoknak is meg kell felelni, különösen, ha a forrás vízszintes vonalakat tartalmaz, amelyeket helyesen kell címkézni. Ebben az útmutatóban lépésről lépésre bemutatjuk, hogyan **mentheted a dokumentumot PDF‑ként** az Aspose.Words for Java használatával, automatikusan **hozzáadva a hozzáférhetőséget a PDF‑hez**, és biztosítva, hogy minden vízszintes vonal **címkézve** legyen egy műtárgyként. + +Egy tiszta Java projekttel kezdünk, betöltünk egy már tartalmazó vízszintes vonalakat tartalmazó DOCX‑et, beállítjuk a PDF mentési beállításokat a PDF/UA‑2 megfelelőséghez, és végül kiírunk egy teljesen hozzáférhető PDF‑et. A végére képes leszel **dokumentumot PDF‑ként menteni**, biztosan, hogy átmegy a hozzáférhetőségi ellenőrzéseken. + +## Előkövetelmények + +- Java 8 vagy újabb telepítve (az útmutatót JDK 17‑en teszteltük). +- Maven 3.6+ (vagy Gradle, ha azt részesíted előnyben) a függőségek kezeléséhez. +- Érvényes Aspose.Words for Java licenc (az ingyenes próba működik, de egy licenc eltávolítja a kiértékelési vízjeleket). +- Egy DOCX fájl (`input.docx`), amely legalább egy vízszintes vonalat tartalmaz – gondolj egy egyszerű vonal elválasztóra, amit a Wordben hozzáadnál. + +> **Pro tipp:** Ha nincs kéznél DOCX fájlod, egyszerűen hozz létre egy új Word dokumentumot, írj néhány bekezdést, illeszd be a *Insert → Horizontal Line* (Beszúrás → Vízszintes vonal) elemet, mentsd `input.docx`‑ként, és helyezd el a választott mappában. + +## 1. lépés: Maven projekt beállítása + +Először hozz létre egy új Maven projektet (vagy adj hozzá egy meglévőhöz). A `pom.xml`-nek tartalmaznia kell az Aspose.Words függőséget: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Miért fontos:** Az `aspose-words` artefakt hozzáadása az első lépés a *convert docx to pdf* folyamatban. Enélkül a fordító nem ismeri fel a `Document`, `PdfSaveOptions` és más kulcsfontosságú osztályokat. + +## 2. lépés: A vízszintes vonalakat tartalmazó forrás DOCX betöltése + +Most egy kis Java osztályt írunk, amely betölti a DOCX‑et. Itt kezdődik a **tag horizontal rules** rész – az Aspose.Words automatikusan egy vízszintes vonalat egy szegéllyel rendelkező bekezdésként kezel, de a PDF/UA motorra bízzuk a címkézést. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Vedd észre, hogy még semmit sem mentettünk – csak **betöltjük** a DOCX‑et, ami a *convert docx to pdf* első felét jelenti. A `Document` objektum most már tartalmazza az összes Word tartalmat, beleértve a beillesztett vízszintes vonalakat is. + +## 3. lépés: PDF mentési beállítások konfigurálása a PDF/UA‑2 megfelelőséghez + +Az **adding accessibility to PDF** varázslata a `PdfSaveOptions`‑ban rejlik. A megfelelőségi szint `PDF_UA_2`‑re állításával az Aspose.Words a következőket teszi: + +1. Címkézi a strukturális elemeket (címek, táblázatok stb.). +2. Megjelöli a díszítő elemeket – például a vízszintes vonalakat – *műtárgyként*, így a képernyőolvasók figyelmen kívül hagyják őket. +3. Beilleszti a szükséges PDF/UA metaadatokat. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Miért állítsuk be a megfelelőséget?** `PDF_UA_2` nélkül a létrejövő PDF még olvasható lehet, de nem fog átmenni az automatikus hozzáférhetőségi ellenőrzőkön. A **tag horizontal rules** követelmény automatikusan teljesül, mivel a PDF/UA a megfelelőségi jelző bekapcsolásakor *műtárgyként* kezeli őket. + +## 4. lépés: Dokumentum mentése PDF‑ként + +Most végre **mentjük a dokumentumot PDF‑ként**. Ez az egyetlen sor végzi a nehéz munkát – a DOCX konvertálását, a hozzáférhetőségi címkék alkalmazását, és a fájl lemezre írását. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Futtasd az osztályt (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`), és egy megerősítő üzenetet látsz. Nyisd meg a keletkezett `ua_compliant.pdf`‑et az Adobe Acrobatban, és ellenőrizd a **File → Properties → Description → PDF/A, PDF/UA** részt – a listán a „PDF/UA‑2” kell, hogy megjelenjen. + +### Várható kimenet + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Nyisd meg a PDF‑et, és észre fogod venni: + +- A dokumentum szövege kijelölhető és kereshető. +- A vízszintes vonal láthatatlan a képernyőolvasók számára (műtárgyként kezelve). +- A PDF átmegy az alap PDF/UA ellenőrző eszközökön (pl. PAC 3). + +## 5. lépés: Hozzáférhetőség ellenőrzése – Gyors ellenőrzőlista + +Bár az Aspose.Words a legtöbb munkát elvégzi, jó gyakorlat az eredmény ellenőrzése. + +| Ellenőrzés | Hogyan ellenőrizhető | +|------------|----------------------| +| **Dokumentum címe** | Nyisd meg az Acrobatot → File → Properties → Title mező (meg kell egyeznie a `pdfOptions.setTitle` értékével). | +| **Műtárgy címkézés** | Használd az Acrobat “Reading Order” (Olvasási sorrend) eszközét. A vízszintes vonalaknak *Artifact* (szürke)ként kell megjelenniük. | +| **Logikai olvasási sorrend** | Futtasd az Acrobat “Accessibility Checker” (Hozzáférhetőségi ellenőrző) eszközét; ellenőrizd, hogy nincsenek strukturális hibák. | +| **Címkézett PDF** | Az Acrobat “Tags” (Címkék) paneljén nézd meg – egy hierarchiát kell látnod (Document → Section → Paragraph, stb.). | +| **PDF/UA megfelelőség** | Az Acrobat a “Standards” (Szabványok) fülön a „PDF/UA‑2” feliratot jeleníti meg. | + +Ha bármelyik ellenőrzés sikertelen, ellenőrizd újra, hogy a legújabb Aspose.Words verziót használod-e, és hogy a `setCompliance(PdfCompliance.PDF_UA_2)` helyesen van-e alkalmazva. + +## Gyakori hibák és elkerülésük + +1. **Hiányzó licenc** – A próbaverzió vízjelet ad hozzá, ami megzavarhatja a PDF/UA validálást. A licencet alkalmazd már a `main` elején: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Helytelen bemeneti útvonal** – A `FileNotFoundException` leállítja a konvertálást. Használj abszolút útvonalakat, vagy helyezd a DOCX‑et a projekt gyökerébe, és hivatkozz rá a `new File("input.docx").getAbsolutePath()` segítségével. +3. **Régebbi Aspose verzió használata** – A PDF/UA támogatás a 22.9‑es verzióban került bevezetésre. Frissíts a legújabb kiadásra, hogy elkerüld a hiányzó funkciókat. +4. **Vízszintes vonal képként** – Ha a vonalat képként illesztetted be a natív Word vízszintes vonal helyett, az Aspose azt egy szokásos képként kezeli, nem műtárgyként. Cseréld le a képet a Word beépített *Horizontal Line* (Vízszintes vonal) elemére a megfelelő címkézéshez. + +## A megoldás bővítése – Mi van, ha többre van szükséged? + +- **Egyéni címkék**: Ha más díszítő elemeid vannak (pl. dísz ikonok), manuálisan megjelölheted őket műtárgyként a `PdfSaveOptions.setArtifactTaggingEnabled(true)` használatával. +- **Több dokumentum**: Iterálj egy DOCX fájlok mappáján, és kötegelt konvertálást végezz, a teljesítmény érdekében újrahasználva ugyanazt a `PdfSaveOptions` példányt. +- **Nyelvcímke hozzáadása**: Többnyelvű PDF‑ek esetén állítsd be a `pdfOptions.setLanguage("en-US")`‑t, hogy a segítő technológiák a megfelelő hangot válasszák. + +## Teljes működő példa (az összes kód együtt) + +Az alábbiakban a teljes, futtatható Java program látható. Másold be a kedvenc IDE‑dbe, állítsd be az útvonalakat, és indítsd el. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Futtasd, nyisd meg a generált PDF‑et, és egy tiszta, hozzáférhető fájlt kapsz, amely készen áll a terjesztésre. + +## Következtetés + +Most bemutattuk, hogyan **mentheted a dokumentumot PDF‑ként** az Aspose.Words for Java használatával, miközben automatikusan **hozzáadod a hozzáférhetőséget a PDF‑hez** és **címkézed a vízszintes vonalakat** műtárgyként. A fő tanulságok: + +- `PdfSaveOptions` használata `PDF_UA_2` megfelelőséggel a hozzáférhetőségi szabványok teljesítéséhez. +- A DOCX betöltése és a `doc.save(..., pdfOptions)` meghívása minden, ami a **convert docx to pdf** feladathoz szükséges. +- A vízszintes vonalakat a rendszer kezeli – nincs szükség extra kódra, ez teljesíti a **tag horizontal rules** követelményt. +- A megközelítés teljesen **aspose convert docx pdf** kompatibilis, a legújabb könyvtárverzióval működik, és egy validálásra kész PDF‑et állít elő. + +Készen állsz a következő kihívásra? Próbálj meg egyéni metaadatokat hozzáadni, betűkészleteket beágyazni, vagy egy egész DOCX mappát kötegelt feldolgozni. Ezek a kiegészítések mind ugyanarra az alapra épülnek, amit itt bemutattunk. + +Van kérdésed a PDF/UA megfelelőségről, a licencelésről vagy más Word elemek kezeléséről? Írj egy megjegyzést, vagy nézd meg az Aspose hivatalos dokumentációját – rengeteg példa vár felfedezésre. Boldog kódolást, és élvezd a hozzáférhető PDF‑ek létrehozását! + +![dokumentum mentése PDF‑ként Aspose.Words Java használatával – hozzáférhető PDF példa](placeholder-image.png "dokumentum mentése PDF‑ként Aspose.Words Java használatával – hozzáférhető PDF példa") + + +## Kapcsolódó oktatóanyagok + +- [Hogyan mentheted a dokumentumot PDF‑ként Aspose.Words for Java használatával](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Hogyan konvertálj Word‑et PDF‑re Aspose.Words for Java használatával](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – DOCX konvertálása PDF‑re Java‑ban](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/hungarian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..7a8ab7d0fc --- /dev/null +++ b/words/hungarian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Mentse a Word dokumentumot markdown formátumban, és fedezze fel, hogyan + exportálhatja a matematikai egyenleteket LaTeX‑be az Aspose.Words for Java segítségével. + Konvertálja a Word egyenleteket LaTeX‑re néhány sorban. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: hu +og_description: Mentse a Word dokumentumot markdown formátumban, és tanulja meg, hogyan + exportálhatja a matematikai egyenleteket LaTeX-be az Aspose.Words for Java segítségével. + Egy teljes, futtatható útmutató. +og_title: Word mentése markdownként – Matematikai kifejezések exportálása LaTeX-be + Java-val +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Word mentése markdownként – Matematikai kifejezések exportálása LaTeX-be Java-val +url: /hu/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word mentése markdownként – Matematikai képletek exportálása LaTeX-be Java-val + +Valaha is szükséged volt **save word as markdown**-ra, de attól tartottál, hogy a képletek összegabalyodott szöveggé válnak? Nem vagy egyedül. Ebben az útmutatóban végigvezetünk a **how to export math** folyamatán, egy `.docx` fájlból közvetlenül LaTeX-be exportálva, miközben a dokumentum többi része tiszta Markdown lesz. + +Mindent lefedünk, a Aspose.Words könyvtár beállításától a végső `out.md` fájl ellenőrzéséig. A végére képes leszel **convert word equations latex** egyetlen metódushívással, és megérted az apró finomságokat, amelyek megbízhatóvá teszik a konverziót. + +--- + +## Amire szükséged lesz + +- **Java 8+** – a kód bármely friss JDK-n fut. +- **Aspose.Words for Java** – akár Maven/Gradle függőség, akár JAR, ha manuális beállítást kedvelsz. +- Egy Word dokumentum (`math.docx`), amely legalább egy Office Math képletet tartalmaz. +- Egy IDE vagy egyszerű `javac`/`java` parancssor – bármi, amiben kényelmesen érzed magad. + +Ha már megvannak, nagyszerű. Ha nem, a következő szakasz pontosan megmutatja, hogyan juttathatod a könyvtárat a projektedbe. + +--- + +## Word mentése markdownként – 1. lépés: Aspose.Words hozzáadása a projekthez + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose ingyenes ideiglenes licencet kínál teszteléshez. Helyezd a `license.xml` fájlt a resources mappádba, és hívd meg a `License license = new License(); license.setLicense("license.xml");` kódot, mielőtt bármilyen dokumentumot betöltenél. + +Miután a függőség feloldódott, készen állsz a konverziós kód megírására. + +--- + +## Hogyan exportáljunk matematikai képleteket LaTeX-be + +A nehéz munkát a `MarkdownSaveOptions` végzi. Ha a `OfficeMathExportMode`-ot `LATEX`-re állítod, minden Office Math objektum LaTeX töredékként jelenik meg a Markdown kimenetben. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Miért működik ez + +- **`Document`** az Aspose belépési pontja; absztrahálja a `.docx` fájlt, és hozzáférést biztosít minden csomóponthoz, beleértve a képleteket. +- **`MarkdownSaveOptions`** megmondja a könyvtárnak, *hogyan* szeretnéd a kimenetet. Alapértelmezés szerint a képleteket képként rendereli, ami aláássa a szövegalapú formátum célját. +- **`OfficeMathExportMode.LATEX`** arra kényszeríti a motorot, hogy minden `OfficeMath` csomópontot a megfelelő LaTeX megfelelőjére fordítson, amit a Markdown értelmezők (például GitHub vagy Jekyll) képesek megjeleníteni egy MathJax plugin használatával. + +--- + +## Word képletek LaTeX-re konvertálása – 2. lépés: A Markdown kimenet ellenőrzése + +A program futtatása után nyisd meg a `out.md`-t. Valami ilyesmit kell látnod: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Megjegyzés:** A LaTeX töredékek `$…$` közé vannak téve inline matematikához, és `$$…$$` közé blokk matematikához. Ez a szabványos szintaxis, amelyet a legtöbb statikus weboldalkészítő megért, ha a MathJax engedélyezve van. + +Ha inkább csak inline képleteket szeretnél, tovább finomíthatod a `MarkdownSaveOptions`-t: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx markdown latex-re – 3. lépés: Szélső esetek és gyakori buktatók + +| Situation | What to watch for | Fix | +|-----------|-------------------|-----| +| **Komplexz beágyazott egyenletek** | Az Aspose extra kapcsos zárójeleket `{}` adhat ki, amelyeket egyes értelmezők szó szerint kezelnek. | A Markdown-et utófeldolgozhatod egy egyszerű regex-szel, hogy összevonja a `{{` → `{`. | +| **Hiányzó MathJax a céloldalon** | A képletek nyers LaTeX kódként jelennek meg. | Add `` a HTML sablonodhoz. | +| **Nagy dokumentumok** | A memóriahasználat megugrik, mert az egész dokumentum egyszerre betöltődik. | Használd a `LoadOptions.setLoadFormat(LoadFormat.DOCX)`-t, és fontold meg az oldalak kötegelt feldolgozását, ha `OutOfMemoryError`-t kapsz. | +| **Licenc nincs beállítva** | Figyelmeztetést kapsz, és a kimenet vízjelezett lehet. | Töltsd be a licencet korán a `main`-ben, ahogy a Maven tippben fentebb látható. | + +--- + +## Word mentése markdownként – Teljes működő példa + +Az alábbi önálló osztályt bármely Java projektbe beillesztheted. Csak cseréld le a `YOUR_DIRECTORY`-t a fájljaid elérési útjára. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Futtasd a programot (`java MathToLatexMarkdown`), és a konzolon megjelenik egy üzenet, amely megerősíti a sikeres futást. Nyisd meg az `out.md`-t bármely szerkesztőben – a képletek tiszta LaTeX kódrészletek lesznek, készen a megjelenítésre. + +--- + +## Várt kimenet pillanatképe + +![save word as markdown output with LaTeX equations](https://example.com/images/markdown-latex-output.png "save word as markdown output with LaTeX equations") + +*A kép egy részletet mutat a generált Markdown-ból, ahol a `\int_{a}^{b} f(x)\,dx` egyenlet `$$`-be van ágyazva.* + +--- + +## Következtetés + +Most bemutattuk, hogyan **save word as markdown**, miközben minden Office Math képletet natív LaTeX-ként őrzünk meg. A kulcsfontosságú lépés a `MarkdownSaveOptions` `OfficeMathExportMode.LATEX`-re állítása volt, amely egy tipikus Word‑to‑Markdown folyamatot teljesen matematikai tudatosságú konverziós eszközzé alakít. + +Most már: + +1. **How to export math** bármely `.docx`-ből, anélkül, hogy a pontosságot elveszítenéd. +2. **Convert word equations latex** statikus weboldalkészítők, dokumentációk vagy tudományos blogok számára. +3. Bővítsd a megközelítést, hogy sok fájlt kötegelt módon dolgozz fel, CI pipeline-okba integráld, vagy akár egy kis webszolgáltatást építs. + +Ha kíváncsi vagy a következő határra, próbáld meg kombinálni ezt **docx to markdown latex**-szal képekben gazdag dokumentumokhoz, vagy fedezd fel az Aspose `HtmlSaveOptions`-át egy web‑kész HTML verzióhoz. A lehetőségek végtelenek—kísérletezz, törj el dolgokat, majd oszd meg a felfedezéseidet a közösséggel. + +Van kérdésed vagy egy nehéz egyenleted, ami nem úgy renderelődött, ahogy vártad? Hagyj egy megjegyzést alább, és jó kódolást! + +## Kapcsolódó oktatóanyagok + +- [Hogyan exportáljunk LaTeX-et Word-ből: DOCX konvertálása Markdown-be és mentés PDF-ként](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [docx konvertálása markdown-re – Matematikai képletek exportálása LaTeX-be Aspose.Words segítségével](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Hogyan konvertáljunk Word-et PDF-re Aspose.Words for Java használatával](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/hungarian/java/document-loading-and-saving/_index.md index 304de17cf0..d50fa872e6 100644 --- a/words/hungarian/java/document-loading-and-saving/_index.md +++ b/words/hungarian/java/document-loading-and-saving/_index.md @@ -100,6 +100,7 @@ A dokumentumbeállítások kulcsfontosságúak a pontos igényekhez igazított k ### [Dokumentumformátum meghatározása Aspose.Words for Java‑ban](./determining-document-format/) ### [Sérült docx helyreállítása – Teljes útmutató a dokumentumok javításához és feldolgozásához](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) ### [Betűtípus helyettesítési figyelmeztetések rögzítése Java-ban az Aspose.Words‑szal – Teljes útmutató](./capture-font-substitution-warnings-in-java-with-aspose-words/) +### [Sérült Word dokumentum megnyitása – Helyreállítási mód beállítása Java-ban](./open-corrupted-word-document-set-recovery-mode-in-java/) ## Gyakran Ismételt Kérdések diff --git a/words/hungarian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/hungarian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..f715b0fc74 --- /dev/null +++ b/words/hungarian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Nyissa meg a sérült Word-dokumentumot Java-ban az Aspose.Words segítségével. + Ismerje meg, hogyan állítható be a helyreállítási mód, és hogyan lehet megbízhatóan + helyreállítani a sérült Word-fájlokat. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: hu +og_description: Nyissa meg a sérült Word-dokumentumot Java-ban az Aspose.Words használatával. + Ez az útmutató bemutatja, hogyan állítható be a helyreállítási mód, és hogyan lehet + hatékonyan helyreállítani a sérült Word-fájlokat. +og_title: Sérült Word-dokumentum megnyitása – Helyreállítási mód beállítása Java-ban +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Sérült Word-dokumentum megnyitása – Helyreállítási mód beállítása Java-ban +url: /hu/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Sérült Word-dokumentum megnyitása – Helyreállítási mód beállítása Java-ban + +Próbált már megnyitni egy sérült Word-dokumentumot, és látta, ahogy a program egy kivételnél elakad? Nem egyedül van – ezek a törött .docx fájlok igazi fejfájást okozhatnak. A jó hír, hogy az Aspose.Words for Java finom‑grained vezérlést biztosít, így **open corrupted word document** anélkül, hogy az alkalmazás összeomlana, és még eldöntheti, hogy figyelmeztetéseket, csendes helyreállítást vagy szigorú elutasítást szeretne. + +Ebben az oktatóanyagban végigvezetjük a teljes folyamatot: a megfelelő `LoadOptions` létrehozásától, a megfelelő **set recovery mode** érték kiválasztásáig, egészen addig, hogy megerősítsük, a dokumentum valóban be lett töltve. A végére pontosan tudni fogja, **how to recover corrupted word file** programozottan, manuális másolás‑beillesztés nélkül. + +> **Ami szükséges** +> * Java 8 vagy újabb (az API Java 11‑kel is működik) +> * Aspose.Words for Java 23.9 (vagy a legújabb verzió) +> * Egy minta sérült .docx fájl – egyszerűen nevezzen át egy érvényes fájlt, hogy szimulálja a sérülést, ha nincs kéznél + +Merüljünk el benne. + +## Sérült Word-dokumentum megnyitása – Lépés‑ről‑lépésre áttekintés + +Az alábbi magas szintű folyamatot fogjuk megvalósítani: + +1. **`LoadOptions` létrehozása** – ez az objektum azt mondja meg az Aspose.Words‑nek, hogyan viselkedjen, ha problémába ütközik. +2. **Helyreállítási mód beállítása** – válassza a `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` vagy `REJECT_CORRUPTED` lehetőségek közül. +3. **A dokumentum betöltése** a konfigurált beállításokkal. +4. **Ellenőrzés**, hogy a betöltés sikeres volt‑e (pl. nyomtassa ki az oldalszámot). + +Minden lépést részletesen kifejtünk, kódrészletekkel, amelyeket közvetlenül be tud másolni a fejlesztőkörnyezetbe. + +## Helyreállítási mód beállítása különböző helyzetekhez + +Az Aspose.Words három helyreállítási stratégiát definiál a `LoadOptions.RecoveryMode`‑ban: + +| Mód | Viselkedés | Mikor használjuk | +|------|-----------|-------------------| +| `RECOVER_WITH_WARNINGS` | Megpróbálja betölteni a dokumentumot, de a felmerülő problémákat figyelmeztetésként jeleníti meg a konzolon. | Akkor használja, ha szeretné látni, *mi* ment rosszul anélkül, hogy megszakadna. | +| `RECOVER_WITHOUT_WARNINGS` | Csendben javítja, amit tud, és elnyomja a figyelmeztetéseket. | Éles környezetek, ahol a naplók tisztán kell maradniuk. | +| `REJECT_CORRUPTED` | Kivételt dob, amint a sérülést észleli. | Szigorú validációs folyamatok, amelyeknek gyorsan kell hibát jelezniük. | + +A megfelelő mód kiválasztása a **set recovery mode** helyes alkalmazásának lényege. A legtöbb hibakeresési munkamenetben a `RECOVER_WITH_WARNINGS` a legideálisabb, mert pontosan megmutatja, mely részeket javították. + +## Hogyan állítsuk helyre a sérült Word-fájlt az Aspose.Words segítségével + +Az alábbi **teljes, futtatható Java program** bemutatja az egész folyamatot. Nyugodtan helyezze el egy `RecoveryModeDemo.java` fájlba, állítsa be az elérési utat, és futtassa. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Miért fontos minden sor + +* **`LoadOptions loadOptions = new LoadOptions();`** – ez az objektum nélkül az Aspose.Words az alapértelmezett helyreállítást használja, amely *elutasítja* a sérült fájlokat. Létrehozásával lehetőséget kap a viselkedés módosítására. +* **`setRecoveryMode(...)`** – ez a **set recovery mode** hívás, amely eldönti, hogy a figyelmeztetések megjelennek‑e, rejtve maradnak‑e, vagy kivételt okoznak. +* **`new Document(path, loadOptions);`** – a konstruktor elfogadja a most konfigurált `LoadOptions`‑t, így a könyvtár már a kezdetektől tudja, hogyan kezelje a törött fájlt. +* **`doc.getPageCount()`** – gyors ellenőrzés. Ha a dokumentum betöltődik és visszaad egy oldalszámot, akkor sikeresen **how to recover corrupted word file**. +* **`doc.save(...)`** – opcionális, de hasznos; a javított verziót visszaírhatja a lemezre későbbi felhasználásra. + +## Gyakori széljegyek kezelése + +### 1. Fájl nem található + +Ha az útvonal hibás, a `Document` `FileNotFoundException`‑t dob. Tegye a betöltést egy try‑catch blokkba, és naplózzon barátságos üzenetet: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Javíthatatlan sérülés + +Még a `RECOVER_WITH_WARNINGS` esetén is előfordulhat, hogy egyes struktúrák helyrehozhatatlanok. Ebben az esetben az Aspose.Words betölti, amit tud, de figyelmeztetéseket kap, például „Cannot read paragraph properties”. Figyelje a konzol kimenetét; ezek a figyelmeztetések gyakran hiányzó szakaszokra mutatnak, amelyeket manuálisan kell rekonstruálni. + +### 3. Nagy fájlok és teljesítmény + +A helyreállítás kis plusz terhelést jelent, mivel a könyvtár kétszer olvassa a fájlt – egyszer a problémák felderítésére, majd újra a felépítésre. Több gigabájtos dokumentumok esetén fontolja meg a fájl streaming‑jét vagy a JVM heap növelését (`-Xmx2g`) az `OutOfMemoryError` elkerülése érdekében. + +## Pro tippek – A helyreállítás megbízhatóvá tétele + +* **Figyelmeztetések naplózása fájlba** – irányítsa a `System.err`‑t egy logger‑be, így auditnyoma lesz annak, mi lett javítva. +* **Érvényesítés a helyreállítás után** – futtassa a `doc.updatePageLayout();`‑t, majd ellenőrizze újra az oldalszámot; néha a layout megváltozik a törött szakaszok javítása után. +* **Kötegelt helyreállítás automatizálása** – csomagolja a demót egy ciklusba, amely egy mappában lévő sérült fájlokat dolgozza fel, minden alkalommal ugyanazt a `LoadOptions`‑t használva. + +## Összegzés + +Most már pontosan tudja, **how to recover corrupted word file** az Aspose.Words for Java használatával. Egy `LoadOptions` példány létrehozásával, a **set recovery mode** megfelelő stratégiára állításával, és a dokumentum ezen beállításokkal történő betöltésével biztonságosan **open corrupted word document** anélkül, hogy az alkalmazás összeomlana. A fenti mintakód egy komplett, azonnal futtatható megoldás, amely kiírja az oldalszámot, és még egy megtisztított másolatot is elment. + +Mi a következő? Próbálja meg a helyreállítási módot `RECOVER_WITHOUT_WARNINGS`‑re cserélni, és hasonlítsa össze a konzol kimenetét, vagy kísérletezzen titkosított dokumentumok betöltésével (ehhez jelszót kell megadni a + +## Kapcsolódó oktatóanyagok + +- [Aspose.Words Java: Átfogó útmutató a Word-dokumentumok feldolgozásához](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Hogyan konvertáljunk Word-et PDF-be az Aspose.Words for Java használatával](/words/english/java/document-converting/using-document-converting/) +- [Hogyan hasonlítsunk össze két Word-fájlt az Aspose.Words for Java segítségével](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/hungarian/java/document-styling/_index.md index afa04f0e0a..82bb3bd26b 100644 --- a/words/hungarian/java/document-styling/_index.md +++ b/words/hungarian/java/document-styling/_index.md @@ -41,8 +41,10 @@ Tanuld meg, hogyan formázhatod a bekezdéseket és a szöveget dokumentumokban Tanuld meg, hogyan szabhatsz testre dokumentumtémákat az Aspose.Words for Java segítségével. Ez az átfogó útmutató lépésről lépésre bemutatja az útmutatást és forráskód példákat. ### [Dokumentum vízjelezése és oldalbeállítás](./document-watermarking-page-setup/) Tanuld meg, hogyan alkalmazhatsz vízjeleket és állíthatsz be oldalkonfigurációkat az Aspose.Words for Java segítségével. Átfogó útmutató forráskóddal. -### [Dokumentum fejléc és lábléc formázása](./document-header-footer-styling/) +### [Dokumentum fejlőc és lábléc formázása](./document-header-footer-styling/) Tanuld meg, hogyan formázhatod a dokumentumok fejlécét és láblécét az Aspose.Words for Java használatával ebben a részletes útmutatóban. Lépésről lépésre útmutató és forráskód is mellékelve. +### [Alapértelmezett betűtípus beállítása az Aspose.Words for Java-ban – Teljes útmutató](./set-default-font-settings-in-aspose-words-for-java-complete/) +Tanuld meg, hogyan állítsd be az alapértelmezett betűtípust az Aspose.Words for Java segítségével. Lépésről lépésre útmutató forráskóddal. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/hungarian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..428a2eb661 --- /dev/null +++ b/words/hungarian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Állítsa be az alapértelmezett betűtípus-beállításokat az Aspose.Words + for Java-ban, és tanulja meg, hogyan állíthat be betűtípus-beállításokat, valamint + hogyan észlelheti a hiányzó betűtípusokat néhány kódsorral. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: hu +og_description: Állítsa be az alapértelmezett betűtípus-beállításokat az Aspose.Words + for Java-ban, tanulja meg a betűtípus-beállítások megadását, és észlelje gyorsan + és megbízhatóan a hiányzó betűtípusokat. +og_title: Alapértelmezett betűtípus-beállítások megadása az Aspose.Words for Java-ban +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Alapértelmezett betűtípus beállítása az Aspose.Words for Java-ban – Teljes + útmutató +url: /hu/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Alapértelmezett betűtípus-beállítások megadása az Aspose.Words for Java‑ban – Teljes útmutató + +Gondolkodtál már azon, hogyan **állítsd be az alapértelmezett betűtípus-beállításokat** egy Word-dokumentum betöltésekor az Aspose.Words for Java‑val? Nem vagy egyedül. A hiányzó glifek egy kifinomult jelentést összezavart káoszzá változtathatnak, és a betűtípus‑helyettesítési figyelmeztetések korai elkapása órákat takarít meg a hibakeresésben. + +Ebben az oktatóanyagban egy tömör, vég‑től‑végig példán keresztül mutatjuk be, hogyan **állítható be az alapértelmezett betűtípus-beállítás**, hogyan **állítható be a betűtípus-beállítás** programozottan, és bemutatunk egy megbízható módszert a **hiányzó betűtípusok észlelésére**, mielőtt azok tönkretennék a megjelenést. + +--- + +## Amit megtanulsz + +- Hogyan hozzunk létre egy `LoadOptions` objektumot egy új `FontSettings` példánnyal. +- Hogyan csatoljunk egy figyelőt, amely **észleli a hiányzó betűtípusokat** a dokumentum betöltése során. +- Hogyan töltsünk be egy DOCX fájlt, miközben a figyelő csendben jelenti a helyettesítéseket. +- Tippek a tartalékbetűtípusok testreszabásához és a termelésben előforduló széljegyek kezeléséhez. + +Nincs szükség extra könyvtárakra, nincs rejtett konfigurációs fájl—csak tiszta Java és Aspose.Words. + +--- + +## Előfeltételek + +Mielőtt belevágunk, győződj meg róla, hogy rendelkezel: + +1. **Aspose.Words for Java** (23.10 vagy újabb verzió) a classpath‑odon. +2. Java 17 (vagy újabb) fejlesztői csomag – bármely modern JDK megfelelő. +3. Egy DOCX fájl, amely szándékosan olyan betűtípust használ, amely nincs telepítve (pl. *„MissingFont.ttf”*). + +Ha hiányzik az Aspose JAR, szerezd be a hivatalos Maven tárolóból: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Ennyi—nem szükséges további betűtípusokat telepíteni ehhez a demóhoz. + +--- + +## 1. lépés: LoadOptions létrehozása és **Alapértelmezett betűtípus-beállítások megadása** + +Az első dolog, amire szükségünk van, egy tiszta `LoadOptions` objektum, amely megmondja az Aspose-nak, hogyan viselkedjen ismeretlen betűtípusok esetén. A `setFontSettings(new FontSettings())` hívással **beállítjuk az alapértelmezett betűtípus-beállításokat**, amelyek egy üres tartaléklista‑val indulnak. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Miért fontos:** +> Ha nem konfigurálsz betűtípusokat kifejezetten, az Aspose a rendszer alapértelmezett gyűjteményére támaszkodik, ami elrejtheti a hiányzó betűtípusok problémáit. Egy új `FontSettings` példánytól indulva teljes irányítást kapsz arról, hogy mely betűtípusok tekinthetők érvényesnek. + +--- + +## 2. lépés: Figyelő csatolása a **hiányzó betűtípusok észleléséhez** + +Az Aspose minden végrehajtott helyettesítéshez egy `WarningInfo` objektumot generál. A `WarningType.FONT_SUBSTITUTION` figyelésével **észlelhetjük a hiányzó betűtípusokat**, amint a dokumentum beolvasásra kerül. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro tipp:** A figyelő ugyanazon a szálon fut, amely a dokumentumot betölti, így gyakorlatilag nincs teljesítménybeli hátránya. Ha későbbi elemzéshez szeretnél figyelmeztetéseket gyűjteni, tedd őket egy `List`‑be a közvetlen kiírás helyett. + +--- + +## 3. lépés: Dokumentum betöltése a konfigurált beállításokkal + +Miután **beállítottuk a betűtípus-beállításokat** és előkészítettük a figyelőt, egyszerűen betöltjük a fájlt. Bármely hiányzó betűtípus azonnal aktiválja a visszahívásunkat. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Ha a forrásfájl olyan betűtípust hivatkozik, amely nincs telepítve, a kimenet hasonló lesz: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Ez a sor pontosan megmutatja, melyik betűtípus hiányzott és melyik tartalékot használták—tökéletes naplózáshoz vagy felhasználói visszajelzéshez. + +--- + +## 4. lépés: Normál feldolgozás folytatása (opcionális) + +Ekkor a dokumentum teljesen be van töltve, és folytathatod a kívánt manipulációkat—szerkesztés, PDF‑re konvertálás vagy szöveg kinyerése. A figyelő már elvégezte a feladatát, így nincs szükség további ellenőrzésekre. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Mi van, ha egyedi tartalékot szeretnél?** +> A `FontSettings` üresen hagyása helyett hozzáadhatsz konkrét betűtípusokat: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Most minden hiányzó betűtípus *Times New Roman*-ra lesz cserélve—megbízható választás a legtöbb nyugati dokumentumhoz. + +--- + +## Vizuális áttekintés + +![Diagram, amely bemutatja, hogyan állítsuk be az alapértelmezett betűtípus-beállításokat az Aspose.Words for Java-ban](image.png "Az alapértelmezett betűtípus-beállítások folyamatának diagramja") + +*Alt szöveg: alapértelmezett betűtípus-beállítások az Aspose.Words for Java-ban folyamatábra.* + +A diagram ábrázolja a folyamatot a `LoadOptions` inicializálásától (ahol **beállítjuk az alapértelmezett betűtípus-beállításokat**) a figyelő csatolásáig (a **hiányzó betűtípusok észleléséhez**) és végül a dokumentum betöltéséig. + +--- + +## Gyakori buktatók és hogyan kerüld el őket + +| Buktató | Miért fordul elő | Megoldás | +|---------|----------------|-----| +| **Elfelejtetted meghívni a `setFontSettings`‑t** | Az Aspose a rendszer alapértelmezett beállításait használja, elrejtve a hiányzó betűtípusokat. | Mindig hozz létre egy új `FontSettings` példányt, és rendeld hozzá a `LoadOptions`‑hoz. | +| **A figyelő nem aktiválódik** | A figyelőt a dokumentum betöltése után adtad hozzá. | Add hozzá a figyelőt *mielőtt* meghívod a `new Document(...)`‑t. | +| **Útvonal elírás `FileNotFoundException`‑t okoz** | A keménykódolt útvonal nem egyezik az operációs rendszer kis‑/nagybetű érzékenységével. | Használd a `Paths.get("...").toAbsolutePath()`‑t, vagy állíts be egy relatív útvonalat a projekt gyökeréből. | +| **Több hiányzó betűtípus elárasztja a naplókat** | Nagy dokumentumok több tucat figyelmeztetést generálhatnak. | Szűrd ki a duplikátumokat, vagy aggregáld az üzeneteket egy `Set`‑ben a kiírás előtt. | + +--- + +## A megoldás kiterjesztése + +Ha egy teljes alkalmazásra szeretnél **betűtípus-beállításokat** megadni, fontold meg egy singleton `FontSettings` létrehozását, és használd újra minden `LoadOptions`‑nél. Így egységes tartalékstratégiát tartasz fenn, és elkerülöd az objektumok többszöri létrehozását. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Most a kódbázis bármely része egyszerűen meghívhatja a `FontConfig.getLoadOptions()`‑t, és azonnal élvezheti ugyanazt a **alapértelmezett betűtípus-beállítások megadásának** logikát. + +--- + +## Következtetés + +Most már mindent áttekintettünk, ami szükséges az **alapértelmezett betűtípus-beállítások megadásához** az Aspose.Words for Java‑ban, a **betűtípus-beállítások programozott megadásához**, és a **hiányzó betűtípusok észleléséhez**, mielőtt azok tönkretennék a kimenetet. A teljes, futtatható példa a fenti kódrészletekben található, és egyszerűen beillesztheted az IDE‑dbe, hogy láthasd a figyelmeztetéseket működés közben. + +Következő lépések? Próbáld ki a tartalékbetűtípus cseréjét, kísérletezz különböző dokumentumformátumokkal (DOC, RTF, HTML), vagy integráld a figyelőgyűjtőt egy felügyeleti műszerfalba. Minél többet játszol a `FontSettings`‑szel, annál nagyobb lesz a bizalmad abban, hogy a generált dokumentumok pontosan úgy néznek ki, ahogy elvárod—nincsenek meglepetések, nincsenek törött glifek. + +Van kérdésed vagy egy bonyolult betűtípus‑helyettesítési helyzet? Hagyj egy megjegyzést alább, és jó kódolást! + +## Kapcsolódó oktatóanyagok + +- [Betűtípus tartalékbeállítások megadása](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Betűtípus tartalékbeállítások megadása](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Betűtípus tartalékbeállítások megadása](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/java/images-shapes/_index.md b/words/hungarian/java/images-shapes/_index.md index 234e2145c9..f1fc747dec 100644 --- a/words/hungarian/java/images-shapes/_index.md +++ b/words/hungarian/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Tanulja meg, hogyan hozhat létre kiváló minőségű miniatűröket és egyedi ### [Word dokumentum létrehozása Java – Téglalap alakzat hozzáadása árnyékhatással](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Ismerje meg, hogyan adhat hozzá árnyékhatású téglalap alakzatot a Word dokumentumhoz Java-ban az Aspose.Words segítségével. +### [Téglalap alakzat létrehozása Java Word dokumentumban – Teljes lépésről‑lépésre útmutató](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Ismerje meg, hogyan hozhat létre téglalap alakzatot Word dokumentumban Java segítségével, részletes, lépésről‑lépésre útmutatóval. + ## További források - [Aspose.Words Java dokumentációhoz](https://reference.aspose.com/words/java/) diff --git a/words/hungarian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/hungarian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..05fed38c2a --- /dev/null +++ b/words/hungarian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-26 +description: Hozzon létre egy téglalap alakzatot egy Java Word dokumentumban, és alkalmazzon + árnyékhatást. Tanulja meg, hogyan adjon hozzá alakzati árnyékot, állítsa be az árnyék + távolságát, és mentse el a fájlt. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: hu +og_description: Hozzon létre egy téglalap alakzatot egy Java Word dokumentumban, alkalmazzon + árnyékhatást, adjon hozzá árnyékot az alakzathoz, és állítsa be az árnyék távolságát + az Aspose.Words segítségével. +og_title: Téglalap alakzat létrehozása Java Word dokumentumban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Téglalap alakzat létrehozása Java Word dokumentumban – Teljes lépésről‑lépésre + útmutató +url: /hu/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Téglalap alakzat létrehozása Java Word dokumentumban – Teljes lépésről‑lépésre útmutató + +Valaha is szükséged volt **téglalap alakzat létrehozására** egy Java Word dokumentumban, de nem tudtad, hol kezdjed? Nem vagy egyedül – sok fejlesztő ütközik ebbe a problémába, amikor programozottan generál jelentéseket vagy számlákat. Ebben az útmutatóban pontosan bemutatjuk, hogyan **téglalap alakzat létrehozása**, alkalmazz egy kifinomult árnyékot, és finomhangold az árnyék távolságát, hogy a végeredmény professzionális legyen. + +Az Aspose.Words for Java-t fogjuk használni, egy robusztus könyvtárat, amely lehetővé teszi a Word fájlok manipulálását anélkül, hogy a Microsoft Office telepítve lenne. A útmutató végére képes leszel **create word document java** projekteket készíteni, amelyek **add shape shadow**, **apply shadow effect**, és **set shadow distance** néhány kódsorral. + +--- + +## Amit építeni fogsz + +- Egy új `.docx` fájl, amely egy cián színű téglalapot tartalmaz. +- Egy valósághű vetett árnyék, amely elmosott, szögelt és részben átlátszó. +- Teljes irányítás az árnyék alakzattól való távolsága felett. +- Egy azonnal futtatható Java osztály, amelyet bármely Maven vagy Gradle projektbe beilleszthetsz. + +Nincs külső eszköz, nincs manuális UI lépés – csak tiszta kód. + +--- + +## Előfeltételek + +- Java 8 vagy újabb (a kód működik Java 11, Java 17 stb. verziókon). +- Aspose.Words for Java könyvtár (elérhető a Maven Centralon). +- Egy kedvenc IDE vagy szövegszerkesztő (IntelliJ IDEA, Eclipse, VS Code …). +- Alapvető ismeretek a Java szintaxisról. + +Ha még sosem adtál hozzá Maven függőséget, itt egy gyors kódrészlet: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Most merüljünk el. + +--- + +## 1. lépés: Téglalap alakzat létrehozása Word dokumentumban + +Az első dolog, amire szükségünk van, egy üres dokumentum és egy `DocumentBuilder`. Tekintsd a buildert egy tollra, amely a dokumentumba ír. Miután megvan, egyetlen metódushívással **create rectangle shape**-t hozhatunk létre. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Miért fontos:** Az `insertShape` metódus nem csak a geometriát hozza létre, hanem hozzáadja az alakzatot a dokumentum belső gyűjteményéhez is, így azonnal elkezdheted formázni azt. + +--- + +## 2. lépés: Árnyékhatás alkalmazása az alakzatra + +Miután a téglalap a lapon megjelenik, **apply shadow effect**-et fogunk alkalmazni. Az árnyékok mélységet adnak, az alakzatot úgy érzik, mintha a lapról kiemelkedne – egy finom UI fejlesztés, amely javíthatja a jelentések olvashatóságát. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro tipp:** A `5.0` elmosás természetesnek tűnik a legtöbb képernyőn megjelenített dokumentumnál. Ha nyomtatod, érdemes egy kicsit alacsonyabb értéket választani, hogy elkerüld a homályos megjelenést. + +--- + +## 3. lépés: Árnyék távolság beállítása – Finomhangolás + +Az árnyékok nem csak az elmosásról szólnak; a megfelelő eltolásra is szükség van. Itt jön képbe a **set shadow distance**. A `7.0` pont távolság mérsékelt eltolást eredményez, amely észrevehető, de nem túl erőteljes. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Mi van, ha nagyobb eltolásra van szükséged?** Növeld az értéket; csökkentsd, ha szorosabb megjelenést szeretnél. Ne feledd, a távolság az szöggel együtt határozza meg az árnyék helyzetét. + +--- + +## 4. lépés: Dokumentum mentése – A munka mentése + +Végül a dokumentumot leírjuk a lemezre. Módosítsd az elérési utat arra a helyre, ahol a fájlt tárolni szeretnéd. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Az osztály futtatása létrehozza a `shadow.docx` fájlt, amely Microsoft Wordben vagy LibreOffice‑ban megnyitva egy cián téglalapot mutat egy lágy szürke árnyékkal, 45°‑os szöggel és 7 pont eltolással. + +--- + +## Teljes működő példa + +Az alábbiakban a teljes, másolás‑és‑beillesztésre készen álló kód található. Tartalmazza az összes importot, megjegyzést és a végső `save` hívást. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Várható kimenet:** Nyisd meg a `shadow.docx` fájlt → egy cián téglalapot látsz az első oldal közepén, amely egy finom szürke árnyékot vet, amely enyhén a jobb‑alsó sarok felé van eltolva. Az árnyék elmosása és átlátszósága természetes fényhatást kölcsönöz. + +--- + +## Gyakori kérdések és speciális esetek + +### „Használhatok másik alakzatot?” + +Természetesen. Cseréld le a `ShapeType.RECTANGLE`-t `ShapeType.OVAL`, `ShapeType.LINE` vagy bármely más támogatott enumra. A többi árnyék kód változatlan marad. + +### „Mi van, ha több árnyékra van szükségem?” + +Az Aspose.Words csak egy árnyékot támogat alakzatonként. Több árnyék szimulálásához duplikáld az alakzatot, minden másolatot eltolva, és állítsd be az átlátszóságot. + +### „Látható az árnyék a LibreOffice‑ban?” + +Igen – az Aspose.Words szabványos OOXML-et ír, amelyet a LibreOffice helyesen értelmez. Az árnyék kissé másként jelenhet meg a renderelő motorok miatt, de a hatás megmarad. + +### „Hogyan változtassam meg az árnyék színét a márkámhoz igazodva?” + +Egyszerűen cseréld le a `java.awt.Color.GRAY`-t bármely általad preferált `java.awt.Color`-ra, például `new java.awt.Color(0, 120, 215)`-ra egy vállalati kékhez. + +--- + +## Kép illusztráció + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illusztráció, amely egy cián téglalapot mutat szürke vetett árnyékkal egy Word dokumentumban. + +--- + +## Összefoglalás és következő lépések + +Áttekintettük, hogyan kell **create rectangle shape**, **apply shadow effect**, **add shape shadow**, és **set shadow distance** az Aspose.Words for Java segítségével. A kód önálló, bármely modern JDK-n fut, és egy kifinomult `.docx` fájlt állít elő, amely készen áll a terjesztésre. + +Szeretnél tovább menni? Próbáld ki: + +- Szöveg hozzáadása a téglalap belsejébe a `builder.moveTo(rectangleShape.getAbsolutePosition())` segítségével. +- Alakzatok táblázatának létrehozása egy diagram felépítéséhez. +- A dokumentum PDF‑be exportálása (`doc.save("output.pdf", SaveFormat.PDF);`). + +Ezek mind a most megismert alapokra épülnek, így magabiztosan tudod bővíteni a példát. + +--- + +## Záró gondolatok + +A **create word document java** feladatok, például az alakzatok és árnyékok elsajátítása óriási előnyt jelent a jelentések, szerződések vagy marketing anyagok automatizálásában. A bemutatott megközelítés tiszta, karbantartható, és – ami a legfontosabb – könnyen testreszabható bármilyen vizuális stílushoz. + +Próbáld ki a kódot, állítsd be az elmosást, a szöget és a távolságot, és nézd, ahogy a dokumentumaid a közönségesből a kifinomulttá változnak. Ha elakadsz, hagyj megjegyzést alul; szívesen segítek. + +Boldog kódolást! + +## Kapcsolódó oktatóanyagok + +- [Word dokumentum létrehozása Java – Téglalap alakzat hozzáadása árnyékhatással](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Űrlapmezők létrehozása és tartalom hozzáadása DocumentBuilderrel az Aspose.Words for Java-ban](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [PDF létrehozása Wordből vonalkód generálással – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/indonesian/java/document-conversion-and-export/_index.md index 23279a66a5..fdb64c55a4 100644 --- a/words/indonesian/java/document-conversion-and-export/_index.md +++ b/words/indonesian/java/document-conversion-and-export/_index.md @@ -93,15 +93,30 @@ Pelajari cara memformat tabel dan menerapkan gaya tabel di Aspose.Words for Java ### [Konversi docx ke markdown – Ekspor Persamaan Matematika ke LaTeX dengan Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Pelajari cara mengonversi file DOCX menjadi markdown dan mengekspor persamaan matematika ke format LaTeX menggunakan Aspose.Words. +### [Simpan Word sebagai Markdown – Ekspor Matematika ke LaTeX dengan Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Simpan dokumen Word sebagai file markdown dan ekspor persamaan matematika ke format LaTeX menggunakan Aspose.Words for Java. + ### [Cara Menyisipkan Gambar dalam Markdown Saat Mengonversi DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Pelajari cara menyisipkan gambar ke dalam file Markdown selama proses konversi DOCX menggunakan Aspose.Words for Java. +### [Menyematkan Gambar sebagai Base64 saat Mengonversi DOCX ke Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Pelajari cara menyisipkan gambar dalam format Base64 selama konversi DOCX ke Markdown menggunakan Aspose.Words for Java. + ### [Simpan Dokumen sebagai TXT – Panduan Cepat Mengekspor Matematika Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Pelajari cara menyimpan dokumen Word sebagai file TXT sambil mengekspor persamaan matematika dengan Aspose.Words. +### [Ekspor docx ke txt dengan Java – Panduan Pemrograman Lengkap](./export-docx-to-txt-with-java-complete-programming-guide/) +Pelajari cara mengekspor file DOCX menjadi TXT menggunakan Aspose.Words for Java dengan contoh kode lengkap. + ### [Buat PDF Aksesibel dari DOCX – Panduan Lengkap](./create-accessible-pdf-from-docx-complete-guide/) Pelajari cara mengonversi file DOCX menjadi PDF yang memenuhi standar aksesibilitas, termasuk tag, teks alternatif, dan struktur dokumen. +### [Simpan Dokumen sebagai PDF dengan Aspose.Words Java – Panduan Aksesibilitas Lengkap](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Pelajari cara menyimpan dokumen sebagai PDF yang sepenuhnya dapat diakses menggunakan Aspose.Words for Java, termasuk tag, teks alternatif, dan struktur. + +### [Buat PDF Aksesibel di Java – Panduan Tagging Lengkap](./create-accessible-pdf-in-java-full-tagging-guide/) +Pelajari cara membuat PDF yang sepenuhnya dapat diakses dengan tag lengkap menggunakan Aspose.Words for Java. + ## Pertanyaan yang Sering Diajukan **Q: Bagaimana cara menambahkan watermark ke PDF yang sudah ada menggunakan Aspose.Words?** diff --git a/words/indonesian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/indonesian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..7f94b03618 --- /dev/null +++ b/words/indonesian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-26 +description: Buat PDF yang dapat diakses di Java dengan kode langkah demi langkah. + Pelajari cara menandai PDF untuk aksesibilitas dan mengaktifkan penandaan PDF menggunakan + PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: id +og_description: Buat PDF yang dapat diakses di Java dengan kode langkah demi langkah. + Pelajari cara menandai PDF untuk aksesibilitas dan mengaktifkan penandaan PDF menggunakan + PdfSaveOptions. +og_title: Buat PDF yang Aksesibel di Java – Panduan Tagging Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Buat PDF yang Aksesibel di Java – Panduan Tagging Lengkap +url: /id/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Membuat PDF yang Aksesibel di Java – Panduan Tagging Lengkap + +Pernah bertanya-tanya bagaimana cara **membuat PDF yang aksesibel** secara langsung dari kode Java? Anda tidak sendirian. Banyak pengembang perlu melayani pengguna yang mengandalkan pembaca layar, dan perbedaan antara PDF biasa dan PDF yang aksesibel bisa sangat besar. Dalam tutorial ini kami akan menjelaskan **cara menandai PDF untuk aksesibilitas**, menunjukkan **cara membuat PDF yang ditandai** dengan Aspose PDF for Java, dan mengungkap langkah‑langkah tepat untuk **menambahkan tag aksesibilitas ke PDF** sehingga setiap pembaca mendapatkan informasi yang sama. + +Kami juga akan membahas praktik terbaik **mengaktifkan tagging PDF**, jebakan umum, dan contoh lengkap yang dapat dijalankan yang dapat Anda masukkan ke dalam proyek Anda hari ini. Tanpa referensi yang samar—hanya kode konkret, penjelasan, dan file akhir yang dapat Anda buka di Adobe Acrobat untuk memverifikasi tag. + +## Apa yang Akan Anda Pelajari + +- Alasan di balik tagging PDF dan kepatuhan aksesibilitas. +- Prasyarat dan penyiapan pustaka (Aspose PDF for Java 23.10 atau lebih baru). +- Cara **membuat PDF yang aksesibel** dari awal, langkah demi langkah. +- Cara **menambahkan tag aksesibilitas ke PDF** selain pemanggilan dasar `setTagDocumentStructure`. +- Tips untuk menguji output dan memecahkan masalah umum. + +Pada akhir panduan ini Anda akan dapat menghasilkan PDF yang lolos pemeriksaan WCAG 2.1 AA dan tetap terlihat profesional. + +--- + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +| Persyaratan | Alasan | +|-------------|--------| +| **Java 8+** | Fitur bahasa modern dan penanganan Unicode yang lebih baik. | +| **Aspose PDF for Java** (v23.10 atau lebih baru) | Menyediakan kelas `PdfSaveOptions` dan dukungan tagging. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, dll.) | Untuk kompilasi dan debugging yang mudah. | +| **Izin menulis** ke folder tempat PDF akan disimpan | Pemanggilan `doc.save` memerlukan jalur yang dapat ditulisi. | + +Jika Anda belum menambahkan Aspose PDF ke proyek Anda, masukkan dependensi Maven berikut ke dalam `pom.xml` Anda: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Tip Pro:** Gunakan versi terbaru; rilis yang lebih baru meningkatkan akurasi tagging dan menambahkan fitur aksesibilitas spesifik bahasa. + +--- + +## Langkah 1: Siapkan Kerangka Dokumen + +Pertama, kami membuat objek `Document` baru. Anggaplah itu sebagai kanvas kosong yang nantinya akan menampung tag yang kami perlukan untuk aksesibilitas. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Mengapa ini penting:** Tanpa konten apa pun, tidak ada yang dapat ditandai. Menambahkan bahkan `TextFragment` sederhana memberi mesin tagging sesuatu untuk diproses, dan secara otomatis membuat tag `

` (paragraf) ketika kami kemudian mengaktifkan tagging struktur. + +--- + +## Langkah 2: Buat PDF Save Options (Inti dari Tagging) + +Sekarang kami menyiapkan opsi yang memberi tahu Aspose PDF untuk menyematkan pohon struktur logis di dalam file. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Pemanggilan `setTagDocumentStructure(true)` adalah saklar **mengaktifkan tagging PDF**. Ketika bernilai true, pustaka membangun pohon tag yang mencerminkan tata letak visual, sehingga PDF dapat dibaca oleh teknologi bantu. + +> **Catatan:** Ini adalah cara paling sederhana untuk **cara membuat PDF yang ditandai**. Untuk kontrol yang lebih detail (misalnya, mengatur bahasa atau tag khusus), Anda dapat menjelajahi `pdfOptions.setTagLanguage("en-US")` dan `pdfOptions.setTagStructureTreeRoot(...)`. + +--- + +## Langkah 3: Simpan PDF yang Aksesibel + +Akhirnya, kami menulis dokumen ke disk menggunakan opsi yang baru saja dikonfigurasi. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Setelah `doc.save` selesai, Anda akan menemukan `accessible.pdf` di folder `output`. Buka di Adobe Acrobat dan lihat **File → Properties → Description → Tags** – Anda seharusnya melihat pohon tag yang terisi. + +--- + +## Cara Menandai PDF untuk Aksesibilitas – Lebih dari Dasar + +Potongan tiga langkah di atas sudah **menambahkan tag aksesibilitas ke PDF**, tetapi dokumen dunia nyata sering membutuhkan sedikit penyempurnaan. Berikut beberapa peningkatan yang dapat Anda tambahkan: + +### 1. Atur Bahasa Dokumen + +Pembaca layar menggunakan atribut bahasa untuk mengucapkan teks dengan benar. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Berikan Judul dan Subjek + +Metadata membantu alat bantu memberikan konteks sebelum pengguna membuka file. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Tandai Gambar dengan Teks Alternatif + +Jika Anda menyisipkan gambar, mereka memerlukan deskripsi `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Tandai Header Tabel + +Tabel terkenal membuat pembaca bingung kecuali Anda menandai baris header. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Langkah tambahan ini membuat PDF Anda tidak hanya *secara teknis* ditandai, tetapi benar‑benar **aksesibel** untuk beragam audiens. + +--- + +## Kesalahan Umum Saat Mengaktifkan Tagging PDF + +| Gejala | Penyebab Kemungkinan | Perbaikan | +|--------|----------------------|-----------| +| Tag tidak muncul di Acrobat | `setTagDocumentStructure` dibiarkan `false` | Pastikan Anda memanggil `pdfOptions.setTagDocumentStructure(true)`. | +| Urutan baca salah | Tata letak kompleks tanpa tag eksplisit | Gunakan `pdfOptions.setTagStructureTreeRoot(...)` untuk mendefinisikan urutan khusus. | +| Gambar dibaca sebagai “image” tanpa deskripsi | Tidak ada teks alternatif yang diatur | Panggil `image.getAlternativeText().setValue("...")`. | +| Bahasa tidak dikenali | `setTagLanguage` tidak disertakan atau locale salah | Berikan kode bahasa BCP‑47 (`en-US`, `fr-FR`). | + +--- + +## Verifikasi Hasil – Apa yang Diharapkan + +Setelah menjalankan program, buka `output/accessible.pdf` di Adobe Acrobat Reader: + +1. **Panel Tag** (`View → Show/Hide → Navigation Panes → Tags`) harus menampilkan hierarki seperti `/Document → /Part → /Sect → /Para`. +2. **Urutan baca** harus mengikuti alur visual (teks dulu, kemudian gambar). +3. **Pembaca layar** (NVDA, VoiceOver) akan membaca “Hello, accessible PDF!” alih-alih hanya “Page 1”. + +Jika salah satu dari item tersebut tidak ada, periksa kembali langkah-langkah di atas—terutama pemanggilan `setTagDocumentStructure`. + +--- + +## Contoh Lengkap yang Dapat Dijalankan (Siap Salin‑Tempel) + + + +## Tutorial Terkait + +- [Buat PDF yang Aksesibel dari Word – Konversi ke PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Buat PDF yang Aksesibel dari DOCX – Panduan Lengkap](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Cara menyimpan dokumen sebagai PDF dengan Aspose.Words untuk Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/indonesian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/indonesian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..7e966c7f59 --- /dev/null +++ b/words/indonesian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Sematkan gambar sebagai base64 saat Anda mengonversi docx ke markdown + dengan Aspose.Words untuk Java. Pelajari cara mengonversi Word ke markdown, menyimpan + Word sebagai markdown, dan menangani gambar. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: id +og_description: Sematkan gambar sebagai base64 saat mengonversi docx ke markdown dengan + Aspose.Words untuk Java. Panduan lengkap untuk mengonversi Word ke markdown dan + menyimpan Word sebagai markdown. +og_title: Sematkan Gambar sebagai Base64 Saat Mengonversi DOCX ke Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Sematkan Gambar sebagai Base64 Saat Mengonversi DOCX ke Markdown +url: /id/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Menyematkan Gambar sebagai Base64 Saat Mengonversi DOCX ke Markdown + +Pernah bertanya-tanya bagaimana cara **menyematkan gambar sebagai base64** saat Anda **mengonversi docx ke markdown**? Anda bukan satu‑satunya—para pengembang terus menanyakan cara menjaga gambar tetap inline tanpa harus mengelola file terpisah. Kabar baiknya, Aspose.Words for Java membuatnya sangat mudah: Anda dapat mengonversi dokumen Word ke Markdown dan secara otomatis menyematkan setiap gambar sebagai string Base64. + +Dalam tutorial ini kita akan membahas seluruh proses—dari memuat file `.docx` yang berisi gambar, mengonfigurasi callback `MarkdownSaveOptions` yang melakukan pekerjaan berat, hingga menyimpan hasilnya sebagai file `.md` yang bersih. Pada akhir tutorial Anda akan tahu persis cara **mengonversi word ke markdown**, **mengonversi gambar ke base64**, dan **menyimpan word sebagai markdown** tanpa meninggalkan folder gambar yang terpisah. Tanpa alat eksternal, tanpa pemrosesan manual—hanya kode Java murni yang dapat Anda masukkan ke proyek apa pun. + +## Apa yang Anda Butuhkan + +- **Java 17** (atau JDK terbaru) – kode menggunakan sintaks lambda, tetapi Anda dapat menyesuaikannya untuk versi yang lebih lama. +- **Aspose.Words for Java** library (versi terbaru per 2026). Tambahkan dependensi Maven atau JAR ke classpath Anda. +- File **DOCX** contoh yang berisi setidaknya satu gambar. +- IDE atau editor teks sederhana—Visual Studio Code, IntelliJ IDEA, atau bahkan `vim` sudah cukup. + +Jika semua sudah siap, mari kita mulai. + +## Langkah 1: Muat Dokumen Word + +Pertama kita buat instance `Document` yang menunjuk ke file sumber. Langkah ini sama baik Anda **mengonversi docx ke markdown** maupun hanya membaca file untuk keperluan lain. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Mengapa ini penting:** Objek `Document` adalah titik masuk untuk setiap operasi Aspose. Ia menyimpan seluruh struktur Word—termasuk gambar, tabel, dan gaya—sehingga callback nantinya dapat memeriksa setiap sumber daya. + +## Langkah 2: Buat MarkdownSaveOptions dan Daftarkan Callback Penyimpanan Sumber Daya + +Keajaiban berada di dalam `MarkdownSaveOptions`. Dengan melampirkan `IResourceSavingCallback` kita mendapatkan kontrol atas cara setiap sumber daya eksternal (seperti gambar) ditulis. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### Mengapa Menggunakan `setSaveToMemory(true)`? + +Ketika `saveToMemory` bernilai true, Aspose menulis byte gambar ke aliran memori alih‑alih ke file. Ekspor Markdown kemudian mengonversi aliran tersebut menjadi string Base64 dan menyisipkannya langsung ke tag gambar Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Itulah inti dari **menyematkan gambar sebagai base64**. + +## Langkah 3: Simpan Dokumen sebagai Markdown + +Setelah callback terpasang, langkah terakhir cukup memanggil `save`. Di sinilah kita benar‑benar **mengonversi word ke markdown** dan, berkat callback, juga **mengonversi gambar ke base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Hasil:** `out.md` berisi teks Markdown dengan setiap gambar direpresentasikan sebagai URI `data:`. Tidak ada file gambar tambahan yang dibuat di disk, sehingga folder tetap rapi. + +## Langkah 4: Verifikasi Output dan Kesalahan Umum + +Buka `out.md` yang dihasilkan di penampil Markdown apa pun (VS Code, GitHub, atau generator situs statis). Anda seharusnya melihat sesuatu seperti: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Daftar Periksa Pemecahan Masalah + +| Masalah | Penyebab Kemungkinan | Solusi | +|---------|----------------------|--------| +| Gambar muncul sebagai tautan rusak | `setSaveToMemory` tidak disertakan | Pastikan `args.setSaveToMemory(true);` berada di dalam callback | +| String Base64 terpotong | Encoding file output tidak cocok | Simpan Markdown menggunakan UTF‑8 (default untuk Aspose) | +| Nama file tidak terduga | `setKeepResourceOriginalName(true)` | Biarkan `false` untuk memaksa logika penamaan khusus | + +## Langkah 5: Variasi Lanjutan (Opsional) + +### Konversi Hanya Gambar yang Dipilih + +Jika Anda hanya ingin menyematkan gambar tertentu (misalnya yang berukuran lebih dari 100 KB), tambahkan pemeriksaan ukuran: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Gunakan Format Gambar yang Berbeda + +`ResourceSavingArgs` memberikan Anda byte mentah, sehingga Anda dapat meng‑encode ulang JPEG menjadi PNG sebelum disematkan—berguna ketika konsumen Markdown target lebih menyukai PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Penyesuaian ini menunjukkan betapa fleksibelnya pendekatan **menyematkan gambar sebagai base64** saat Anda **mengonversi docx ke markdown**. + +## Kesimpulan + +Anda baru saja mempelajari cara **menyematkan gambar sebagai base64** saat **mengonversi docx ke markdown** menggunakan Aspose.Words for Java. Dengan menambahkan `IResourceSavingCallback` sederhana, library melakukan semua pekerjaan berat: ia **mengonversi word ke markdown**, **mengonversi gambar ke base64**, dan akhirnya **menyimpan word sebagai markdown** dengan satu panggilan `save`. + +Silakan bereksperimen—coba aturan penyaringan gambar yang berbeda, alihkan ke output HTML, atau rangkaikan langkah ini dengan generator situs statis. Pola yang sama juga berlaku untuk format lain (HTML, EPUB), sehingga Anda dapat menggunakan kembali callback di mana pun diperlukan sumber daya inline. + +**Langkah Selanjutnya:** +- Jelajahi `HtmlSaveOptions` untuk HTML dengan gambar Base64. +- Gabungkan ini dengan pipeline CI untuk mengotomatiskan pembuatan dokumentasi. +- Selami `DocumentVisitor` Aspose jika Anda memerlukan kontrol yang lebih halus atas proses konversi. + +Selamat coding, dan nikmati file Markdown Anda yang bersih dan mandiri! + +## Tutorial Terkait + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/indonesian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..dbd3ba72ae --- /dev/null +++ b/words/indonesian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Ekspor docx ke txt menggunakan Java dan Aspose.Words. Pelajari cara mengonversi + docx ke teks, mempertahankan Unicode, dan mengekspor Word sebagai txt dalam beberapa + langkah. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: id +og_description: Ekspor docx ke txt dalam Java. Tutorial ini menunjukkan cara mengonversi + docx ke teks, mempertahankan unicode teks biasa, dan mengekspor Word ke txt secara + efisien. +og_title: Ekspor docx ke txt dengan Java – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Ekspor docx ke txt dengan Java – Panduan Pemrograman Lengkap +url: /id/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ekspor docx ke txt dengan Java – Panduan Pemrograman Lengkap + +Pernah membutuhkan untuk **export docx to txt** tetapi khawatir kehilangan karakter khusus? Anda tidak sendirian. Saat Anda mengonversi dokumen Word ke file plain‑text, simbol Unicode, tabel, dan bahkan pemformatan sederhana dapat menghilang seperti sihir. + +Dalam panduan ini kami akan menjelaskan cara yang andal untuk **export docx to txt** menggunakan Aspose.Words untuk Java, mempertahankan setiap glyph Unicode dan menjaga tata letak tabel tetap dapat dibaca. Pada akhir tutorial Anda juga akan mengetahui cara **convert docx to text**, **convert word to text**, dan bahkan **export word as txt** tanpa masalah. + +## Apa yang Dibahas dalam Tutorial Ini + +* Menyiapkan Aspose.Words dalam proyek Java +* Memuat file DOCX dan menyiapkannya untuk output plain‑text +* Mengonfigurasi dukungan **plain text unicode** melalui `TxtSaveOptions` +* Trik opsional untuk menjaga tabel tetap terbaca dalam file `.txt` yang dihasilkan +* Menyimpan file dan memverifikasi output + +Tidak ada skrip eksternal, tidak ada alat baris perintah yang misterius—hanya kode Java murni yang dapat Anda masukkan ke dalam proyek Maven atau Gradle mana pun. + +> **Mengapa penting?** File plain‑text ringan, ramah kontrol versi, dan sempurna untuk pengindeksan pencarian atau alur pemrosesan hilir. Jika Anda pernah mencoba `cat` file Word dan mendapatkan teks tak terbaca, tutorial ini menyelesaikan masalah tersebut. + +--- + +## Ekspor docx ke txt – Ikhtisar + +Sebelum kita menyelam ke kode, mari klarifikasi istilahnya. **Export docx to txt** berarti mengambil paket Microsoft Word `.docx` dan menuliskan konten teksnya ke file `.txt` sederhana. Tidak seperti konversi PDF, ekspor teks menghapus gaya tetapi dapat mempertahankan jeda baris, penanda paragraf, dan—jika Anda mengonfigurasinya dengan benar—karakter Unicode seperti emoji, huruf beraksen, atau skrip Asia. + +Aspose.Words membuat ini mudah karena mengabstraksi format file Word dan menyediakan kelas `TxtSaveOptions` dimana Anda dapat menentukan encoding, penanganan tabel, dan lainnya. + +### Prasyarat + +* Java 11 atau lebih baru (API bekerja dengan Java 8+, tetapi kami akan mengasumsikan JDK terbaru) +* Aspose.Words for Java JAR (tersedia di Maven Central) +* File contoh `unicode.docx` yang berisi beragam karakter Unicode—misalnya “こんにちは”, “😊”, dan tabel sederhana + +Jika Anda sudah memiliki semuanya, mari kita mulai. + +--- + +## Langkah 1: Muat File DOCX (Convert docx to text) + +Hal pertama yang perlu Anda lakukan adalah membaca dokumen sumber ke memori. Di sinilah proses **convert docx to text** secara resmi dimulai. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Mengapa ini penting:* `Document` adalah representasi Aspose.Words dari file Word. Dengan memuatnya, Anda mendapatkan akses ke semua paragraf, tabel, dan bahkan elemen tersembunyi. Jika file tidak ditemukan, Aspose akan melempar `FileNotFoundException` yang jelas, sehingga Anda langsung tahu apa yang salah. + +--- + +## Langkah 2: Konfigurasikan TxtSaveOptions untuk Unicode (Plain text unicode) + +File plain‑text hanyalah aliran byte, jadi Anda harus memberi tahu Java set karakter mana yang akan digunakan. UTF‑8 adalah standar de‑facto untuk **plain text unicode** karena dapat mengkodekan setiap titik kode Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Tips pro:** Jika Anda melewatkan pemanggilan `setEncoding`, Aspose secara default menggunakan charset default platform, yang pada banyak mesin Windows adalah Windows‑1252. Default tersebut secara diam-diam akan menghilangkan karakter seperti “ß” atau “—”. + +--- + +## Langkah 3: Pertahankan Tata Letak Tabel (Opsional, tetapi berguna untuk keterbacaan) + +Saat Anda **export word as txt**, tabel biasanya diratakan menjadi satu baris teks, membuatnya tidak terbaca. Aspose.Words menawarkan flag sederhana untuk mempertahankan struktur visual. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Kapan menggunakannya:* Jika DOCX sumber Anda berisi faktur, jadwal, atau data berbentuk grid, mengaktifkan `PreserveTableLayout` akan menyisipkan tab dan jeda baris sehingga file yang dihasilkan masih menyerupai tabel. Jika Anda tidak memerlukannya, Anda dapat menghilangkan baris tersebut dan mendapatkan output yang lebih ringkas. + +--- + +## Langkah 4: Simpan Dokumen sebagai Plain‑Text (Export word as txt) + +Sekarang pekerjaan berat selesai—cukup tulis byte ke disk. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Menjalankan program menghasilkan `plain.txt` di folder yang sama. Buka dengan editor teks apa pun (Notepad++, VS Code, bahkan `cat` di terminal) dan Anda akan melihat: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Perhatikan bagaimana salam Jepang dan emotikon tetap ada, dan tabel mempertahankan kolomnya berkat `PreserveTableLayout`. Itulah inti dari **export docx to txt** yang bersih. + +--- + +## Langkah 5: Verifikasi Output (Convert word to text sanity check) + +Pemeriksaan cepat mencegah kehilangan data secara diam-diam. Berikut beberapa cara untuk memastikan Anda benar‑benar **convert word to text** dengan tepat: + +1. **Perbandingan checksum** – hitung hash SHA‑256 dari file `.txt` sebelum dan sesudah konversi bolak‑balik (txt → docx → txt) untuk memastikan kestabilan. +2. **Cari penanda Unicode** – gunakan `grep` atau pencarian dalam file IDE untuk menemukan karakter seperti “😊”. +3. **Buka di beberapa editor** – beberapa versi Notepad Windows lama masih salah menginterpretasikan UTF‑8 tanpa BOM; membuka file di VS Code memastikan encoding yang tepat. + +Jika salah satu pemeriksaan ini gagal, periksa kembali bahwa `saveOptions.setEncoding(StandardCharsets.UTF_8)` ada dan bahwa DOCX sumber Anda memang berisi teks Unicode. + +--- + +## Kesalahan Umum & Cara Menghindarinya + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Karakter yang hilang** | Charset sistem default (mis., Windows‑1252) menghapus glyph non‑ASCII. | Set secara eksplisit UTF‑8 melalui `saveOptions.setEncoding`. | +| **Tabel menjadi satu baris** | `PreserveTableLayout` dibiarkan pada nilai default `false`. | Panggil `saveOptions.setPreserveTableLayout(true)`. | +| **File tidak ditemukan** | Path salah atau izin baca tidak tersedia. | Gunakan path absolut atau `Paths.get(...)` dengan penanganan pengecualian yang tepat. | +| **Penurunan kinerja pada dokumen besar** | Memuat seluruh dokumen ke memori. | Stream dokumen dalam potongan menggunakan `DocumentBuilder` jika Anda hanya membutuhkan bagian tertentu. | + +--- + +## Bonus: Mengekspor Banyak File DOCX Secara Batch + +Jika Anda perlu **convert docx to text** untuk seluruh folder, bungkus logika dalam loop: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Potongan kode ini **export docx to txt** untuk setiap file di direktori, menghemat Anda berjam‑jam kerja manual. + +--- + +## Kesimpulan + +Anda baru saja mempelajari cara **export docx to txt** dengan Java, memastikan setiap karakter Unicode tetap utuh, tabel tetap dapat dibaca, dan seluruh proses dapat diulang. Dengan mengonfigurasi `TxtSaveOptions` untuk UTF‑8 dan secara opsional mempertahankan tata letak tabel, Anda dapat dengan andal **convert docx to text**, **convert word to text**, dan **export word as txt** untuk alur kerja hilir apa pun. + +Siap untuk tantangan berikutnya? Cobalah mengekspor ke format plain‑text lain seperti markdown (`.md`) atau CSV, atau jelajahi kemampuan konversi PDF Aspose.Words. Prinsip yang sama—encoding eksplisit, preservasi tata letak, dan verifikasi menyeluruh—berlaku di semua kasus. + +Selamat coding, semoga file teks Anda selalu kaya Unicode! + +--- + +![Diagram alur export docx ke txt](/images/export-docx-to-txt-pipeline.png){alt="diagram alur export docx ke txt"} + +## Tutorial Terkait + +- [Konversi Docx ke Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Konversi DOCX ke PDF di Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Konversi docx ke markdown – Ekspor Persamaan Matematika ke LaTeX dengan Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/indonesian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..d565cfcb35 --- /dev/null +++ b/words/indonesian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: Simpan dokumen sebagai PDF menggunakan Aspose.Words Java dan tambahkan + aksesibilitas ke PDF. Pelajari cara mengonversi docx ke PDF, menandai garis horizontal, + dan memastikan kepatuhan PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: id +og_description: Simpan dokumen sebagai PDF dengan Aspose.Words Java sambil menambahkan + aksesibilitas ke PDF. Panduan langkah demi langkah untuk mengonversi docx ke PDF + dan menandai garis horizontal untuk kepatuhan PDF/UA‑2. +og_title: Simpan Dokumen sebagai PDF dengan Aspose.Words Java – Aksesibilitas Jadi + Mudah +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Simpan Dokumen sebagai PDF dengan Aspose.Words Java – Panduan Aksesibilitas + Lengkap +url: /id/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Simpan Dokumen sebagai PDF dengan Aspose.Words Java – Panduan Aksesibilitas Lengkap + +Pernah bertanya-tanya bagaimana cara **save document as PDF** sambil tetap membuatnya dapat diakses oleh pembaca layar? Anda tidak sendirian. Banyak pengembang perlu *convert docx to pdf* dan tetap memenuhi standar PDF/UA‑2, terutama ketika sumbernya berisi garis horizontal yang harus ditandai dengan benar. Dalam tutorial ini kami akan membahas langkah‑langkah tepat untuk **save document as PDF** menggunakan Aspose.Words untuk Java, secara otomatis **add accessibility to PDF**, dan memastikan setiap garis horizontal **tagged** sebagai artefak. + +Kami akan memulai dengan proyek Java yang bersih, memuat DOCX yang sudah memiliki garis horizontal, mengonfigurasi opsi penyimpanan PDF untuk kepatuhan PDF/UA‑2, dan akhirnya menulis PDF yang sepenuhnya dapat diakses. Pada akhir tutorial, Anda akan dapat **save document as pdf** dengan keyakinan bahwa ia lulus pemeriksaan aksesibilitas. + +## Prasyarat + +- Java 8 atau lebih baru terpasang (tutorial ini diuji pada JDK 17). +- Maven 3.6+ (atau Gradle jika Anda lebih suka) untuk mengelola dependensi. +- Lisensi Aspose.Words untuk Java yang valid (versi percobaan gratis berfungsi, tetapi lisensi menghilangkan watermark evaluasi). +- File DOCX (`input.docx`) yang mencakup setidaknya satu garis horizontal—pikirkan sebagai pemisah garis sederhana yang Anda tambahkan di Word. + +> **Tip pro:** Jika Anda tidak memiliki file DOCX, cukup buat dokumen Word baru, ketik beberapa paragraf, sisipkan *Insert → Horizontal Line*, simpan sebagai `input.docx`, dan letakkan di folder pilihan Anda. + +## Langkah 1: Siapkan Proyek Maven + +Pertama, buat proyek Maven baru (atau tambahkan ke proyek yang sudah ada). `pom.xml` memerlukan dependensi Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Mengapa ini penting:** Menambahkan artefak `aspose-words` adalah langkah pertama untuk *convert docx to pdf*. Tanpa itu, kompiler tidak akan mengenali `Document`, `PdfSaveOptions`, dan kelas penting lainnya. + +## Langkah 2: Muat DOCX Sumber yang Mengandung Garis Horizontal + +Sekarang kami akan menulis kelas Java kecil yang memuat DOCX. Di sinilah bagian **tag horizontal rules** dimulai—Aspose.Words secara otomatis memperlakukan garis horizontal sebagai paragraf dengan border, tetapi kami akan membiarkan mesin PDF/UA menangani penandaan. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Perhatikan bahwa kami belum menyimpan apa pun—kami hanya **loading** DOCX, yang merupakan setengah pertama dari *convert docx to pdf*. Objek `Document` kini menyimpan semua konten Word, termasuk setiap garis horizontal yang Anda sisipkan. + +## Langkah 3: Konfigurasikan Opsi Penyimpanan PDF untuk Kepatuhan PDF/UA‑2 + +Keajaiban **add accessibility to PDF** terdapat pada `PdfSaveOptions`. Dengan mengatur tingkat kepatuhan ke `PDF_UA_2`, Aspose.Words akan: + +1. Menandai elemen struktural (heading, tabel, dll.). +2. Menandai elemen dekoratif—seperti garis horizontal sebagai *artifacts*, sehingga pembaca layar mengabaikannya. +3. Menyisipkan metadata PDF/UA yang diperlukan. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Mengapa mengatur kepatuhan?** Tanpa `PDF_UA_2`, PDF yang dihasilkan mungkin masih dapat dibaca tetapi tidak akan lulus validator aksesibilitas otomatis. Persyaratan **tag horizontal rules** terpenuhi secara otomatis karena PDF/UA memperlakukan mereka sebagai *artifacts* ketika flag kepatuhan diaktifkan. + +## Langkah 4: Simpan Dokumen sebagai PDF + +Sekarang kami akhirnya **save document as pdf**. Baris tunggal ini melakukan pekerjaan berat—mengonversi DOCX, menerapkan tag aksesibilitas, dan menulis file ke disk. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Jalankan kelas (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) dan Anda akan melihat pesan konfirmasi. Buka `ua_compliant.pdf` yang dihasilkan di Adobe Acrobat dan periksa **File → Properties → Description → PDF/A, PDF/UA**—Anda harus melihat “PDF/UA‑2” terdaftar. + +### Output yang Diharapkan + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Buka PDF, dan Anda akan memperhatikan: + +- Teks dokumen dapat dipilih dan dicari. +- Garis horizontal tidak terlihat oleh pembaca layar (diperlakukan sebagai artefak). +- PDF lulus alat validasi PDF/UA dasar (mis., PAC 3). + +## Langkah 5: Verifikasi Aksesibilitas – Daftar Periksa Cepat + +Meskipun Aspose.Words melakukan sebagian besar pekerjaan, sebaiknya memverifikasi output. + +| Pemeriksaan | Cara Memverifikasi | +|-------|----------------| +| **Document title** | Buka Acrobat → File → Properties → bidang Title (harus cocok dengan `pdfOptions.setTitle`). | +| **Artifact tagging** | Gunakan alat “Reading Order” di Acrobat. Garis horizontal harus muncul sebagai *Artifact* (abu-abu). | +| **Logical reading order** | Jalankan “Accessibility Checker” di Acrobat; pastikan tidak ada kesalahan struktural. | +| **Tagged PDF** | Di Acrobat, lihat panel “Tags” – Anda harus melihat hierarki (Document → Section → Paragraph, dll.). | +| **PDF/UA compliance** | Acrobat akan menampilkan “PDF/UA‑2” di tab “Standards”. | + +Jika salah satu pemeriksaan ini gagal, periksa kembali bahwa Anda menggunakan versi Aspose.Words terbaru dan bahwa `setCompliance(PdfCompliance.PDF_UA_2)` diterapkan dengan benar. + +## Kesalahan Umum & Cara Menghindarinya + +1. **Missing License** – Versi percobaan menambahkan watermark yang dapat merusak validasi PDF/UA. Terapkan lisensi Anda di awal `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` akan menghentikan konversi. Gunakan path absolut atau letakkan DOCX di root proyek dan referensikan dengan `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – Dukungan PDF/UA ditambahkan pada versi 22.9. Tingkatkan ke rilis terbaru untuk menghindari fitur yang hilang. +4. **Horizontal Rule as Image** – Jika Anda menyisipkan garis sebagai gambar alih-alih garis horizontal Word bawaan, Aspose memperlakukannya sebagai gambar biasa, bukan artefak. Ganti gambar dengan *Horizontal Line* bawaan Word untuk penandaan yang tepat. + +## Memperluas Solusi – Bagaimana Jika Anda Membutuhkan Lebih Banyak? + +- **Custom Tags**: Jika Anda memiliki elemen dekoratif lain (mis., ikon dekoratif), Anda dapat secara manual menandainya sebagai artefak menggunakan `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Loop melalui folder berisi file DOCX dan batch‑convert mereka, menggunakan kembali instance `PdfSaveOptions` yang sama untuk kinerja. +- **Adding a Language Tag**: Untuk PDF multibahasa, set `pdfOptions.setLanguage("en-US")` untuk membantu teknologi bantu memilih suara yang tepat. + +## Contoh Lengkap yang Berfungsi (Semua Kode Bersama) + +Berikut adalah program Java lengkap yang dapat dijalankan. Salin‑tempel ke IDE Anda, sesuaikan path, dan jalankan. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +## Kesimpulan + +Kami baru saja mendemonstrasikan cara **save document as pdf** dengan Aspose.Words untuk Java sambil secara otomatis **add accessibility to pdf** dan **tag horizontal rules** sebagai artefak. Poin penting yang dapat diambil: + +- Gunakan `PdfSaveOptions` dengan kepatuhan `PDF_UA_2` untuk memenuhi standar aksesibilitas. +- Memuat DOCX dan memanggil `doc.save(..., pdfOptions)` adalah semua yang Anda butuhkan untuk **convert docx to pdf**. +- Garis horizontal ditangani secara otomatis—tidak diperlukan kode tambahan, memenuhi persyaratan **tag horizontal rules**. +- Pendekatan ini sepenuhnya **aspose convert docx pdf** compliant, bekerja dengan versi perpustakaan terbaru, dan menghasilkan PDF siap validasi. + +Siap untuk tantangan berikutnya? Coba tambahkan metadata khusus, sematkan font, atau proses batch seluruh folder file DOCX. Setiap ekstensi tersebut dibangun di atas fondasi yang sama yang kami jelaskan di sini. + +Ada pertanyaan tentang kepatuhan PDF/UA, lisensi, atau penanganan elemen Word lainnya? Tinggalkan komentar atau periksa dokumentasi resmi Aspose—ada banyak contoh untuk dijelajahi. Selamat coding, dan nikmati membuat PDF yang dapat diakses! + +![simpan dokumen sebagai pdf menggunakan Aspose.Words Java – contoh PDF yang dapat diakses](placeholder-image.png "simpan dokumen sebagai pdf menggunakan Aspose.Words Java – contoh PDF yang dapat diakses") + +## Tutorial Terkait + +- [Cara menyimpan dokumen sebagai pdf dengan Aspose.Words untuk Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Cara Mengonversi Word ke PDF Menggunakan Aspose.Words untuk Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Mengonversi DOCX ke PDF di Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/indonesian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..9faa87589e --- /dev/null +++ b/words/indonesian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Simpan Word sebagai markdown dan temukan cara mengekspor persamaan matematika + ke LaTeX menggunakan Aspose.Words untuk Java. Konversi persamaan Word ke LaTeX dalam + beberapa baris saja. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: id +og_description: Simpan dokumen Word sebagai markdown dan pelajari cara mengekspor + persamaan matematika ke LaTeX menggunakan Aspose.Words untuk Java. Panduan lengkap + yang dapat dijalankan. +og_title: Simpan kata sebagai markdown – Ekspor Matematika ke LaTeX dengan Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Simpan Word sebagai Markdown – Ekspor Matematika ke LaTeX dengan Java +url: /id/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Simpan Word sebagai Markdown – Ekspor Matematika ke LaTeX dengan Java + +Pernah membutuhkan untuk **save word as markdown** tetapi khawatir persamaan Anda akan menjadi berantakan? Anda tidak sendirian. Dalam panduan ini kami akan menjelaskan **cara mengekspor matematika** dari file `.docx` langsung ke LaTeX sementara sisanya menjadi Markdown yang bersih. + +Kami akan membahas semuanya mulai dari menyiapkan pustaka Aspose.Words hingga memverifikasi file `out.md` akhir. Pada akhir panduan Anda akan dapat **convert word equations latex** dalam satu pemanggilan metode, dan Anda akan memahami nuansa kecil yang membuat konversi menjadi andal. + +--- + +## Apa yang Anda Butuhkan + +- **Java 8+** – kode berjalan pada JDK terbaru apa pun. +- **Aspose.Words for Java** – baik sebagai dependensi Maven/Gradle maupun JAR jika Anda lebih suka penyiapan manual. +- Dokumen Word (`math.docx`) yang berisi setidaknya satu persamaan Office Math. +- IDE atau baris perintah `javac`/`java` biasa – apa pun yang Anda nyaman gunakan. + +Jika Anda sudah memiliki semuanya, bagus. Jika belum, bagian berikutnya menunjukkan cara menambahkan pustaka ke proyek Anda. + +--- + +## Save word as markdown – Langkah 1: Tambahkan Aspose.Words ke Proyek Anda + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose menawarkan lisensi sementara gratis untuk pengujian. Letakkan file `license.xml` di folder resources Anda dan panggil `License license = new License(); license.setLicense("license.xml");` sebelum memuat dokumen apa pun. + +Setelah dependensi terpasang, Anda siap menulis kode konversi. + +--- + +## Cara Mengekspor Persamaan Matematika ke LaTeX + +Proses utama dilakukan oleh `MarkdownSaveOptions`. Dengan mengubah `OfficeMathExportMode` menjadi `LATEX`, setiap objek Office Math akan dirender sebagai fragmen LaTeX di dalam output Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Mengapa Ini Berfungsi + +- **`Document`** adalah titik masuk Aspose; ia mengabstraksi file `.docx` dan memberi Anda akses ke setiap node, termasuk persamaan. +- **`MarkdownSaveOptions`** memberi tahu pustaka *bagaimana* Anda menginginkan output. Perilaku default adalah merender persamaan sebagai gambar, yang menghilangkan tujuan format berbasis teks. +- **`OfficeMathExportMode.LATEX`** memaksa mesin menerjemahkan setiap node `OfficeMath` ke ekivalen LaTeX‑nya, yang dapat dirender oleh parser Markdown (seperti GitHub atau Jekyll) ketika digabungkan dengan plugin MathJax. + +--- + +## Convert word equations LaTeX – Langkah 2: Verifikasi Output Markdown + +Setelah menjalankan program, buka `out.md`. Anda akan melihat sesuatu seperti ini: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Catatan:** Fragmen LaTeX dibungkus dalam `$…$` untuk matematika inline dan `$$…$$` untuk matematika blok. Ini adalah sintaks standar yang dipahami oleh kebanyakan generator situs statis ketika MathJax diaktifkan. + +Jika Anda lebih suka persamaan tetap inline saja, Anda dapat menyesuaikan `MarkdownSaveOptions` lebih lanjut: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx to markdown latex – Langkah 3: Kasus Tepi & Jebakan Umum + +| Situasi | Hal yang Perlu Diperhatikan | Solusi | +|-----------|-------------------|-----| +| **Persamaan bersarang kompleks** | Aspose mungkin menghasilkan kurung tambahan `{}` yang diperlakukan secara harfiah oleh beberapa parser. | Lakukan post‑process pada Markdown dengan regex sederhana untuk mengubah `{{` menjadi `{`. | +| **MathJax tidak ada di situs target** | Persamaan muncul sebagai kode LaTeX mentah. | Tambahkan `` ke template HTML Anda. | +| **Dokumen besar** | Konsumsi memori melonjak karena seluruh dokumen dimuat sekaligus. | Gunakan `LoadOptions.setLoadFormat(LoadFormat.DOCX)` dan pertimbangkan memproses halaman secara batch jika Anda mengalami `OutOfMemoryError`. | +| **Lisensi tidak disetel** | Anda akan menerima peringatan dan output mungkin berwatermark. | Muat lisensi di awal `main` seperti yang ditunjukkan pada tip Maven di atas. | + +--- + +## Save word as markdown – Contoh Lengkap yang Berfungsi + +Berikut adalah kelas mandiri yang dapat Anda salin‑tempel ke proyek Java mana pun. Cukup ganti `YOUR_DIRECTORY` dengan path ke file Anda. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Jalankan program (`java MathToLatexMarkdown`) dan Anda akan melihat pesan konsol yang mengonfirmasi keberhasilan. Buka `out.md` di editor apa pun – persamaan akan menjadi potongan LaTeX bersih siap untuk dirender. + +--- + +## Snapshot Output yang Diharapkan + +![output save word as markdown dengan persamaan LaTeX](https://example.com/images/markdown-latex-output.png "output save word as markdown dengan persamaan LaTeX") + +*Gambar ini menunjukkan potongan Markdown yang dihasilkan dimana persamaan `\int_{a}^{b} f(x)\,dx` dibungkus dalam `$$`.* + +--- + +## Kesimpulan + +Kami baru saja menunjukkan cara **save word as markdown** sambil mempertahankan setiap persamaan Office Math sebagai LaTeX asli. Langkah kunci adalah mengonfigurasi `MarkdownSaveOptions` dengan `OfficeMathExportMode.LATEX`, yang mengubah alur kerja Word‑to‑Markdown biasa menjadi alat konversi yang sepenuhnya menyadari matematika. + +Sekarang Anda dapat: + +1. **How to export math** dari file `.docx` apa pun tanpa kehilangan keakuratan. +2. **Convert word equations latex** untuk generator situs statis, dokumentasi, atau blog akademik. +3. Perluas pendekatan untuk memproses banyak file secara batch, mengintegrasikan dengan pipeline CI, atau bahkan membangun layanan web kecil. + +Jika Anda penasaran dengan tantangan berikutnya, coba gabungkan ini dengan **docx to markdown latex** untuk dokumen yang banyak mengandung gambar, atau jelajahi `HtmlSaveOptions` milik Aspose untuk versi HTML siap web. Kemungkinannya tak terbatas—cobalah, pecahkan, lalu bagikan temuan Anda dengan komunitas. + +Ada pertanyaan atau persamaan rumit yang tidak ter-render seperti yang diharapkan? Tinggalkan komentar di bawah, dan selamat coding! + +## Tutorial Terkait + +- [Cara Mengekspor LaTeX dari Word: Konversi DOCX ke Markdown & Simpan sebagai PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Konversi docx ke markdown – Ekspor Persamaan Matematika ke LaTeX dengan Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Cara Mengonversi Word ke PDF Menggunakan Aspose.Words untuk Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/indonesian/java/document-loading-and-saving/_index.md index d17f931218..ec9e2c0dcd 100644 --- a/words/indonesian/java/document-loading-and-saving/_index.md +++ b/words/indonesian/java/document-loading-and-saving/_index.md @@ -128,15 +128,10 @@ Pelajari cara menyimpan dokumen dalam format RTF menggunakan Aspose.Words untuk Pelajari cara menyimpan dokumen sebagai file teks di Aspose.Words untuk Java. Ikuti panduan langkah demi langkah kami dengan contoh kode Java. ### [Menentukan Format Dokumen di Aspose.Words untuk Java](./determining-document-format/) -Pelajari cara mendeteksi format dokumen di Java dengan Aspose.Words. Identifikasi DOC, DOCX, dan lainnya. Atur file secara efisien. ### [Memulihkan File Word Rusak – Panduan C# untuk Membuka dengan Aman](./recover-corrupted-word-file-c-guide-to-open-safely/) -Pelajari cara memulihkan dan membuka file Word yang rusak menggunakan C# dengan aman melalui langkah-langkah praktis. - ### [Pulihkan docx yang rusak – Panduan Lengkap untuk Memperbaiki dan Memproses Dokumen](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) -Pelajari cara memulihkan file DOCX yang rusak, memperbaikinya, dan melanjutkan pemrosesan dokumen dengan Aspose.Words untuk Java. - +### [Buka Dokumen Word Rusak – Atur Mode Pemulihan di Java](./open-corrupted-word-document-set-recovery-mode-in-java/) ### [Menangkap Peringatan Substitusi Font di Java dengan Aspose.Words – Panduan Lengkap](./capture-font-substitution-warnings-in-java-with-aspose-words/) -Pelajari cara menangkap peringatan substitusi font saat memuat dokumen di Java menggunakan Aspose.Words, termasuk contoh kode lengkap. ## Pertanyaan yang Sering Diajukan diff --git a/words/indonesian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/indonesian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..b35d0271eb --- /dev/null +++ b/words/indonesian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Buka dokumen Word yang rusak di Java dengan Aspose.Words. Pelajari cara + mengatur mode pemulihan dan memulihkan file Word yang rusak secara andal. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: id +og_description: Buka dokumen Word yang rusak di Java menggunakan Aspose.Words. Panduan + ini menunjukkan cara mengatur mode pemulihan dan memulihkan file Word yang rusak + secara efisien. +og_title: Buka Dokumen Word yang Rusak – Atur Mode Pemulihan di Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Buka Dokumen Word yang Rusak – Atur Mode Pemulihan di Java +url: /id/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buka Dokumen Word Rusak – Atur Mode Pemulihan di Java + +Pernah mencoba membuka dokumen Word yang rusak dan melihat program terhenti karena pengecualian? Anda tidak sendirian—file .docx yang rusak memang menyebalkan. Kabar baiknya, Aspose.Words untuk Java memberi Anda kontrol yang detail sehingga Anda dapat **membuka dokumen word yang rusak** tanpa aplikasi crash, bahkan dapat memilih apakah ingin menampilkan peringatan, pemulihan diam-diam, atau penolakan keras. + +Dalam tutorial ini kita akan melewati seluruh proses: mulai dari membuat `LoadOptions` yang tepat, memilih nilai **set recovery mode** yang sesuai, dan akhirnya memastikan dokumen memang berhasil dimuat. Pada akhir tutorial Anda akan tahu **cara memulihkan file word yang rusak** secara programatik, tanpa perlu menyalin‑tempel manual. + +> **Apa yang Anda perlukan** +> * Java 8 atau lebih baru (API juga bekerja dengan Java 11) +> * Aspose.Words untuk Java 23.9 (atau versi terbaru) +> * Contoh file .docx yang rusak—cukup ganti nama file yang valid untuk mensimulasikan kerusakan jika Anda belum memiliki file tersebut + +Mari kita mulai. + +## Buka Dokumen Word Rusak – Ikhtisar Langkah‑per‑Langkah + +Berikut alur tingkat tinggi yang akan kita implementasikan: + +1. **Buat `LoadOptions`** – objek ini memberi tahu Aspose.Words bagaimana bersikap ketika menemukan masalah. +2. **Atur mode pemulihan** – pilih `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, atau `REJECT_CORRUPTED`. +3. **Muat dokumen** menggunakan opsi yang telah dikonfigurasi. +4. **Verifikasi** bahwa pemuatan berhasil (misalnya, cetak jumlah halaman). + +Setiap langkah dijelaskan secara detail, dengan potongan kode yang dapat Anda salin‑tempel langsung ke IDE. + +## Atur Mode Pemulihan untuk Berbagai Skenario + +Aspose.Words mendefinisikan tiga strategi pemulihan di dalam `LoadOptions.RecoveryMode`: + +| Mode | Perilaku | Kapan digunakan | +|------|----------|-----------------| +| `RECOVER_WITH_WARNINGS` | Mencoba memuat dokumen, tetapi menampilkan setiap masalah sebagai peringatan di konsol. | Anda ingin melihat *apa* yang salah tanpa menghentikan proses. | +| `RECOVER_WITHOUT_WARNINGS` | Diam‑diam memperbaiki apa yang bisa dan menekan peringatan. | Lingkungan produksi di mana log harus tetap bersih. | +| `REJECT_CORRUPTED` | Melempar pengecualian begitu kerusakan terdeteksi. | Pipeline validasi ketat yang harus gagal cepat. | + +Memilih mode yang tepat adalah inti dari **set recovery mode** secara benar. Dalam kebanyakan sesi debugging, `RECOVER_WITH_WARNINGS` adalah pilihan yang ideal karena memberi tahu Anda bagian mana yang diperbaiki. + +## Cara Memulihkan File Word Rusak Menggunakan Aspose.Words + +Berikut adalah **program Java lengkap yang dapat dijalankan** yang mendemonstrasikan seluruh proses. Silakan letakkan ke dalam file `RecoveryModeDemo.java`, sesuaikan path, dan jalankan. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Mengapa setiap baris penting + +* **`LoadOptions loadOptions = new LoadOptions();`** – tanpa objek ini Aspose.Words menggunakan pemulihan default, yang *menolak* file yang rusak. Membuatnya memberi Anda titik masuk untuk mengubah perilaku tersebut. +* **`setRecoveryMode(...)`** – ini adalah pemanggilan **set recovery mode** yang menentukan apakah peringatan muncul, disembunyikan, atau menyebabkan pengecualian. +* **`new Document(path, loadOptions);`** – konstruktor menerima `LoadOptions` yang baru saja kita konfigurasikan, sehingga perpustakaan tahu cara memperlakukan file rusak sejak awal. +* **`doc.getPageCount()`** – pemeriksaan cepat. Jika dokumen dimuat dan mengembalikan jumlah halaman, Anda telah berhasil **cara memulihkan file word yang rusak**. +* **`doc.save(...)`** – opsional namun berguna; Anda dapat menulis versi yang telah diperbaiki kembali ke disk untuk penggunaan selanjutnya. + +## Menangani Kasus Edge yang Umum + +### 1. File Tidak Ditemukan + +Jika path salah, `Document` akan melempar `FileNotFoundException`. Bungkus pemuatan dalam blok try‑catch dan log pesan yang ramah: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Kerusakan yang Tidak Dapat Dipulihkan + +Bahkan dengan `RECOVER_WITH_WARNINGS`, beberapa struktur berada di luar jangkauan perbaikan. Dalam kasus tersebut Aspose.Words tetap memuat apa yang dapat, tetapi Anda akan melihat peringatan seperti “Cannot read paragraph properties”. Perhatikan output konsol; peringatan tersebut sering menunjukkan bagian yang hilang yang mungkin perlu Anda susun kembali secara manual. + +### 3. File Besar dan Kinerja + +Pemulihan menambah sedikit overhead karena perpustakaan mem-parsing file dua kali—sekali untuk mendeteksi masalah, sekali lagi untuk membangun kembali. Untuk dokumen berukuran multi‑gigabyte, pertimbangkan streaming file atau meningkatkan heap JVM (`-Xmx2g`) agar terhindar dari `OutOfMemoryError`. + +## Tips Pro – Membuat Pemulihan Lebih Tangguh + +* **Log peringatan ke file** – alihkan `System.err` ke logger sehingga Anda memiliki jejak audit tentang apa yang telah diperbaiki. +* **Validasi setelah pemulihan** – jalankan `doc.updatePageLayout();` lalu periksa kembali jumlah halaman; terkadang tata letak berubah setelah memperbaiki bagian yang rusak. +* **Otomatisasi pemulihan batch** – bungkus demo dalam loop yang memproses folder berisi file rusak, menggunakan `LoadOptions` yang sama setiap kali. + +## Kesimpulan + +Anda kini tahu persis **cara memulihkan file word yang rusak** menggunakan Aspose.Words untuk Java. Dengan membuat instance `LoadOptions`, **set recovery mode** ke strategi yang sesuai dengan skenario Anda, dan memuat dokumen dengan opsi tersebut, Anda dapat dengan aman **membuka dokumen word yang rusak** tanpa membuat aplikasi Anda crash. Kode contoh di atas adalah solusi lengkap yang siap dijalankan, mencetak jumlah halaman, dan bahkan menyimpan salinan yang telah dibersihkan. + +Apa selanjutnya? Cobalah mengganti mode pemulihan menjadi `RECOVER_WITHOUT_WARNINGS` dan bandingkan output konsol, atau bereksperimen dengan memuat dokumen terenkripsi (Anda perlu menyediakan kata sandi melalui + +## Tutorial Terkait + +- [Aspose.Words Java: Panduan Komprehensif untuk Pemrosesan Dokumen Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Cara Mengonversi Word ke PDF Menggunakan Aspose.Words untuk Java](/words/english/java/document-converting/using-document-converting/) +- [Cara Membandingkan Dua File Word dengan Aspose.Words untuk Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/indonesian/java/document-styling/_index.md index 1da2a93681..7888ce36a9 100644 --- a/words/indonesian/java/document-styling/_index.md +++ b/words/indonesian/java/document-styling/_index.md @@ -43,6 +43,8 @@ Pelajari cara menyesuaikan tema dokumen menggunakan Aspose.Words untuk Java. Pan Pelajari cara menerapkan tanda air dan mengatur konfigurasi halaman dengan Aspose.Words untuk Java. Panduan lengkap dengan kode sumber. ### [Penataan Header dan Footer Dokumen](./document-header-footer-styling/) Pelajari cara menata header dan footer dokumen menggunakan Aspose.Words untuk Java dalam panduan terperinci ini. Petunjuk langkah demi langkah dan kode sumber disertakan. +### [Mengatur Pengaturan Font Default di Aspose.Words untuk Java – Panduan Lengkap](./set-default-font-settings-in-aspose-words-for-java-complete/) +Pelajari cara mengatur font default secara programatis dengan Aspose.Words untuk Java. Panduan langkah demi langkah lengkap dengan contoh kode sumber. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/indonesian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..c15d3477ad --- /dev/null +++ b/words/indonesian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Atur pengaturan font default di Aspose.Words untuk Java dan pelajari + cara mengatur pengaturan font serta mendeteksi font yang hilang hanya dalam beberapa + baris kode. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: id +og_description: Atur pengaturan font default di Aspose.Words untuk Java, pelajari + cara mengatur pengaturan font dan mendeteksi font yang hilang dengan cepat dan andal. +og_title: Atur Pengaturan Font Default di Aspose.Words untuk Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Atur Pengaturan Font Default di Aspose.Words untuk Java – Panduan Lengkap +url: /id/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Atur Pengaturan Font Default di Aspose.Words untuk Java – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **set default font settings** saat memuat dokumen Word dengan Aspose.Words for Java? Anda tidak sendirian. Glyph yang hilang dapat mengubah laporan yang rapi menjadi berantakan, dan menangkap peringatan substitusi font‑substitution lebih awal menghemat berjam‑jam debugging. + +Dalam tutorial ini kami akan membahas contoh singkat, end‑to‑end yang **sets default font settings**, menunjukkan cara **set font settings** secara programatis, dan mendemonstrasikan cara andal untuk **detect missing fonts** sebelum mereka merusak tata letak Anda. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara membuat objek `LoadOptions` dengan instance `FontSettings` baru. +- Cara melampirkan listener peringatan yang akan **detect missing fonts** selama pemuatan dokumen. +- Cara memuat file DOCX sementara listener secara diam‑diam melaporkan setiap substitusi. +- Tips untuk menyesuaikan font fallback dan menangani edge case dalam produksi. + +Tanpa pustaka tambahan, tanpa file konfigurasi yang rumit—hanya Java biasa dan Aspose.Words. + +--- + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +1. **Aspose.Words for Java** (versi 23.10 atau lebih baru) di classpath Anda. +2. Kit pengembangan Java 17 (atau lebih baru) – JDK modern apa pun dapat digunakan. +3. File DOCX yang sengaja menggunakan font yang tidak Anda miliki terpasang (misalnya *“MissingFont.ttf”*). + +Jika Anda belum memiliki JAR Aspose, dapatkan dari repositori Maven resmi: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Itu saja—tidak perlu menginstal font tambahan untuk demo ini. + +--- + +## Langkah 1: Buat LoadOptions dan **Set Default Font Settings** + +Hal pertama yang kita butuhkan adalah objek `LoadOptions` yang bersih yang memberi tahu Aspose bagaimana berperilaku ketika menemukan jenis huruf yang tidak dikenal. Dengan memanggil `setFontSettings(new FontSettings())` kami **set default font settings** yang dimulai dengan daftar fallback kosong. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Mengapa ini penting:** +> Ketika Anda tidak secara eksplisit mengonfigurasi font, Aspose akan kembali ke koleksi default sistem, yang mungkin menyembunyikan masalah font yang hilang. Dengan memulai dari instance `FontSettings` yang baru, Anda mendapatkan kontrol penuh atas font mana yang dianggap valid. + +--- + +## Langkah 2: Lampirkan Listener Peringatan untuk **Detect Missing Fonts** + +Aspose menghasilkan objek `WarningInfo` untuk setiap substitusi yang dilakukannya. Dengan mendengarkan `WarningType.FONT_SUBSTITUTION` kita dapat **detect missing fonts** segera setelah dokumen diparsing. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Tips pro:** Listener berjalan pada thread yang sama dengan yang memuat dokumen, sehingga hampir tidak ada penalti kinerja. Jika Anda perlu mengumpulkan peringatan untuk analisis nanti, masukkan ke dalam `List` alih‑alih mencetak langsung. + +--- + +## Langkah 3: Muat Dokumen Menggunakan Opsi yang Dikonfigurasi + +Sekarang setelah kami **set font settings** dan menyiapkan listener, kami cukup memuat file. Setiap font yang hilang akan memicu callback kami secara instan. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Jika file sumber merujuk pada font yang tidak terpasang, Anda akan melihat output serupa dengan: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Baris itu memberi tahu Anda secara tepat font mana yang hilang dan fallback mana yang digunakan—sempurna untuk logging atau umpan balik pengguna. + +--- + +## Langkah 4: Lanjutkan Pemrosesan Normal (Opsional) + +Pada titik ini dokumen sudah sepenuhnya dimuat, dan Anda dapat melanjutkan dengan manipulasi apa pun yang Anda inginkan—mengedit, mengonversi ke PDF, atau mengekstrak teks. Listener peringatan sudah melakukan tugasnya, jadi Anda tidak memerlukan pemeriksaan tambahan. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Bagaimana jika Anda menginginkan fallback khusus?** +> Alih‑alih membiarkan `FontSettings` kosong, Anda dapat menambahkan font tertentu: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Sekarang setiap jenis huruf yang hilang akan diganti dengan *Times New Roman*—pilihan yang dapat diandalkan untuk sebagian besar dokumen Barat. + +--- + +## Gambaran Visual + +![Diagram yang menunjukkan cara mengatur pengaturan font default di Aspose.Words untuk Java](image.png "Diagram alur pengaturan font default") + +*Alt text: alur pengaturan font default di Aspose.Words untuk Java.* + +Diagram tersebut menggambarkan alur mulai dari inisialisasi `LoadOptions` (di mana kami **set default font settings**) hingga melampirkan listener peringatan (untuk **detect missing fonts**) dan akhirnya memuat dokumen. + +--- + +## Kesalahan Umum & Cara Menghindarinya + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **Forgot to call `setFontSettings`** | Aspose menggunakan default sistem, menyembunyikan font yang hilang. | Selalu buat instance `FontSettings` baru dan tetapkan ke `LoadOptions`. | +| **Listener not triggered** | Listener ditambahkan setelah dokumen dimuat. | Tambahkan listener peringatan *sebelum* memanggil `new Document(...)`. | +| **Path typo leads to `FileNotFoundException`** | Path yang ditulis keras tidak cocok dengan sensitivitas huruf besar/kecil OS. | Gunakan `Paths.get("...").toAbsolutePath()` atau konfigurasikan path relatif dari root proyek. | +| **Multiple missing fonts overwhelm logs** | Dokumen besar dapat menghasilkan puluhan peringatan. | Filter duplikat atau gabungkan pesan dalam `Set` sebelum mencetak. | + +--- + +## Memperluas Solusi + +Jika Anda perlu **set font settings** untuk seluruh aplikasi, pertimbangkan membuat `FontSettings` singleton dan menggunakannya kembali di semua `LoadOptions`. Dengan begitu Anda mempertahankan strategi fallback yang konsisten dan menghindari pembuatan objek berulang. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Sekarang bagian mana pun dari basis kode Anda dapat cukup memanggil `FontConfig.getLoadOptions()` dan langsung mendapatkan manfaat dari logika **set default font settings** yang sama. + +--- + +## Kesimpulan + +Kami baru saja membahas semua yang Anda perlukan untuk **set default font settings** di Aspose.Words untuk Java, **set font settings** secara programatis, dan **detect missing fonts** sebelum mereka merusak output Anda. Contoh lengkap yang dapat dijalankan terdapat dalam potongan kode di atas, dan Anda dapat menempelkannya langsung ke IDE Anda untuk melihat peringatan beraksi. + +Langkah selanjutnya? Coba ganti font fallback, bereksperimen dengan format dokumen berbeda (DOC, RTF, HTML), atau integrasikan pengumpul peringatan ke dalam dasbor pemantauan. Semakin banyak Anda bermain dengan `FontSettings`, semakin yakin Anda bahwa dokumen yang dihasilkan akan terlihat persis seperti yang diharapkan—tanpa kejutan, tanpa glyph yang rusak. + +Ada pertanyaan atau skenario substitusi font yang rumit? Tinggalkan komentar di bawah, dan selamat coding! + +--- + +## Tutorial Terkait + +- [Atur Pengaturan Font Fallback](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Atur Pengaturan Font Fallback](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Atur Pengaturan Font Fallback](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/java/images-shapes/_index.md b/words/indonesian/java/images-shapes/_index.md index d24d2b1234..a5977a9415 100644 --- a/words/indonesian/java/images-shapes/_index.md +++ b/words/indonesian/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Pelajari cara membuat gambar mini berkualitas tinggi dan bitmap berukuran khusus ### [Buat Dokumen Word Java – Tambahkan Bentuk Persegi Panjang dengan Efek Bayangan](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Pelajari cara menambahkan bentuk persegi panjang dengan efek bayangan ke dokumen Word menggunakan Aspose.Words untuk Java. +### [Buat Bentuk Persegi Panjang dalam Dokumen Word Java – Panduan Langkah‑ demi‑Langkah Lengkap](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Panduan lengkap untuk menambahkan bentuk persegi panjang ke dokumen Word menggunakan Aspose.Words untuk Java. + ## Sumber Daya Tambahan - [Dokumentasi Aspose.Words untuk Java](https://reference.aspose.com/words/java/) diff --git a/words/indonesian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/indonesian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..5a96c6dc77 --- /dev/null +++ b/words/indonesian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-05-26 +description: Buat bentuk persegi panjang dalam dokumen Word Java dan terapkan efek + bayangan. Pelajari cara menambahkan bayangan pada bentuk, mengatur jarak bayangan, + dan menyimpan file. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: id +og_description: Buat bentuk persegi panjang dalam dokumen Word Java, terapkan efek + bayangan, tambahkan bayangan bentuk, dan atur jarak bayangan dengan Aspose.Words. +og_title: Buat Bentuk Persegi Panjang di Dokumen Word Java – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Membuat Bentuk Persegi Panjang di Dokumen Word Java – Panduan Lengkap Langkah + demi Langkah +url: /id/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat Bentuk Persegi Panjang di Dokumen Word Java – Panduan Langkah-demi-Langkah Lengkap + +Pernah membutuhkan untuk **create rectangle shape** di dokumen Word Java tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—banyak pengembang mengalami kendala ini saat menghasilkan laporan atau faktur secara programatis. Dalam tutorial ini kami akan menjelaskan secara tepat cara **create rectangle shape**, menerapkan bayangan yang halus, dan menyesuaikan jarak bayangan sehingga hasilnya terlihat profesional. + +Kami akan menggunakan Aspose.Words for Java, sebuah pustaka kuat yang memungkinkan Anda memanipulasi file Word tanpa perlu menginstal Microsoft Office. Pada akhir panduan ini Anda akan dapat membuat proyek **create word document java** yang **add shape shadow**, **apply shadow effect**, dan **set shadow distance** hanya dengan beberapa baris kode. + +--- + +## Apa yang Akan Anda Bangun + +- File `.docx` baru yang berisi persegi panjang berwarna sian. +- Bayangan jatuh realistis yang kabur, miring, dan sebagian transparan. +- Kontrol penuh atas jarak bayangan dari bentuk. +- Kelas Java siap‑jalankan yang dapat Anda masukkan ke proyek Maven atau Gradle mana pun. + +Tanpa alat eksternal, tanpa langkah UI manual—hanya kode murni. + +--- + +## Prasyarat + +- Java 8 atau lebih baru (kode ini bekerja pada Java 11, Java 17, dll.). +- Pustaka Aspose.Words for Java (tersedia melalui Maven Central). +- IDE atau editor teks yang Anda sukai (IntelliJ IDEA, Eclipse, VS Code…). +- Pemahaman dasar tentang sintaks Java. + +Jika Anda belum pernah menambahkan dependensi Maven sebelumnya, berikut cuplikan singkatnya: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Sekarang, mari kita mulai. + +--- + +## Langkah 1: Buat Bentuk Persegi Panjang di Dokumen Word + +Hal pertama yang kita butuhkan adalah dokumen kosong dan `DocumentBuilder`. Anggap builder sebagai pena yang menulis ke dalam dokumen. Setelah kita memiliki itu, kita dapat **create rectangle shape** dengan satu panggilan metode. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Mengapa ini penting:** Metode `insertShape` tidak hanya membuat geometri tetapi juga menambahkan bentuk ke koleksi internal dokumen, sehingga Anda dapat langsung mulai menata tampilannya. + +--- + +## Langkah 2: Terapkan Efek Bayangan ke Bentuk + +Sekarang persegi panjang berada di halaman, kita akan **apply shadow effect**. Bayangan memberikan kedalaman, membuat bentuk terasa seolah terangkat dari halaman—peningkatan UI halus yang dapat meningkatkan keterbacaan dalam laporan. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Tip pro:** Blur `5.0` terlihat alami untuk kebanyakan dokumen yang ditampilkan di layar. Jika Anda mencetak, Anda mungkin menginginkan nilai sedikit lebih rendah untuk menghindari tampilan kabur. + +--- + +## Langkah 3: Atur Jarak Bayangan – Penyetelan Penempatan + +Bayangan bukan hanya tentang blur; mereka juga membutuhkan offset yang tepat. Di sinilah kita **set shadow distance**. Jarak `7.0` poin menghasilkan offset sedang yang terlihat namun tidak berlebihan. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Bagaimana jika Anda membutuhkan offset yang lebih besar?** Tingkatkan nilai; turunkan untuk tampilan yang lebih ketat. Ingat, jarak bekerja bersama dengan sudut untuk menempatkan bayangan dengan benar. + +--- + +## Langkah 4: Simpan Dokumen – Simpan Pekerjaan Anda + +Akhirnya, kami menulis dokumen ke disk. Ubah path ke lokasi mana pun Anda ingin file tersebut disimpan. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Menjalankan kelas akan membuat file `shadow.docx` yang, ketika dibuka di Microsoft Word atau LibreOffice, menampilkan persegi panjang sian dengan bayangan abu-abu lembut yang miring 45° dan offset sebesar 7 poin. + +--- + +## Contoh Kerja Lengkap + +Berikut adalah kode lengkap yang siap disalin‑tempel. Kode ini mencakup semua impor, komentar, dan pemanggilan `save` akhir. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Output yang diharapkan:** Buka `shadow.docx` → Anda akan melihat persegi panjang sian terpusat di halaman pertama, memancarkan bayangan abu-abu halus yang sedikit offset ke kanan‑bawah. Blur dan transparansi bayangan membuatnya tampak seperti pencahayaan alami. + +--- + +## Pertanyaan Umum & Kasus Tepi + +### “Bisakah saya menggunakan bentuk lain?” + +Tentu saja. Ganti `ShapeType.RECTANGLE` dengan `ShapeType.OVAL`, `ShapeType.LINE`, atau enum lain yang didukung. Sisanya kode bayangan tetap sama. + +### “Bagaimana jika saya membutuhkan beberapa bayangan?” + +Aspose.Words hanya mendukung satu bayangan per bentuk. Untuk mensimulasikan beberapa bayangan, duplikat bentuk, offset setiap salinan, dan sesuaikan transparansi. + +### “Apakah bayangan terlihat di LibreOffice?” + +Ya—Aspose.Words menulis OOXML standar, yang diinterpretasikan LibreOffice dengan benar. Bayangan mungkin terlihat sedikit berbeda karena mesin rendering, tetapi efeknya tetap ada. + +### “Bagaimana cara mengubah warna bayangan agar sesuai dengan merek saya?” + +Cukup ganti `java.awt.Color.GRAY` dengan `java.awt.Color` apa pun yang Anda inginkan, misalnya `new java.awt.Color(0, 120, 215)` untuk biru korporat. + +--- + +## Ilustrasi Gambar + +![buat bentuk persegi panjang di dokumen Word Java](https://example.com/images/rectangle-shadow.png) + +*Teks alt:* **create rectangle shape** ilustrasi yang menunjukkan persegi panjang sian dengan bayangan jatuh abu-abu dalam dokumen Word. + +--- + +## Ringkasan & Langkah Selanjutnya + +Kami telah membahas cara **create rectangle shape**, **apply shadow effect**, **add shape shadow**, dan **set shadow distance** menggunakan Aspose.Words for Java. Kode ini mandiri, berjalan pada JDK modern apa pun, dan menghasilkan file `.docx` yang halus siap didistribusikan. + +Ingin melangkah lebih jauh? Coba: + +- Menambahkan teks di dalam persegi panjang dengan `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Membuat tabel bentuk untuk membangun diagram. +- Mengekspor dokumen ke PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Setiap hal ini dibangun di atas dasar yang sama yang baru saja kami jelajahi, sehingga Anda akan merasa nyaman memperluas contoh ini. + +--- + +## Pemikiran Akhir + +Menguasai tugas **create word document java** seperti membentuk dan memberi bayangan memberi Anda keunggulan besar saat mengotomatisasi laporan, kontrak, atau materi pemasaran. Pendekatan yang ditunjukkan di sini bersih, dapat dipelihara, dan—yang terpenting—mudah disesuaikan untuk gaya visual apa pun yang Anda butuhkan. + +Jalankan kode tersebut, sesuaikan blur, sudut, dan jarak, dan saksikan dokumen Anda bertransformasi dari biasa menjadi halus. Jika Anda menemui kendala, tinggalkan komentar di bawah; saya senang membantu. + +Selamat coding! + +## Tutorial Terkait + +- [Buat Dokumen Word Java – Tambahkan Bentuk Persegi Panjang dengan Efek Bayangan](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Cara membuat bidang formulir dan menambahkan konten menggunakan DocumentBuilder di Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Buat PDF dari Word dengan Generasi Barcode – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/italian/java/document-conversion-and-export/_index.md index 03ee1cd629..c3660028d4 100644 --- a/words/italian/java/document-conversion-and-export/_index.md +++ b/words/italian/java/document-conversion-and-export/_index.md @@ -86,18 +86,33 @@ Scopri come formattare tabelle e applicare stili di tabella in Aspose.Words per ### [Converti docx in markdown – Esporta equazioni matematiche in LaTeX con Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Scopri come trasformare documenti DOCX in markdown e convertire le equazioni matematiche in LaTeX usando Aspose.Words. +### [Salva Word come markdown – Esporta Math in LaTeX con Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Scopri come salvare un documento Word in formato markdown ed esportare le equazioni matematiche in LaTeX usando Aspose.Words per Java. + ### [Come incorporare immagini in Markdown durante la conversione di DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Scopri come includere immagini nei file Markdown generati dalla conversione di documenti DOCX con Aspose.Words for Java. +### [Incorporare immagini come Base64 durante la conversione di DOCX in Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Scopri come incorporare immagini in formato Base64 nei file Markdown generati dalla conversione di documenti DOCX con Aspose.Words per Java. + ### [Salva documento come TXT – Guida rapida all'esportazione di equazioni Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Esporta documenti Word in formato TXT mantenendo le equazioni matematiche in modo semplice e veloce. +### [Esporta docx in txt con Java – Guida completa di programmazione](./export-docx-to-txt-with-java-complete-programming-guide/) +Scopri come convertire documenti DOCX in file TXT usando Aspose.Words per Java con esempi di codice completi. + ### [Aspose Word to PDF – Converti DOCX in PDF in Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Scopri come convertire file DOCX in PDF usando Aspose.Words per Java con pochi passaggi. ### [Crea PDF accessibile da DOCX – Guida completa](./create-accessible-pdf-from-docx-complete-guide/) Impara a generare PDF accessibili da file DOCX mantenendo struttura e tag per l'accessibilità. +### [Salva documento come PDF con Aspose.Words Java – Guida completa all'accessibilità](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Scopri come salvare documenti PDF accessibili da Word usando Aspose.Words per Java, mantenendo struttura e tag per l'accessibilità. + +### [Crea PDF accessibile in Java – Guida completa al tagging](./create-accessible-pdf-in-java-full-tagging-guide/) +Scopri come generare PDF accessibili con tag completi usando Aspose.Words per Java, garantendo conformità e leggibilità. + ## Domande frequenti **Q: Come aggiungo una filigrana a un PDF esistente usando Aspose.Words?** diff --git a/words/italian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/italian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..71b9ba1cc4 --- /dev/null +++ b/words/italian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Crea PDF accessibili in Java con codice passo‑passo. Scopri come etichettare + i PDF per l'accessibilità e abilitare il tagging dei PDF usando PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: it +og_description: Crea PDF accessibili in Java con codice passo‑passo. Scopri come etichettare + i PDF per l'accessibilità e abilitare il tagging dei PDF usando PdfSaveOptions. +og_title: Crea PDF accessibile in Java – Guida completa al tagging +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Crea PDF accessibili in Java – Guida completa al tagging +url: /it/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea PDF Accessibile in Java – Guida Completa al Tagging + +Ti sei mai chiesto come **creare PDF accessibili** direttamente dal codice Java? Non sei solo. Molti sviluppatori devono fornire contenuti a utenti che si affidano ai lettori di schermo, e la differenza tra un PDF semplice e uno accessibile può essere enorme. In questo tutorial ti guideremo attraverso **come taggare i PDF per l'accessibilità**, ti mostreremo **come creare PDF taggati** con Aspose PDF for Java, e riveleremo i passaggi esatti per **aggiungere tag di accessibilità ai PDF** così ogni lettore può ottenere le stesse informazioni. + +Tratteremo anche le migliori pratiche per **abilitare il tagging dei PDF**, gli errori comuni, e un esempio completo e eseguibile che puoi inserire nel tuo progetto oggi. Nessun riferimento vago—solo codice concreto, spiegazioni e un file finale che puoi aprire in Adobe Acrobat per verificare i tag. + +## Cosa Imparerai + +- Il motivo alla base del tagging dei PDF e della conformità all'accessibilità. +- Prerequisiti e configurazione della libreria (Aspose PDF for Java 23.10 o successivo). +- Come **creare PDF accessibili** da zero, passo dopo passo. +- Modi per **aggiungere tag di accessibilità ai PDF** oltre alla chiamata base `setTagDocumentStructure`. +- Suggerimenti per testare il risultato e risolvere i problemi comuni. + +Alla fine di questa guida sarai in grado di generare PDF che superano i controlli WCAG 2.1 AA e hanno un aspetto professionale allo stesso tempo. + +--- + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +| Requisito | Motivo | +|-------------|--------| +| **Java 8+** | Funzionalità moderne del linguaggio e migliore gestione Unicode. | +| **Aspose PDF for Java** (v23.10 or newer) | Fornisce la classe `PdfSaveOptions` e il supporto al tagging. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Per compilazione e debug facili. | +| **Write permission** to a folder where the PDF will be saved | La chiamata `doc.save` richiede un percorso scrivibile. | + +Se non hai ancora aggiunto Aspose PDF al tuo progetto, inserisci la seguente dipendenza Maven nel tuo `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Consiglio professionale:** Usa l'ultima versione; le release più recenti migliorano la precisione del tagging e aggiungono funzionalità di accessibilità specifiche per lingua. + +--- + +## Passo 1: Configura lo Scheletro del Documento + +Per prima cosa, creiamo un nuovo oggetto `Document`. Pensalo come una tela vuota che in seguito conterrà i tag necessari per l'accessibilità. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Perché è importante:** Senza alcun contenuto, non c'è nulla da taggare. Aggiungere anche un semplice `TextFragment` fornisce al motore di tagging qualcosa su cui lavorare, e crea automaticamente un tag `

` (paragrafo) quando abilitiamo successivamente il tagging della struttura. + +## Passo 2: Crea le Opzioni di Salvataggio PDF (il Cuore del Tagging) + +Ora prepariamo le opzioni che indicano ad Aspose PDF di incorporare un albero di struttura logica all'interno del file. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +La chiamata a `setTagDocumentStructure(true)` è l'interruttore per **abilitare il tagging dei PDF**. Quando impostato a true, la libreria costruisce un albero di tag che rispecchia il layout visivo, rendendo il PDF leggibile dalle tecnologie assistive. + +> **Nota:** Questo è il modo più semplice per **creare PDF taggati**. Per un controllo più granulare (ad esempio, impostare la lingua o tag personalizzati), puoi esplorare `pdfOptions.setTagLanguage("en-US")` e `pdfOptions.setTagStructureTreeRoot(...)`. + +## Passo 3: Salva il PDF Accessibile + +Infine, scriviamo il documento su disco usando le opzioni appena configurate. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Quando `doc.save` termina, troverai `accessible.pdf` nella cartella `output`. Aprilo in Adobe Acrobat e guarda **File → Properties → Description → Tags** – dovresti vedere un albero di tag popolato. + +## Come Taggare PDF per l'Accessibilità – Oltre le Basi + +Il frammento a tre passaggi sopra già **aggiunge tag di accessibilità ai PDF**, ma i documenti del mondo reale spesso richiedono un po' più di rifinitura. Ecco alcune migliorie che puoi aggiungere: + +### 1. Imposta la Lingua del Documento + +I lettori di schermo usano l'attributo lingua per pronunciare correttamente il testo. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Fornisci un Titolo e un Soggetto + +I metadati aiutano gli strumenti assistivi a fornire contesto prima che l'utente apra il file. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Tagga le Immagini con Testo Alternativo + +Se inserisci immagini, hanno bisogno di descrizioni `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Contrassegna le Intestazioni delle Tabelle + +Le tabelle sono famose per confondere i lettori a meno che non segnali le righe di intestazione. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Questi passaggi aggiuntivi rendono il tuo PDF non solo *tecnicamente* taggato, ma davvero **accessibile** per un pubblico diversificato. + +--- + +## Problemi Comuni Quando Abiliti il Tagging dei PDF + +| Sintomo | Probabile Causa | Risoluzione | +|---------|-----------------|-------------| +| Tag mancanti in Acrobat | `setTagDocumentStructure` lasciato a `false` | Assicurati di chiamare `pdfOptions.setTagDocumentStructure(true)`. | +| Ordine di lettura errato | Layout complesso senza tag espliciti | Usa `pdfOptions.setTagStructureTreeRoot(...)` per definire un ordine personalizzato. | +| Le immagini vengono lette come “image” senza descrizione | Nessun testo alternativo impostato | Chiama `image.getAlternativeText().setValue("...")`. | +| Lingua non riconosciuta | `setTagLanguage` omesso o locale errato | Fornisci un codice lingua BCP‑47 (`en-US`, `fr-FR`). | + +Essere consapevoli di questi problemi ti farà risparmiare ore di debug in seguito. + +--- + +## Verifica il Risultato – Cosa Aspettarsi + +Dopo aver eseguito il programma, apri `output/accessible.pdf` in Adobe Acrobat Reader: + +1. **Pannello Tag** (`View → Show/Hide → Navigation Panes → Tags`) dovrebbe elencare una gerarchia come `/Document → /Part → /Sect → /Para`. +2. **Ordine di lettura** dovrebbe seguire il flusso visivo (testo prima, poi immagini). +3. **Lettore di schermo** (NVDA, VoiceOver) leggerà “Hello, accessible PDF!” invece di semplicemente “Page 1”. + +Se qualcuno di questi elementi manca, ricontrolla i passaggi sopra—soprattutto la chiamata `setTagDocumentStructure`. + +--- + +## Esempio Completo Funzionante (Pronto per Copia‑Incolla) + + + +## Tutorial Correlati + +- [Crea PDF Accessibile da Word – Converti in PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Crea PDF Accessibile da DOCX – Guida Completa](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Come salvare un documento come PDF con Aspose.Words per Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/italian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/italian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..ed61e9f950 --- /dev/null +++ b/words/italian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Incorpora le immagini come base64 mentre converti i file docx in markdown + con Aspose.Words per Java. Impara a convertire Word in markdown, a salvare Word + come markdown e a gestire le immagini. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: it +og_description: Incorpora le immagini in base64 durante la conversione da docx a markdown + con Aspose.Words per Java. Guida completa per convertire Word in markdown e salvare + Word come markdown. +og_title: Incorpora le immagini in Base64 durante la conversione da DOCX a Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Incorpora le immagini in Base64 durante la conversione da DOCX a Markdown +url: /it/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Incorporare immagini come Base64 durante la conversione da DOCX a Markdown + +Ti sei mai chiesto come **incorporare immagini come base64** mentre **converti docx in markdown**? Non sei l'unico—gli sviluppatori chiedono costantemente come mantenere le immagini in linea senza gestire file separati. La buona notizia è che Aspose.Words for Java lo rende un gioco da ragazzi: puoi convertire un documento Word in Markdown e incorporare automaticamente ogni immagine come stringa Base64. + +In questo tutorial percorreremo l'intero processo—dal caricamento di un `.docx` che contiene immagini, alla configurazione di un callback `MarkdownSaveOptions` che fa il lavoro pesante, fino al salvataggio del risultato in un file `.md` pulito. Alla fine saprai esattamente come **convertire Word in Markdown**, **convertire immagini in base64**, e **salvare Word come Markdown** senza lasciare cartelle di immagini residue. Nessuno strumento esterno, nessuna post‑elaborazione manuale—solo puro codice Java che puoi inserire in qualsiasi progetto. + +## Cosa ti servirà + +- **Java 17** (o qualsiasi JDK recente) – il codice utilizza la sintassi lambda, ma puoi adattarlo a versioni più vecchie. +- **Aspose.Words for Java** library (ultima versione al 2026). Aggiungi la dipendenza Maven o il JAR al tuo classpath. +- Un file **DOCX** di esempio che contiene almeno un'immagine. +- Un IDE o un semplice editor di testo—Visual Studio Code, IntelliJ IDEA, o anche `vim` va bene. + +Se li hai già, ottimo—tuffiamoci subito. + +## Passo 1: Carica il documento Word + +Prima creiamo un'istanza `Document` che punta al file sorgente. Questo è lo stesso passo sia che tu **converti docx in markdown** sia che stia semplicemente leggendo il file per altri scopi. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Perché è importante:** L'oggetto `Document` è il punto di ingresso per ogni operazione Aspose. Contiene l'intera struttura Word—including immagini, tabelle e stili—così il callback successivo può ispezionare ogni risorsa. + +## Passo 2: Crea MarkdownSaveOptions e registra un callback di salvataggio delle risorse + +La magia risiede in `MarkdownSaveOptions`. Collegando un `IResourceSavingCallback` otteniamo il controllo su come ogni risorsa esterna (come un'immagine) viene scritta. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### Perché usare `setSaveToMemory(true)`? + +Quando `saveToMemory` è true, Aspose scrive i byte dell'immagine in uno stream di memoria invece che in un file. L'esportatore Markdown quindi converte quello stream in una stringa Base64 e la inserisce direttamente nel tag immagine Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Questo è il fulcro di **incorporare immagini come base64**. + +## Passo 3: Salva il documento come Markdown + +Ora che il callback è in posizione, l'ultimo passo è semplicemente chiamare `save`. Qui è dove effettivamente **converti Word in Markdown** e, grazie al callback, anche **converti immagini in base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Risultato:** `out.md` contiene testo Markdown con ogni immagine rappresentata come un URI `data:`. Nessun file immagine extra viene creato su disco, così la cartella rimane ordinata. + +## Passo 4: Verifica l'output e i problemi comuni + +Apri il `out.md` generato in qualsiasi visualizzatore Markdown (VS Code, GitHub, o un generatore di siti statici). Dovresti vedere qualcosa del genere: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Lista di controllo per la risoluzione dei problemi + +| Problema | Causa Probabile | Soluzione | +|----------|-----------------|-----------| +| L'immagine appare come un collegamento interrotto | `setSaveToMemory` è stato omesso | Assicurati che `args.setSaveToMemory(true);` sia all'interno del callback | +| La stringa Base64 è troncata | Mancata corrispondenza della codifica del file di output | Salva il Markdown usando UTF‑8 (predefinito per Aspose) | +| Nomi file inaspettati | `setKeepResourceOriginalName(true)` | Mantienilo `false` per forzare la logica di denominazione personalizzata | + +## Passo 5: Varianti avanzate (opzionale) + +### Converti solo le immagini selezionate + +Se vuoi incorporare solo alcune immagini (ad esempio quelle più grandi di 100 KB), aggiungi un controllo sulla dimensione: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Usa un formato immagine diverso + +`ResourceSavingArgs` ti fornisce i byte grezzi, così potresti ricodificare i JPEG in PNG prima di incorporarli—utile quando il consumatore Markdown di destinazione preferisce PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Queste modifiche illustrano quanto sia flessibile l'approccio **incorporare immagini come base64** quando **converti docx in markdown**. + +## Conclusione + +Hai appena imparato come **incorporare immagini come base64** mentre **converti docx in markdown** usando Aspose.Words for Java. Collegando un semplice `IResourceSavingCallback`, la libreria fa tutto il lavoro pesante: **converti Word in Markdown**, **converti immagini in base64**, e infine **salvi Word come Markdown** con una singola chiamata `save`. + +Sentiti libero di sperimentare—prova diverse regole di filtraggio delle immagini, passa all'output HTML, o concatena questo passaggio con un generatore di siti statici. Lo stesso schema funziona anche per altri formati (HTML, EPUB), così puoi riutilizzare il callback ovunque ti servano risorse in linea. + +**Passi successivi:** +- Esplora `HtmlSaveOptions` per HTML con immagini Base64. +- Combina questo con una pipeline CI per automatizzare la generazione della documentazione. +- Approfondisci `DocumentVisitor` di Aspose se hai bisogno di un controllo ancora più fine sul processo di conversione. + +Buon coding, e goditi i tuoi file Markdown puliti e autonomi! + +## Tutorial correlati + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/italian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..18e1b1899d --- /dev/null +++ b/words/italian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-26 +description: Esporta docx in txt usando Java e Aspose.Words. Scopri come convertire + docx in testo, preservare Unicode e esportare Word in txt in pochi passaggi. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: it +og_description: Esporta docx in txt in Java. Questo tutorial mostra come convertire + docx in testo, mantenere il testo semplice Unicode e esportare Word in txt in modo + efficiente. +og_title: Esporta docx in txt con Java – Guida completa +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Esporta docx in txt con Java – Guida completa alla programmazione +url: /it/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esporta docx in txt con Java – Guida completa di programmazione + +Hai mai avuto bisogno di **export docx to txt** ma temuto di perdere i caratteri speciali? Non sei l'unico. Quando converti documenti Word in file plain‑text, i simboli Unicode, le tabelle e persino la formattazione semplice possono scomparire come per magia. + +In questa guida vedremo un modo affidabile per **export docx to txt** usando Aspose.Words per Java, preservando ogni glifo Unicode e mantenendo i layout delle tabelle leggibili. Alla fine saprai anche come **convert docx to text**, **convert word to text**, e persino **export word as txt** senza problemi. + +## Cosa copre questo tutorial + +* Impostare Aspose.Words in un progetto Java +* Caricare un file DOCX e prepararlo per l'output plain‑text +* Configurare il supporto **plain text unicode** tramite `TxtSaveOptions` +* Trucchi opzionali per mantenere le tabelle leggibili nel file `.txt` risultante +* Salvare il file e verificare l'output + +Nessuno script esterno, nessuno strumento da riga di comando misterioso—solo puro codice Java che puoi inserire in qualsiasi progetto Maven o Gradle. + +> **Perché importa?** I file plain‑text sono leggeri, facili da gestire con il version‑control e perfetti per l'indicizzazione di ricerca o pipeline di elaborazione a valle. Se hai mai provato a `cat` un file Word e hai ottenuto spazzatura, questo tutorial risolve il problema. + +## Export docx to txt – Panoramica + +Prima di immergerci nel codice, chiarifichiamo la terminologia. **Export docx to txt** significa prendere un pacchetto Microsoft Word `.docx` e scrivere il suo contenuto testuale in un semplice file `.txt`. A differenza di una conversione PDF, un'esportazione di testo rimuove lo stile ma può conservare interruzioni di riga, marcatori di paragrafo e—se lo configuri correttamente—caratteri Unicode come emoji, lettere accentate o script asiatici. + +Aspose.Words rende tutto indolore perché astrae il formato del file Word e offre una classe `TxtSaveOptions` dove puoi specificare la codifica, la gestione delle tabelle e altro. + +### Prerequisiti + +* Java 11 o superiore (l'API funziona con Java 8+, ma assumeremo un JDK recente) +* Aspose.Words per Java JAR (disponibile su Maven Central) +* Un file di esempio `unicode.docx` contenente diversi caratteri Unicode—ad esempio “こんにちは”, “😊”, e una semplice tabella + +Se li hai, iniziamo. + +## Passo 1: Carica il file DOCX (Convert docx to text) + +La prima cosa da fare è leggere il documento sorgente in memoria. È qui che inizia ufficialmente il processo di **convert docx to text**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Perché è importante:* `Document` è la rappresentazione di Aspose.Words di un file Word. Caricandolo, ottieni l'accesso a tutti i paragrafi, le tabelle e persino gli elementi nascosti. Se il file non viene trovato, Aspose lancia una chiara `FileNotFoundException`, così saprai subito cosa è andato storto. + +## Passo 2: Configura TxtSaveOptions per Unicode (Plain text unicode) + +I file plain‑text sono semplici flussi di byte, quindi devi indicare a Java quale set di caratteri usare. UTF‑8 è lo standard de‑facto per **plain text unicode** perché può codificare ogni punto di codice Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Suggerimento professionale:** Se salti la chiamata `setEncoding`, Aspose usa la codifica predefinita della piattaforma, che su molte macchine Windows è Windows‑1252. Questa impostazione predefinita eliminerà silenziosamente caratteri come “ß” o “—”. + +## Passo 3: Preserva il layout della tabella (Opzionale, ma utile per la leggibilità) + +Quando **export word as txt**, le tabelle di solito si appiattiscono in un'unica riga di testo, rendendole illeggibili. Aspose.Words offre un semplice flag per mantenere la struttura visiva. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Quando usarlo:* Se il tuo DOCX di origine contiene fatture, orari o qualsiasi dato a griglia, abilitare `PreserveTableLayout` inserirà tabulazioni e interruzioni di riga così il file risultante assomiglierà ancora a una tabella. Se non ti serve, puoi omettere la riga e ottenere un output più compatto. + +## Passo 4: Salva il documento come plain‑text (Export word as txt) + +Ora il lavoro pesante è fatto—basta scrivere i byte su disco. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Eseguendo il programma si genera `plain.txt` nella stessa cartella. Aprilo con qualsiasi editor di testo (Notepad++, VS Code, anche `cat` in un terminale) e vedrai: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Nota come il saluto giapponese e la faccina siano sopravvissuti, e la tabella abbia mantenuto le colonne grazie a `PreserveTableLayout`. Questa è l'essenza di un **export docx to txt** pulito. + +## Passo 5: Verifica l'output (Convert word to text sanity check) + +Un rapido controllo di sanità previene la perdita silenziosa di dati. Ecco alcuni modi per confermare che tu abbia davvero **convert word to text** correttamente: + +1. **Checksum comparison** – calcola un hash SHA‑256 del file `.txt` prima e dopo una conversione round‑trip (txt → docx → txt) per garantire la stabilità. +2. **Search for Unicode markers** – usa `grep` o la ricerca nel file dell'IDE per individuare caratteri come “😊”. +3. **Open in multiple editors** – alcune vecchie versioni di Notepad di Windows interpretano ancora male UTF‑8 senza BOM; aprire il file in VS Code conferma la codifica corretta. + +Se uno di questi controlli fallisce, ricontrolla che `saveOptions.setEncoding(StandardCharsets.UTF_8)` sia presente e che il tuo DOCX di origine contenga davvero testo Unicode. + +## Problemi comuni e come evitarli + +| Problema | Perché succede | Soluzione | +|----------|----------------|-----------| +| **Caratteri mancanti** | Il charset di sistema predefinito (es. Windows‑1252) elimina i glifi non‑ASCII. | Imposta esplicitamente UTF‑8 tramite `saveOptions.setEncoding`. | +| **Le tabelle diventano una singola riga** | `PreserveTableLayout` lasciato al valore predefinito `false`. | Chiama `saveOptions.setPreserveTableLayout(true)`. | +| **File non trovato** | Percorso errato o permessi di lettura mancanti. | Usa percorsi assoluti o `Paths.get(...)` con una corretta gestione delle eccezioni. | +| **Rallentamento delle prestazioni su documenti enormi** | Caricamento dell'intero documento in memoria. | Trasmetti il documento a blocchi usando `DocumentBuilder` se ti servono solo sezioni specifiche. | + +## Bonus: Esportare più file DOCX in batch + +Se hai bisogno di **convert docx to text** per un'intera cartella, avvolgi la logica in un ciclo: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Questo snippet **export docx to txt** per ogni file nella directory, risparmiandoti ore di lavoro manuale. + +## Conclusione + +Hai appena imparato come **export docx to txt** con Java, garantendo che ogni carattere Unicode rimanga intatto, le tabelle siano leggibili e l'intero processo sia ripetibile. Configurando `TxtSaveOptions` per UTF‑8 e, facoltativamente, preservando i layout delle tabelle, puoi affidabilmente **convert docx to text**, **convert word to text**, e **export word as txt** per qualsiasi workflow a valle. + +Pronto per la prossima sfida? Prova a esportare in altri formati plain‑text come markdown (`.md`) o CSV, o esplora le capacità di conversione PDF di Aspose.Words. Gli stessi principi—codifica esplicita, preservazione del layout e verifica approfondita—si applicano in tutti i casi. + +Buona programmazione, e che i tuoi file di testo rimangano sempre ricchi di Unicode! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="diagramma del flusso export docx to txt"} + +## Tutorial correlati + +- [Converti Docx in Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Converti DOCX in PDF con Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Converti docx in markdown – Esporta equazioni matematiche in LaTeX con Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/italian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..5295539f53 --- /dev/null +++ b/words/italian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: Salva il documento come PDF usando Aspose.Words per Java e aggiungi l'accessibilità + al PDF. Impara a convertire docx in PDF, a etichettare le linee orizzontali e a + garantire la conformità a PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: it +og_description: Salva il documento come PDF con Aspose.Words Java aggiungendo l'accessibilità + al PDF. Guida passo‑passo per convertire docx in PDF e contrassegnare le linee orizzontali + per la conformità PDF/UA‑2. +og_title: Salva documento come PDF con Aspose.Words Java – Accessibilità semplificata +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Salva documento come PDF con Aspose.Words Java – Guida completa all'accessibilità +url: /it/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salva documento come PDF con Aspose.Words Java – Guida completa all'accessibilità + +Ti sei mai chiesto come **salvare documento come PDF** mantenendolo accessibile per i lettori di schermo? Non sei solo. Molti sviluppatori hanno bisogno di *convertire docx in pdf* e soddisfare comunque gli standard PDF/UA‑2, soprattutto quando la sorgente contiene linee orizzontali che devono essere correttamente taggate. In questo tutorial percorreremo i passaggi esatti per **salvare documento come PDF** usando Aspose.Words per Java, aggiungere automaticamente **accessibilità al PDF**, e garantire che ogni linea orizzontale sia **taggata** come artefatto. + +Inizieremo con un progetto Java pulito, caricheremo un DOCX che contiene già linee orizzontali, configureremo le opzioni di salvataggio PDF per la conformità PDF/UA‑2, e infine scriveremo un PDF completamente accessibile. Alla fine, sarai in grado di **salvare documento come pdf** con la certezza che superi i controlli di accessibilità. + +## Prerequisiti + +- Java 8 o versioni successive installato (il tutorial è stato testato su JDK 17). +- Maven 3.6+ (o Gradle se preferisci) per gestire le dipendenze. +- Una licenza valida di Aspose.Words per Java (la versione di prova funziona, ma una licenza rimuove le filigrane di valutazione). +- Un file DOCX (`input.docx`) che includa almeno una linea orizzontale — pensa a un semplice separatore di linea che aggiungeresti in Word. + +> **Suggerimento:** Se non hai a disposizione un DOCX, crea semplicemente un nuovo documento Word, digita qualche paragrafo, inserisci *Insert → Horizontal Line*, salva come `input.docx` e posizionalo in una cartella a tua scelta. + +## Passo 1: Configura il progetto Maven + +Per prima cosa, crea un nuovo progetto Maven (o aggiungine uno esistente). Il `pom.xml` necessita della dipendenza Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Perché è importante:** Aggiungere l'artifact `aspose-words` è il primo passo per *convertire docx in pdf*. Senza di esso, il compilatore non riconoscerà `Document`, `PdfSaveOptions` e altre classi cruciali. + +## Passo 2: Carica il DOCX sorgente contenente linee orizzontali + +Ora scriveremo una piccola classe Java che carica il DOCX. Qui inizia la parte **taggare le linee orizzontali** — Aspose.Words tratta automaticamente una linea orizzontale come un paragrafo con un bordo, ma lasceremo che il motore PDF/UA gestisca il tagging. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Nota che non abbiamo ancora salvato nulla — stiamo solo **caricando** il DOCX, che è la prima metà di *convertire docx in pdf*. L'oggetto `Document` ora contiene tutto il contenuto Word, incluse le linee orizzontali che hai inserito. + +## Passo 3: Configura le opzioni di salvataggio PDF per la conformità PDF/UA‑2 + +La magia di **aggiungere accessibilità al PDF** risiede in `PdfSaveOptions`. Impostando il livello di conformità a `PDF_UA_2`, Aspose.Words farà: + +1. Taggare gli elementi strutturali (intestazioni, tabelle, ecc.). +2. Contrassegnare gli elementi decorativi — come le linee orizzontali — come *artifact*, così i lettori di schermo li ignorano. +3. Inserire i metadati PDF/UA necessari. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Perché impostare la conformità?** Senza `PDF_UA_2`, il PDF risultante può ancora essere leggibile ma non supererà i validator di accessibilità automatizzati. Il requisito **taggare le linee orizzontali** è soddisfatto automaticamente perché PDF/UA le tratta come *artifact* quando il flag di conformità è attivo. + +## Passo 4: Salva il documento come PDF + +Ora finalmente **salviamo documento come pdf**. Questa singola riga esegue il lavoro pesante — converte il DOCX, applica i tag di accessibilità e scrive il file su disco. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Esegui la classe (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) e vedrai un messaggio di conferma. Apri il `ua_compliant.pdf` risultante in Adobe Acrobat e controlla **File → Properties → Description → PDF/A, PDF/UA** — dovresti vedere elencato “PDF/UA‑2”. + +### Output previsto + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Apri il PDF, e noterai: + +- Il testo del documento è selezionabile e ricercabile. +- La linea orizzontale è invisibile ai lettori di schermo (trattata come un artifact). +- Il PDF supera gli strumenti di validazione PDF/UA di base (ad es., PAC 3). + +## Passo 5: Verifica l'accessibilità – Checklist rapida + +Anche se Aspose.Words fa la maggior parte del lavoro, è buona pratica verificare l'output. + +| Controllo | Come verificare | +|-------|----------------| +| **Titolo del documento** | Apri Acrobat → File → Properties → campo Title (dovrebbe corrispondere a `pdfOptions.setTitle`). | +| **Tagging degli artifact** | Usa lo strumento “Reading Order” di Acrobat. Le linee orizzontali dovrebbero apparire come *Artifact* (grigio). | +| **Ordine di lettura logico** | Esegui l’“Accessibility Checker” in Acrobat; assicurati che non ci siano errori strutturali. | +| **PDF taggato** | In Acrobat, guarda il pannello “Tags” – dovresti vedere una gerarchia (Document → Section → Paragraph, ecc.). | +| **Conformità PDF/UA** | Acrobat mostrerà “PDF/UA‑2” nella scheda “Standards”. | + +Se uno di questi controlli fallisce, ricontrolla di aver usato l'ultima versione di Aspose.Words e che `setCompliance(PdfCompliance.PDF_UA_2)` sia applicata correttamente. + +## Problemi comuni e come evitarli + +1. **Licenza mancante** – La versione di prova aggiunge una filigrana che può compromettere la validazione PDF/UA. Applica la tua licenza all'inizio di `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Percorso di input errato** – Un `FileNotFoundException` interromperà la conversione. Usa percorsi assoluti o posiziona il DOCX nella radice del progetto e riferiscilo con `new File("input.docx").getAbsolutePath()`. +3. **Uso di una versione Aspose più vecchia** – Il supporto PDF/UA è stato aggiunto nella versione 22.9. Aggiorna all'ultima release per evitare funzionalità mancanti. +4. **Linea orizzontale come immagine** – Se hai inserito la linea come immagine invece di una linea orizzontale nativa di Word, Aspose la tratta come un'immagine normale, non come un artifact. Sostituisci l'immagine con la *Horizontal Line* integrata di Word per un corretto tagging. + +## Estendere la soluzione – E se ti servisse di più? + +- **Tag personalizzati**: Se hai altri elementi decorativi (ad es., icone decorative), puoi marcarli manualmente come artifact usando `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Documenti multipli**: Itera su una cartella di file DOCX e convertili in batch, riutilizzando la stessa istanza `PdfSaveOptions` per le prestazioni. +- **Aggiunta di un tag lingua**: Per PDF multilingue, imposta `pdfOptions.setLanguage("en-US")` per aiutare le tecnologie assistive a scegliere la voce corretta. + +## Esempio completo funzionante (tutto il codice insieme) + +Di seguito trovi il programma Java completo e eseguibile. Copialo‑incollalo nel tuo IDE, regola i percorsi e avvia l'esecuzione. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Eseguilo, apri il PDF generato, e avrai un file pulito e accessibile pronto per la distribuzione. + +## Conclusione + +Abbiamo appena dimostrato come **salvare documento come pdf** con Aspose.Words per Java aggiungendo automaticamente **accessibilità al pdf** e **taggare le linee orizzontali** come artifact. I punti chiave: + +- Usa `PdfSaveOptions` con conformità `PDF_UA_2` per soddisfare gli standard di accessibilità. +- Caricare un DOCX e chiamare `doc.save(..., pdfOptions)` è tutto ciò di cui hai bisogno per **convertire docx in pdf**. +- Le linee orizzontali sono gestite automaticamente — nessun codice aggiuntivo necessario, soddisfacendo il requisito **taggare le linee orizzontali**. +- L'approccio è completamente **aspose convert docx pdf** conforme, funziona con l'ultima versione della libreria e produce un PDF pronto per la validazione. + +Pronto per la prossima sfida? Prova ad aggiungere metadati personalizzati, incorporare font, o elaborare in batch un'intera cartella di file DOCX. Ognuna di queste estensioni si basa sulla stessa base che abbiamo mostrato. + +Hai domande sulla conformità PDF/UA, licenze o sulla gestione di altri elementi Word? Lascia un commento o consulta la documentazione ufficiale di Aspose — c'è una ricchezza di esempi da esplorare. Buon coding e divertiti a creare PDF accessibili! + +![salva documento come pdf usando Aspose.Words Java – esempio di PDF accessibile](placeholder-image.png "salva documento come pdf usando Aspose.Words Java – esempio di PDF accessibile") + +## Tutorial correlati + +- [Come salvare documento come pdf con Aspose.Words per Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Come convertire Word in PDF usando Aspose.Words per Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Converti DOCX in PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/italian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..f9ab6bb165 --- /dev/null +++ b/words/italian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-26 +description: Salva Word come markdown e scopri come esportare le equazioni matematiche + in LaTeX usando Aspose.Words per Java. Converti le equazioni Word in LaTeX in poche + righe. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: it +og_description: Salva Word come markdown e impara come esportare le equazioni matematiche + in LaTeX usando Aspose.Words per Java. Una guida completa e eseguibile. +og_title: Salva Word come markdown – Esporta la matematica in LaTeX con Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Salva Word come markdown – Esporta matematica in LaTeX con Java +url: /it/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salva Word come markdown – Esporta formule in LaTeX con Java + +Hai mai avuto bisogno di **salvare Word come markdown** ma temuto che le tue equazioni si trasformassero in un caos? Non sei solo. In questa guida ti mostreremo **come esportare le formule** da un file `.docx` direttamente in LaTeX mentre il resto del documento diventa un Markdown pulito. + +Copriremo tutto, dall'installazione della libreria Aspose.Words alla verifica del file finale `out.md`. Alla fine sarai in grado di **convertire le equazioni Word in LaTeX** con una singola chiamata di metodo, e comprenderai le piccole sfumature che rendono la conversione affidabile. + +--- + +## Cosa ti serve + +- **Java 8+** – il codice funziona su qualsiasi JDK recente. +- **Aspose.Words for Java** – sia la dipendenza Maven/Gradle sia il JAR se preferisci l'installazione manuale. +- Un documento Word (`math.docx`) che contiene almeno un'equazione Office Math. +- Un IDE o la semplice riga di comando `javac`/`java` – quello che preferisci. + +Se li hai già, ottimo. Altrimenti, la sezione successiva mostra esattamente come aggiungere la libreria al tuo progetto. + +## Salva Word come markdown – Passo 1: Aggiungi Aspose.Words al tuo progetto + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Consiglio:** Aspose offre una licenza temporanea gratuita per i test. Inserisci il file `license.xml` nella cartella delle risorse e chiama `License license = new License(); license.setLicense("license.xml");` prima di caricare qualsiasi documento. + +Una volta risolta la dipendenza, sei pronto per scrivere il codice di conversione. + +## Come esportare le equazioni matematiche in LaTeX + +Il lavoro pesante è svolto da `MarkdownSaveOptions`. Cambiando il suo `OfficeMathExportMode` in `LATEX`, ogni oggetto Office Math viene renderizzato come frammento LaTeX all'interno dell'output Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Perché funziona + +- **`Document`** è il punto di ingresso di Aspose; astrae il file `.docx` e ti dà accesso a ogni nodo, incluse le equazioni. +- **`MarkdownSaveOptions`** indica alla libreria *come* desideri l'output. Il comportamento predefinito è renderizzare le equazioni come immagini, il che vanifica lo scopo di un formato basato su testo. +- **`OfficeMathExportMode.LATEX`** costringe il motore a tradurre ogni nodo `OfficeMath` nella sua equivalente LaTeX, che i parser Markdown (come GitHub o Jekyll) possono renderizzare quando combinati con un plugin MathJax. + +## Converti le equazioni Word in LaTeX – Passo 2: Verifica l'output Markdown + +Dopo aver eseguito il programma, apri `out.md`. Dovresti vedere qualcosa di simile: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Nota:** I frammenti LaTeX sono racchiusi in `$…$` per la matematica inline e `$$…$$` per la matematica a blocco. Questa è la sintassi standard che la maggior parte dei generatori di siti statici comprende quando MathJax è abilitato. + +Se preferisci che le equazioni rimangano solo inline, puoi modificare ulteriormente `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Da Docx a markdown LaTeX – Passo 3: Casi limite e problemi comuni + +| Situazione | Cosa controllare | Soluzione | +|------------|------------------|-----------| +| **Equazioni nidificate complesse** | Aspose potrebbe generare parentesi graffe extra `{}` che alcuni parser trattano letteralmente. | Post‑processa il Markdown con una semplice regex per comprimere `{{` → `{`. | +| **MathJax mancante sul sito di destinazione** | Le equazioni appaiono come codice LaTeX grezzo. | Aggiungi `` al tuo template HTML. | +| **Documenti di grandi dimensioni** | Il consumo di memoria aumenta perché l'intero documento viene caricato in una volta. | Usa `LoadOptions.setLoadFormat(LoadFormat.DOCX)` e considera di processare le pagine in batch se incontri `OutOfMemoryError`. | +| **Licenza non impostata** | Riceverai un avviso e l'output potrebbe avere una filigrana. | Carica la licenza all'inizio di `main` come mostrato nel consiglio Maven sopra. | + +## Salva Word come markdown – Esempio completo funzionante + +Di seguito trovi una classe autonoma che puoi copiare‑incollare in qualsiasi progetto Java. Sostituisci `YOUR_DIRECTORY` con il percorso dei tuoi file. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Esegui il programma (`java MathToLatexMarkdown`) e vedrai il messaggio di conferma sulla console. Apri `out.md` in qualsiasi editor – le equazioni dovrebbero essere frammenti LaTeX puliti pronti per il rendering. + +## Anteprima dell'output previsto + +![output di save word as markdown con equazioni LaTeX](https://example.com/images/markdown-latex-output.png "output di save word as markdown con equazioni LaTeX") + +*L'immagine mostra un frammento del Markdown generato dove l'equazione `\int_{a}^{b} f(x)\,dx` è racchiusa in `$$`.* + +## Conclusione + +Abbiamo appena dimostrato come **salvare Word come markdown** preservando ogni equazione Office Math come LaTeX nativo. Il passaggio chiave è stato configurare `MarkdownSaveOptions` con `OfficeMathExportMode.LATEX`, che trasforma una tipica pipeline Word‑to‑Markdown in uno strumento di conversione completamente consapevole della matematica. + +Ora puoi: + +1. **Come esportare le formule** da qualsiasi `.docx` senza perdere fedeltà. +2. **Convertire le equazioni Word in LaTeX** per generatori di siti statici, documentazione o blog accademici. +3. Estendere l'approccio per elaborare in batch molti file, integrarlo con pipeline CI, o persino creare un piccolo servizio web. + +Se sei curioso della prossima frontiera, prova a combinare questo con **docx to markdown latex** per documenti ricchi di immagini, o esplora `HtmlSaveOptions` di Aspose per una versione HTML pronta per il web. Le possibilità sono infinite—sperimenta, rompi le cose, e poi condividi le tue scoperte con la community. + +Hai domande o un'equazione difficile che non è stata renderizzata come previsto? Lascia un commento qui sotto, e buona programmazione! + +## Tutorial correlati + +- [Come esportare LaTeX da Word: Converti DOCX in Markdown e salva come PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Converti docx in markdown – Esporta equazioni matematiche in LaTeX con Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Come convertire Word in PDF usando Aspose.Words per Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/italian/java/document-loading-and-saving/_index.md index 0ab9d93519..1c476c88c2 100644 --- a/words/italian/java/document-loading-and-saving/_index.md +++ b/words/italian/java/document-loading-and-saving/_index.md @@ -83,13 +83,13 @@ Le impostazioni del documento sono la chiave per fornire file su misura per le t ## Tutorial Correlati – Caricamento, Salvataggio e Conversione ### [Caricamento e Salvataggio di Documenti HTML con Aspose.Words per Java](./loading-and-saving-html-documents/) -Impara a caricare e salvare documenti HTML in Java usando Aspose.Words per Java. Guida passo‑per‑passo con esempi di codice per un'integrazione fluida dei documenti. +Impara a caricare e salvare documenti HTML in Java usando Aspose.Words per Java. Guida passo‑per‑step con esempi di codice per un'integrazione fluida dei documenti. ### [Lavorare con le Opzioni di Caricamento in Aspose.Words per Java](./using-load-options/) Padroneggia le Load Options in Aspose.Words per Java. Personalizza il caricamento dei documenti, gestisci la crittografia, converti forme, imposta versioni Word e molto altro per una gestione efficiente dei documenti Java. ### [Configurare le Opzioni di Caricamento RTF in Aspose.Words per Java](./configuring-rtf-load-options/) -Configura le RTF Load Options in Aspose.Words per Java. Scopri come riconoscere il testo UTF‑8 nei documenti RTF. Guida passo‑per‑passo con esempi di codice. +Configura le RTF Load Options in Aspose.Words per Java. Scopri come riconoscere il testo UTF‑8 nei documenti RTF. Guida passo‑per‑step con esempi di codice. ### [Caricamento di File di Testo con Aspose.Words per Java](./loading-text-files/) Sblocca la potenza di Aspose.Words per Java. Impara a caricare documenti di testo, gestire elenchi, spazi e direzione del testo. @@ -98,7 +98,7 @@ Sblocca la potenza di Aspose.Words per Java. Impara a caricare documenti di test Scopri la manipolazione avanzata dei documenti con Aspose.Words per Java. Cripta, gestisci metafile e molto altro. I tuoi documenti Word, a modo tuo. ### [Salvataggio di Documenti HTML con Layout Fisso in Aspose.Words per Java](./saving-html-documents-with-fixed-layout/) -Impara a salvare documenti HTML con layout fisso in Aspose.Words per Java. Segui la nostra guida passo‑per‑passo per una formattazione fluida dei documenti. +Impara a salvare documenti HTML con layout fisso in Aspose.Words per Java. Segui la nostra guida passo‑per‑step per una formattazione fluida dei documenti. ### [Opzioni Avanzate di Salvataggio di Documenti HTML con Aspose.Words Java](./advance-html-documents-saving-options/) In questo tutorial abbiamo coperto varie opzioni avanzate di salvataggio di documenti HTML con Aspose.Words per Java. Queste opzioni ti consentono di creare HTML di alta qualità. @@ -106,11 +106,14 @@ In questo tutorial abbiamo coperto varie opzioni avanzate di salvataggio di docu ### [Recupera docx corrotto – Guida completa per riparare e processare i documenti](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) Scopri come riparare file DOCX corrotti, recuperarne il contenuto e continuare l'elaborazione con Aspose.Words per Java. +### [Apri documento Word corrotto – Imposta la modalità di recupero in Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Scopri come aprire file Word danneggiati impostando la modalità di recupero con Aspose.Words per Java, garantendo il ripristino dei contenuti. + ### [Salvataggio di Immagini da Documenti in Aspose.Words per Java](./saving-images-from-documents/) -Impara a salvare immagini da documenti usando Aspose.Words per Java con la nostra guida completa passo‑per‑passo. Personalizza formati, compressione e altro. +Impara a salvare immagini da documenti usando Aspose.Words per Java con la nostra guida completa passo‑per‑step. Personalizza formati, compressione e altro. ### [Salvataggio di Documenti come Markdown in Aspose.Words per Java](./saving-documents-as-markdown/) -Impara a convertire documenti Word in Markdown con Aspose.Words per Java. Questa guida passo‑per‑passo copre l'allineamento delle tabelle, la gestione delle immagini e altro. +Impara a convertire documenti Word in Markdown con Aspose.Words per Java. Questa guida passo‑per‑step copre l'allineamento delle tabelle, la gestione delle immagini e altro. ### [Salvataggio di Documenti in Formato ODT in Aspose.Words per Java](./saving-documents-as-odt-format/) Impara a salvare documenti in formato ODT usando Aspose.Words per Java. Garantisce la compatibilità con suite di ufficio open‑source. @@ -119,16 +122,16 @@ Impara a salvare documenti in formato ODT usando Aspose.Words per Java. Garantis Impara a salvare documenti in formato OOXML con Aspose.Words per Java. Sicuro, ottimizzato e personalizzabile senza sforzo. ### [Salvataggio di Documenti in Formato PCL in Aspose.Words per Java](./saving-documents-as-pcl-format/) -Impara a salvare documenti in formato PCL usando Aspose.Words per Java. Guida passo‑per‑passo ed esempi di codice per una conversione efficiente. +Impara a salvare documenti in formato PCL usando Aspose.Words per Java. Guida passo‑per‑step ed esempi di codice per una conversione efficiente. ### [Salvataggio di Documenti come PDF in Aspose.Words per Java](./saving-documents-as-pdf/) Impara a salvare documenti Word come PDF usando Aspose.Words per Java. Personalizza caratteri, proprietà e qualità delle immagini. Guida completa per la conversione PDF. ### [Salvataggio di Documenti in Formato RTF in Aspose.Words per Java](./saving-documents-as-rtf-format/) -Impara a salvare documenti in formato RTF usando Aspose.Words per Java. Guida passo‑per‑passo con codice sorgente per una conversione efficiente. +Impara a salvare documenti in formato RTF usando Aspose.Words per Java. Guida passo‑per‑step con codice sorgente per una conversione efficiente. ### [Salvataggio di Documenti come File di Testo in Aspose.Words per Java](./saving-documents-as-text-files/) -Impara a salvare documenti come file di testo in Aspose.Words per Java. Segui la nostra guida passo‑per‑passo con esempi di codice Java. +Impara a salvare documenti come file di testo in Aspose.Words per Java. Segui la nostra guida passo‑per‑step con esempi di codice Java. ### [Determinare il Formato del Documento in Aspose.Words per Java](./determining-document-format/) Impara a rilevare i formati dei documenti in Java con Aspose.Words. Identifica DOC, DOCX e altri. Organizza i file in modo efficiente. diff --git a/words/italian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/italian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..ddca375f38 --- /dev/null +++ b/words/italian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Apri un documento Word corrotto in Java con Aspose.Words. Scopri come + impostare la modalità di recupero e ripristinare in modo affidabile i file Word + corrotti. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: it +og_description: Apri un documento Word corrotto in Java usando Aspose.Words. Questa + guida mostra come impostare la modalità di recupero e ripristinare i file Word corrotti + in modo efficiente. +og_title: Apri documento Word corrotto – Imposta la modalità di recupero in Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Apri documento Word corrotto – Imposta la modalità di recupero in Java +url: /it/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aprire un documento Word corrotto – Impostare la modalità di recupero in Java + +Hai mai provato ad aprire un documento Word corrotto e hai visto il programma bloccarsi a causa di un'eccezione? Non sei solo: quei file .docx danneggiati possono essere davvero un grattacapo. La buona notizia è che Aspose.Words per Java ti offre un controllo granulare così puoi **aprire un documento Word corrotto** senza che l'app vada in crash, e decidere se vuoi avvisi, recupero silenzioso o un rifiuto definitivo. + +In questo tutorial percorreremo l’intero processo: dalla creazione delle giuste `LoadOptions`, alla scelta del valore appropriato di **set recovery mode**, fino a confermare che il documento sia stato effettivamente caricato. Alla fine saprai **come recuperare un file Word corrotto** programmaticamente, senza necessità di copia‑incolla manuale. + +> **Ciò di cui avrai bisogno** +> * Java 8 o superiore (l’API funziona anche con Java 11) +> * Aspose.Words per Java 23.9 (o l’ultima versione) +> * Un file .docx corrotto di esempio – basta rinominare qualsiasi file valido per simulare la corruzione se non ne hai uno a disposizione + +Immergiamoci. + +## Aprire un documento Word corrotto – Panoramica passo‑passo + +Di seguito il flusso ad alto livello che implementeremo: + +1. **Creare `LoadOptions`** – questo oggetto indica ad Aspose.Words come comportarsi quando incontra problemi. +2. **Impostare la modalità di recupero** – scegliere `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` o `REJECT_CORRUPTED`. +3. **Caricare il documento** usando le opzioni configurate. +4. **Verificare** che il caricamento sia riuscito (ad es., stampare il conteggio delle pagine). + +Ogni passaggio è spiegato in dettaglio, con snippet di codice che puoi copiare‑incollare direttamente nel tuo IDE. + +## Impostare la modalità di recupero per diversi scenari + +Aspose.Words definisce tre strategie di recupero all’interno di `LoadOptions.RecoveryMode`: + +| Modalità | Comportamento | Quando usarla | +|----------|---------------|---------------| +| `RECOVER_WITH_WARNINGS` | Tenta di caricare il documento, ma segnala eventuali problemi come avvisi nella console. | Vuoi vedere *cosa* è andato storto senza interrompere l’esecuzione. | +| `RECOVER_WITHOUT_WARNINGS` | Corregge silenziosamente ciò che può e sopprime gli avvisi. | Ambienti di produzione dove i log devono rimanere puliti. | +| `REJECT_CORRUPTED` | Lancia un’eccezione non appena viene rilevata la corruzione. | Pipeline di validazione rigorose che devono fallire immediatamente. | + +Scegliere la modalità giusta è l’essenza di **set recovery mode** correttamente. Nella maggior parte delle sessioni di debug `RECOVER_WITH_WARNINGS` è la scelta ideale perché indica esattamente quali parti sono state riparate. + +## Come recuperare un file Word corrotto usando Aspose.Words + +Di seguito un **programma Java completo e eseguibile** che dimostra l’intero processo. Sentiti libero di inserirlo in un file `RecoveryModeDemo.java`, regolare il percorso e avviare l’esecuzione. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Perché ogni riga è importante + +* **`LoadOptions loadOptions = new LoadOptions();`** – senza questo oggetto Aspose.Words utilizza il recupero predefinito, che *rifiuta* i file corrotti. Creandolo ottieni il punto di aggancio per modificare tale comportamento. +* **`setRecoveryMode(...)`** – questa è la chiamata **set recovery mode** che decide se gli avvisi appaiono, rimangono nascosti o causano un’eccezione. +* **`new Document(path, loadOptions);`** – il costruttore accetta le `LoadOptions` appena configurate, così la libreria sa come trattare il file danneggiato fin dall’inizio. +* **`doc.getPageCount()`** – un rapido controllo di sanità. Se il documento si carica e restituisce il conteggio delle pagine, hai **come recuperare un file Word corrotto** con successo. +* **`doc.save(...)`** – opzionale ma utile; puoi scrivere la versione riparata su disco per un uso successivo. + +## Gestione dei casi limite più comuni + +### 1. File non trovato + +Se il percorso è errato, `Document` lancia una `FileNotFoundException`. Avvolgi il caricamento in un blocco try‑catch e registra un messaggio amichevole: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Corruzione irreparabile + +Anche con `RECOVER_WITH_WARNINGS`, alcune strutture sono oltre la possibilità di riparazione. In tal caso Aspose.Words carica comunque ciò che può, ma vedrai avvisi come “Cannot read paragraph properties”. Presta attenzione all’output della console; quegli avvisi spesso indicano sezioni mancanti che potresti dover ricostruire manualmente. + +### 3. File di grandi dimensioni e performance + +Il recupero aggiunge un piccolo overhead perché la libreria analizza il file due volte—una per rilevare i problemi, un’altra per ricostruire. Per documenti multi‑gigabyte, considera lo streaming del file o aumenta l’heap JVM (`-Xmx2g`) per evitare `OutOfMemoryError`. + +## Pro Tips – Rendere il recupero più robusto + +* **Registrare gli avvisi su file** – reindirizza `System.err` a un logger così avrai una traccia di audit di ciò che è stato corretto. +* **Validare dopo il recupero** – esegui `doc.updatePageLayout();` e poi ricontrolla il conteggio delle pagine; a volte il layout cambia dopo la correzione di sezioni rotte. +* **Automatizzare il recupero batch** – avvolgi il demo in un ciclo che processa una cartella di file corrotti, usando le stesse `LoadOptions` ogni volta. + +## Conclusione + +Ora sai esattamente **come recuperare un file Word corrotto** usando Aspose.Words per Java. Creando un’istanza di `LoadOptions`, **set recovery mode** alla strategia più adatta al tuo scenario, e caricando il documento con tali opzioni, puoi aprire in sicurezza **documenti Word corrotti** senza far crashare la tua applicazione. Il codice di esempio sopra è una soluzione completa, pronta all’uso, che stampa il conteggio delle pagine e salva anche una copia pulita. + +Qual è il prossimo passo? Prova a cambiare la modalità di recupero in `RECOVER_WITHOUT_WARNINGS` e confronta l’output della console, oppure sperimenta il caricamento di documenti criptati (dovrai fornire una password tramite + +## Tutorial correlati + +- [Aspose.Words Java: Guida completa all'elaborazione di documenti Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Come convertire Word in PDF usando Aspose.Words per Java](/words/english/java/document-converting/using-document-converting/) +- [Come confrontare due file Word con Aspose.Words per Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/italian/java/document-styling/_index.md index 9035c0f3ad..8be8b5b295 100644 --- a/words/italian/java/document-styling/_index.md +++ b/words/italian/java/document-styling/_index.md @@ -43,6 +43,8 @@ Scopri come personalizzare i temi dei documenti utilizzando Aspose.Words per Jav Scopri come applicare filigrane e configurare le pagine con Aspose.Words per Java. Una guida completa con codice sorgente. ### [Stile dell'intestazione e del piè di pagina del documento](./document-header-footer-styling/) Scopri come formattare intestazioni e piè di pagina dei documenti utilizzando Aspose.Words per Java in questa guida dettagliata. Istruzioni dettagliate e codice sorgente inclusi. +### [Impostare le impostazioni predefinite del carattere in Aspose.Words per Java – Guida completa](./set-default-font-settings-in-aspose-words-for-java-complete/) +Scopri come impostare i font predefiniti nei documenti con Aspose.Words per Java, con esempi di codice passo passo. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/italian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..b8465e14bc --- /dev/null +++ b/words/italian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Imposta le impostazioni di carattere predefinite in Aspose.Words per + Java e scopri come configurare le impostazioni dei caratteri e rilevare i caratteri + mancanti in poche righe di codice. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: it +og_description: Imposta le impostazioni predefinite dei caratteri in Aspose.Words + per Java, impara a configurare le impostazioni dei caratteri e a rilevare rapidamente + e in modo affidabile i caratteri mancanti. +og_title: Imposta le impostazioni predefinite del carattere in Aspose.Words per Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Imposta le impostazioni predefinite dei caratteri in Aspose.Words per Java + – Guida completa +url: /it/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Impostare le impostazioni predefinite dei font in Aspose.Words per Java – Guida completa + +Ti sei mai chiesto come **impostare le impostazioni predefinite dei font** quando si carica un documento Word con Aspose.Words per Java? Non sei l’unico. I glifi mancanti possono trasformare un report curato in un caos incomprensibile, e rilevare in anticipo gli avvisi di sostituzione dei font fa risparmiare ore di debug. + +In questo tutorial percorreremo un esempio conciso, end‑to‑end che **imposta le impostazioni predefinite dei font**, ti mostra come **impostare le impostazioni dei font** programmaticamente e dimostra un metodo affidabile per **rilevare i font mancanti** prima che rovinino il layout. + +--- + +## Cosa imparerai + +- Come creare un oggetto `LoadOptions` con una nuova istanza di `FontSettings`. +- Come collegare un listener di avviso che **rilevi i font mancanti** durante il caricamento del documento. +- Come caricare un file DOCX mentre il listener segnala silenziosamente eventuali sostituzioni. +- Suggerimenti per personalizzare i font di fallback e gestire i casi limite in produzione. + +Nessuna libreria aggiuntiva, nessun file di configurazione oscuro—solo Java puro e Aspose.Words. + +--- + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +1. **Aspose.Words per Java** (versione 23.10 o successiva) nel classpath. +2. Un kit di sviluppo Java 17 (o successivo) – qualsiasi JDK moderno va bene. +3. Un file DOCX che utilizzi intenzionalmente un font non installato (ad es., *“MissingFont.ttf”*). + +Se ti manca il JAR di Aspose, scaricalo dal repository Maven ufficiale: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Tutto qui—non è necessario installare font aggiuntivi per questa demo. + +--- + +## Passo 1: Creare LoadOptions e **Impostare le impostazioni predefinite dei font** + +La prima cosa di cui abbiamo bisogno è un oggetto `LoadOptions` pulito che dica ad Aspose come comportarsi quando incontra caratteri sconosciuti. Chiamando `setFontSettings(new FontSettings())` **impostiamo le impostazioni predefinite dei font** che partono da una lista di fallback vuota. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Perché è importante:** +> Quando non configuri esplicitamente i font, Aspose ricorre alla collezione predefinita del sistema, il che può nascondere problemi di font mancanti. Partendo da una nuova istanza di `FontSettings` ottieni il pieno controllo su quali font sono considerati validi. + +--- + +## Passo 2: Collegare un Listener di Avviso per **Rilevare i Font Mancanti** + +Aspose genera un oggetto `WarningInfo` per ogni sostituzione effettuata. Ascoltando `WarningType.FONT_SUBSTITUTION` possiamo **rilevare i font mancanti** non appena il documento viene analizzato. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Consiglio professionale:** Il listener viene eseguito nello stesso thread che carica il documento, quindi il costo in termini di prestazioni è praticamente nullo. Se devi raccogliere gli avvisi per un’analisi successiva, inseriscili in una `List` invece di stamparli direttamente. + +--- + +## Passo 3: Caricare il Documento Utilizzando le Opzioni Configurate + +Ora che abbiamo **impostato le impostazioni dei font** e preparato un listener, carichiamo semplicemente il file. Qualsiasi font mancante attiverà immediatamente il nostro callback. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Se il file sorgente fa riferimento a un font non installato, vedrai un output simile a: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Quella riga ti indica esattamente quale font era mancante e quale fallback è stato usato—perfetto per logging o feedback all’utente. + +--- + +## Passo 4: Continuare con l’Elaborazione Normale (Opzionale) + +A questo punto il documento è completamente caricato e puoi procedere con qualsiasi manipolazione desideri—modifica, conversione in PDF o estrazione del testo. Il listener di avviso ha già svolto il suo compito, quindi non servono controlli aggiuntivi. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **E se vuoi un fallback personalizzato?** +> Invece di lasciare `FontSettings` vuoto, puoi aggiungere font specifici: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Ora qualsiasi carattere mancante verrà sostituito con *Times New Roman*—una scelta affidabile per la maggior parte dei documenti occidentali. + +--- + +## Panoramica Visiva + +![Diagramma che mostra come impostare le impostazioni predefinite dei font in Aspose.Words per Java](image.png "Diagramma del flusso di impostazione delle impostazioni predefinite dei font") + +*Testo alternativo: diagramma del flusso di impostazione delle impostazioni predefinite dei font in Aspose.Words per Java.* + +Il diagramma illustra il flusso dall’inizializzazione di `LoadOptions` (dove **impostiamo le impostazioni predefinite dei font**) al collegamento del listener di avviso (per **rilevare i font mancanti**) e infine al caricamento del documento. + +--- + +## Errori Comuni & Come Evitarli + +| Problema | Perché Accade | Soluzione | +|----------|----------------|-----------| +| **Dimenticato di chiamare `setFontSettings`** | Aspose usa i valori predefiniti del sistema, nascondendo i font mancanti. | Crea sempre una nuova istanza di `FontSettings` e assegnala a `LoadOptions`. | +| **Listener non attivato** | Listener aggiunto dopo il caricamento del documento. | Aggiungi il listener di avviso *prima* di chiamare `new Document(...)`. | +| **Errore di battitura nel percorso che porta a `FileNotFoundException`** | Il percorso hard‑coded non corrisponde alla sensibilità al maiuscolo/minuscolo del OS. | Usa `Paths.get("...").toAbsolutePath()` o configura un percorso relativo dalla radice del progetto. | +| **Molti font mancanti sommergono i log** | Documenti grandi possono generare decine di avvisi. | Filtra i duplicati o aggrega i messaggi in un `Set` prima di stamparli. | + +--- + +## Estendere la Soluzione + +Se devi **impostare le impostazioni dei font** per un’intera applicazione, considera la creazione di un singleton `FontSettings` e il suo riutilizzo in tutti i `LoadOptions`. In questo modo mantieni una strategia di fallback coerente ed eviti la creazione ripetuta di oggetti. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Ora qualsiasi parte del tuo codice può semplicemente chiamare `FontConfig.getLoadOptions()` e beneficiare immediatamente della stessa logica di **impostare le impostazioni predefinite dei font**. + +--- + +## Conclusione + +Abbiamo appena coperto tutto ciò che serve per **impostare le impostazioni predefinite dei font** in Aspose.Words per Java, **impostare le impostazioni dei font** programmaticamente e **rilevare i font mancanti** prima che corrompano il risultato. L’esempio completo e funzionante è nei frammenti di codice sopra, e puoi incollarlo direttamente nel tuo IDE per vedere gli avvisi in azione. + +Passi successivi? Prova a cambiare il font di fallback, sperimenta con formati di documento diversi (DOC, RTF, HTML) o integra il raccoglitore di avvisi in una dashboard di monitoraggio. Più giochi con `FontSettings`, più avrai la certezza che i documenti generati appaiano esattamente come previsto—senza sorprese, senza glifi rotti. + +Hai domande o uno scenario di sostituzione dei font complesso? Lascia un commento qui sotto, e buon coding! + +## Tutorial Correlati + +- [Imposta impostazioni di fallback dei font](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Imposta impostazioni di fallback dei font](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Imposta impostazioni di fallback dei font](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/java/images-shapes/_index.md b/words/italian/java/images-shapes/_index.md index 28d6660935..78f1ca6397 100644 --- a/words/italian/java/images-shapes/_index.md +++ b/words/italian/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Scopri come generare miniature di alta qualità e bitmap di dimensioni personali ### [Crea documento Word Java – Aggiungi forma rettangolare con effetto ombra](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Impara a inserire una forma rettangolare con ombra in un documento Word usando Aspose.Words per Java. +### [Crea forma rettangolare in documento Word Java – Guida completa passo‑passo](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Scopri come aggiungere una forma rettangolare a un documento Word usando Aspose.Words per Java, con istruzioni dettagliate passo dopo passo. + ## Risorse aggiuntive - [Documentazione di Aspose.Words per Java](https://reference.aspose.com/words/java/) diff --git a/words/italian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/italian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..772888757d --- /dev/null +++ b/words/italian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-05-26 +description: Crea una forma rettangolare in un documento Word Java e applica l'effetto + ombra. Impara come aggiungere l'ombra alla forma, impostare la distanza dell'ombra + e salvare il file. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: it +og_description: Crea una forma rettangolare in un documento Word Java, applica l'effetto + ombra, aggiungi l'ombra alla forma e imposta la distanza dell'ombra con Aspose.Words. +og_title: Crea una forma rettangolare in un documento Word con Java – Guida completa +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Crea una forma rettangolare in un documento Word Java – Guida completa passo + passo +url: /it/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea forma rettangolare in un documento Word Java – Guida completa passo‑passo + +Hai mai avuto bisogno di **create rectangle shape** in un documento Word Java ma non sapevi da dove cominciare? Non sei solo—molti sviluppatori incontrano questo ostacolo quando generano report o fatture in modo programmatico. In questo tutorial ti mostreremo passo passo come **create rectangle shape**, applicare un'ombra curata e regolare finemente la distanza dell'ombra affinché il risultato abbia un aspetto professionale. + +Useremo Aspose.Words for Java, una libreria robusta che consente di manipolare file Word senza necessità di installare Microsoft Office. Alla fine di questa guida sarai in grado di creare progetti **create word document java** che **add shape shadow**, **apply shadow effect** e **set shadow distance** con poche righe di codice. + +--- + +## Cosa costruirai + +- Un nuovo file `.docx` contenente un rettangolo ciano. +- Un'ombra realistica che è sfocata, inclinata e parzialmente trasparente. +- Controllo completo sulla distanza dell'ombra dalla forma. +- Una classe Java pronta da eseguire che puoi inserire in qualsiasi progetto Maven o Gradle. + +Nessuno strumento esterno, nessun passaggio manuale dell'interfaccia—solo puro codice. + +--- + +## Prerequisiti + +- Java 8 o superiore (il codice funziona su Java 11, Java 17, ecc.). +- Libreria Aspose.Words for Java (disponibile tramite Maven Central). +- Un IDE o editor di testo a tua scelta (IntelliJ IDEA, Eclipse, VS Code…). +- Familiarità di base con la sintassi Java. + +Se non hai mai aggiunto una dipendenza Maven prima, ecco lo snippet rapido: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Ora, immergiamoci. + +--- + +## Step 1: Create Rectangle Shape in a Word Document + +La prima cosa di cui abbiamo bisogno è un documento vuoto e un `DocumentBuilder`. Pensa al builder come a una penna che scrive nel documento. Una volta che lo abbiamo, possiamo **create rectangle shape** con una singola chiamata di metodo. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Perché è importante:** Il metodo `insertShape` non solo crea la geometria ma aggiunge anche la forma alla collezione interna del documento, così puoi subito iniziare a stilizzarla. + +--- + +## Step 2: Apply Shadow Effect to the Shape + +Ora che il rettangolo è sulla pagina, **apply shadow effect**. Le ombre danno profondità, facendo sembrare la forma sollevata dalla pagina—un miglioramento UI sottile che può aumentare la leggibilità nei report. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Consiglio professionale:** Una sfocatura di `5.0` appare naturale per la maggior parte dei documenti visualizzati su schermo. Se stampi, potresti voler un valore leggermente più basso per evitare un aspetto sfocato. + +--- + +## Step 3: Set Shadow Distance – Fine‑Tuning Placement + +Le ombre non riguardano solo la sfocatura; hanno anche bisogno del giusto offset. È qui che **set shadow distance**. Una distanza di `7.0` punti crea un offset moderato, visibile ma non eccessivo. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **E se ti serve un offset più grande?** Aumenta il valore; diminuiscilo per un aspetto più stretto. Ricorda, la distanza lavora insieme all'angolo per posizionare correttamente l'ombra. + +--- + +## Step 4: Save the Document – Persist Your Work + +Infine, scriviamo il documento su disco. Cambia il percorso dove desideri che il file venga salvato. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Eseguendo la classe si crea un file `shadow.docx` che, quando aperto in Microsoft Word o LibreOffice, mostra un rettangolo ciano con un'ombra grigia morbida inclinata a 45° e offset di 7 punti. + +--- + +## Full Working Example + +Di seguito trovi il codice completo, pronto per copia‑incolla. Include tutti gli import, i commenti e la chiamata finale `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Output previsto:** Apri `shadow.docx` → vedrai un rettangolo ciano centrato nella prima pagina, che proietta una leggera ombra grigia leggermente spostata verso il basso‑destra. La sfocatura e la trasparenza dell'ombra la fanno apparire come illuminazione naturale. + +--- + +## Common Questions & Edge Cases + +### “Can I use a different shape?” + +Assolutamente. Sostituisci `ShapeType.RECTANGLE` con `ShapeType.OVAL`, `ShapeType.LINE` o qualsiasi altro enum supportato. Il resto del codice dell'ombra rimane invariato. + +### “What if I need multiple shadows?” + +Aspose.Words supporta solo una singola ombra per forma. Per simulare più ombre, duplica la forma, offsetta ogni copia e regola la trasparenza. + +### “Is the shadow visible in LibreOffice?” + +Sì—Aspose.Words scrive OOXML standard, che LibreOffice interpreta correttamente. L'ombra potrebbe apparire leggermente diversa a causa dei motori di rendering, ma l'effetto rimane. + +### “How do I change the shadow color to match my brand?” + +Basta sostituire `java.awt.Color.GRAY` con qualsiasi `java.awt.Color` preferisci, ad esempio `new java.awt.Color(0, 120, 215)` per un blu aziendale. + +--- + +## Image Illustration + +![crea forma rettangolare in documento Word Java](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illustrazione che mostra un rettangolo ciano con un'ombra grigia a caduta in un documento Word. + +--- + +## Recap & Next Steps + +Abbiamo coperto come **create rectangle shape**, **apply shadow effect**, **add shape shadow** e **set shadow distance** usando Aspose.Words for Java. Il codice è autonomo, funziona su qualsiasi JDK moderno e produce un file `.docx` rifinito pronto per la distribuzione. + +Vuoi andare oltre? Prova: + +- Aggiungere testo all'interno del rettangolo con `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Creare una tabella di forme per costruire un diagramma. +- Esportare il documento in PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Ognuno di questi si basa sugli stessi fondamenti appena esplorati, così ti sentirai a tuo agio nell'estendere l'esempio. + +--- + +## Final Thoughts + +Padroneggiare le attività **create word document java** come la modellazione e l'ombreggiatura ti dà un grande vantaggio nell'automazione di report, contratti o materiale di marketing. L'approccio mostrato qui è pulito, manutenibile e—soprattutto—facile da modificare per qualsiasi stile visivo tu necessiti. + +Prova il codice, regola la sfocatura, l'angolo e la distanza, e guarda i tuoi documenti trasformarsi da banali a raffinati. Se incontri un problema, lascia un commento qui sotto; sarò felice di aiutarti. + +Buona programmazione! + +## Related Tutorials + +- [Crea documento Word Java – Aggiungi forma rettangolare con effetto ombra](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Come creare campi modulo e aggiungere contenuto usando DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Crea PDF da Word con generazione di codici a barre – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/japanese/java/document-conversion-and-export/_index.md index 8a52aceb19..5b38069d21 100644 --- a/words/japanese/java/document-conversion-and-export/_index.md +++ b/words/japanese/java/document-conversion-and-export/_index.md @@ -80,25 +80,29 @@ Aspose.Words for Java で文書内の数式の力を引き出します。Office ### [Aspose.Words for Java でドキュメントシェイプを使用する](./using-document-shapes/) ### [Aspose.Words for Java でドキュメントにウォーターマークを使用する](./using-watermarks-to-documents/) -Aspose.Words for Java で文書にウォーターマークを追加する方法を学びます。テキストや画像のウォーターマークをカスタマイズして、プロフェッショナルな文書を作成します。 ### [Aspose.Words for Java で DOCX を PDF に変換](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) -Aspose.Words for Java を使用して DOCX ファイルを PDF に変換する手順をステップバイステップで解説します。 ### [DOCX からアクセシブル PDF を作成 – 完全ガイド](./create-accessible-pdf-from-docx-complete-guide/) -DOCX ファイルをアクセシブルな PDF に変換する手順とベストプラクティスをステップバイステップで解説します。 + +### [Aspose.Words for Java でアクセシブル PDF を作成 – 完全タグ付けガイド](./create-accessible-pdf-in-java-full-tagging-guide/) +Aspose.Words for Java を使用して、アクセシブル PDF を作成し、完全なタグ付けを実装する方法をステップバイステップで解説します。 ### [Aspose.Words for Java でテーブルとテーブルスタイルの書式設定](./formatting-tables-and-table-styles/) -Aspose.Words for Java でテーブルの書式設定とテーブルスタイルの適用方法を学びます。効果的なテーブル書式設定のためのソースコード付きステップバイステップガイドを探ります。Aspose.Words で文書レイアウトを強化します。 ### [docx を markdown に変換 – Aspose.Words で数式を LaTeX にエクスポート](./convert-docx-to-markdown-export-math-equations-to-latex-with/) -Aspose.Words を使用して DOCX 文書を Markdown に変換し、数式を LaTeX 形式でエクスポートする方法をステップバイステップで解説します。 + +### [Word を markdown に保存 – Java で数式を LaTeX にエクスポート](./save-word-as-markdown-export-math-to-latex-with-java/) ### [DOCX を変換する際に Markdown に画像を埋め込む方法](./how-to-embed-images-in-markdown-when-converting-docx/) -Aspose.Words for Java を使用して DOCX を Markdown に変換する際、画像を正しく埋め込む手順をステップバイステップで解説します。 + +### [DOCX を Markdown に変換する際に画像を Base64 として埋め込む](./embed-images-as-base64-when-converting-docx-to-markdown/) ### [ドキュメントをTXTとして保存 – Word数式エクスポートのクイックガイド](./save-document-as-txt-quick-guide-to-exporting-word-math/) -Aspose.Words for Java を使用して、Word 文書を TXT 形式で保存し、数式をエクスポートする方法をステップバイステップで解説します。 + +### [Aspose.Words Java で文書を PDF として保存 – 完全アクセシビリティガイド](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) + +### [Aspose.Words for Java で docx を txt にエクスポート – 完全プログラミングガイド](./export-docx-to-txt-with-java-complete-programming-guide/) --- diff --git a/words/japanese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/japanese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..f8d841fb39 --- /dev/null +++ b/words/japanese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,223 @@ +--- +category: general +date: 2026-05-26 +description: Javaでステップバイステップのコードを使用してアクセシブルなPDFを作成します。PDFをアクセシビリティ対応にタグ付けする方法と、PdfSaveOptionsを使ってPDFタグ付けを有効にする方法を学びます。 +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: ja +og_description: ステップバイステップのコードでJavaでアクセシブルなPDFを作成します。アクセシビリティ向けにPDFにタグ付けする方法と、PdfSaveOptionsを使用してPDFタグ付けを有効にする方法を学びましょう。 +og_title: JavaでアクセシブルなPDFを作成する – 完全タグ付けガイド +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: JavaでアクセシブルPDFを作成する – 完全タグ付けガイド +url: /ja/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# JavaでアクセシブルなPDFを作成 – 完全タグ付けガイド + +Javaコードから直接 **アクセシブルなPDF** を作成する方法を考えたことがありますか? あなたは一人ではありません。多くの開発者がスクリーンリーダーに依存するユーザーに対応する必要があり、普通のPDFとアクセシブルなPDFの違いは大きいです。このチュートリアルでは **PDFをアクセシビリティ向けにタグ付けする方法** を解説し、Aspose PDF for Java を使って **タグ付きPDFを作成する方法** を示し、**PDFにアクセシビリティタグを追加する** 正確な手順を明らかにします。 + +また **PDFタグ付けを有効にする** ベストプラクティス、一般的な落とし穴、そしてすぐにプロジェクトに組み込める完全な実行可能サンプルもカバーします。曖昧な参照は一切なく、具体的なコード、解説、そしてタグを確認できるAdobe Acrobatで開く最終ファイルを提供します。 + +## 学べること + +- PDFタグ付けとアクセシビリティコンプライアンスの背景 +- 前提条件とライブラリ設定(Aspose PDF for Java 23.10 以降) +- **アクセシブルなPDF** をゼロから作成する手順 +- 基本的な `setTagDocumentStructure` 呼び出しを超えて **PDFにアクセシビリティタグを追加する** 方法 +- 出力のテスト方法と一般的な問題のトラブルシューティング + +このガイドを終える頃には、WCAG 2.1 AA 基準をクリアし、見た目もプロフェッショナルなPDFを生成できるようになります。 + +--- + +## 前提条件 + +| 要件 | 理由 | +|------|------| +| **Java 8+** | 最新の言語機能と Unicode の取り扱いが向上します。 | +| **Aspose PDF for Java** (v23.10 以上) | `PdfSaveOptions` クラスとタグ付けサポートを提供します。 | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code など) | コンパイルとデバッグが容易になります。 | +| **Write permission** to a folder where the PDF will be saved | `doc.save` 呼び出しには書き込み可能なパスが必要です。 | + +まだ Aspose PDF をプロジェクトに追加していない場合は、次の Maven 依存関係を `pom.xml` に追加してください。 + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** 最新バージョンを使用してください。新しいリリースはタグ付け精度を向上させ、言語固有のアクセシビリティ機能を追加します。 + +--- + +## 手順 1: ドキュメントの骨組みを設定 + +まず、新しい `Document` オブジェクトを作成します。これは、後でアクセシビリティ用のタグを保持する空白のキャンバスと考えてください。 + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Why this matters:** コンテンツが無ければタグ付けするものがありません。簡単な `TextFragment` を追加するだけで、タグ付けエンジンが処理できる対象ができ、後で構造タグを有効にすると自動的に `

`(段落)タグが生成されます。 + +## 手順 2: PDF保存オプションを作成(タグ付けの核心) + +次に、Aspose PDF に論理構造ツリーをファイルに埋め込むよう指示するオプションを準備します。 + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +`setTagDocumentStructure(true)` の呼び出しは **PDFタグ付けを有効にする** スイッチです。`true` に設定すると、ライブラリは視覚的レイアウトを鏡像するタグツリーを構築し、支援技術が PDF を読み取れるようになります。 + +> **Note:** これは **how to create tagged pdf** の最もシンプルな方法です。言語やカスタムタグなど、より細かい制御が必要な場合は `pdfOptions.setTagLanguage("en-US")` や `pdfOptions.setTagStructureTreeRoot(...)` を検討してください。 + +## 手順 3: アクセシブルなPDFを保存 + +最後に、先ほど設定したオプションを使ってドキュメントをディスクに書き出します。 + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +`doc.save` が完了すると、`output` フォルダーに `accessible.pdf` が生成されます。Adobe Acrobat で開き、**File → Properties → Description → Tags** を確認すると、タグツリーが正しく構築されているはずです。 + +## PDFをアクセシビリティ向けにタグ付けする方法 – 基本を超えて + +上記の 3 ステップスニペットだけでも **PDFにアクセシビリティタグを追加する** ことはできますが、実務の文書ではもう少し手を加える必要があります。以下の拡張をぜひ取り入れてみてください。 + +### 1. ドキュメント言語を設定 + +スクリーンリーダーは言語属性を使ってテキストを正しく発音します。 + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. タイトルとサブジェクトを提供 + +メタデータは、ユーザーがファイルを開く前に支援ツールがコンテキストを提供するのに役立ちます。 + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. 画像に代替テキストをタグ付け + +画像を埋め込む場合、`alt` 説明が必要です。 + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. テーブルヘッダーをマーク + +テーブルはヘッダー行をマークしないと、読者を混乱させがちです。 + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +これらの追加手順により、PDFは単に *技術的に* タグ付けされるだけでなく、さまざまなユーザーにとって真に **アクセシブル** なものになります。 + +## PDFタグ付けを有効にする際の一般的な落とし穴 + +| 症状 | 考えられる原因 | 対策 | +|------|----------------|------| +| Acrobat でタグが表示されない | `setTagDocumentStructure` が `false` のまま | `pdfOptions.setTagDocumentStructure(true)` を呼び出しているか確認してください。 | +| 読み順が正しくない | 明示的なタグがない複雑レイアウト | `pdfOptions.setTagStructureTreeRoot(...)` でカスタム順序を定義してください。 | +| 画像が「image」だけで説明がない | 代替テキストが設定されていない | `image.getAlternativeText().setValue("...")` を呼び出してください。 | +| 言語が認識されない | `setTagLanguage` が省略またはロケールが間違っている | BCP‑47 言語コード(例: `en-US`, `fr-FR`)を指定してください。 | + +これらのポイントを把握しておけば、後からのデバッグにかかる時間を大幅に削減できます。 + +## 結果の検証 – 期待されること + +プログラムを実行したら、Adobe Acrobat Reader で `output/accessible.pdf` を開きます。 + +1. **Tags panel** (`View → Show/Hide → Navigation Panes → Tags`) に `/Document → /Part → /Sect → /Para` のような階層が表示されるはずです。 +2. **Reading order** が視覚的な流れ(テキスト → 画像)に従っていることを確認してください。 +3. **Screen reader**(NVDA、VoiceOver など)は「Hello, accessible PDF!」と読み上げ、単に「Page 1」だけを読むことはありません。 + +上記の項目が欠けている場合は、特に `setTagDocumentStructure` の呼び出しを再確認してください。 + +## 完全動作例(コピー&ペースト可能) + + + +## 関連チュートリアル + +- [WordからアクセシブルなPDFを作成 – PDF/UAに変換](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [DOCXからアクセシブルなPDFを作成 – 完全ガイド](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Aspose.Words for JavaでドキュメントをPDFとして保存する方法](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/japanese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..bdcc0bcc29 --- /dev/null +++ b/words/japanese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java を使用して docx を markdown に変換する際に、画像を base64 で埋め込みます。Word + を markdown に変換する方法、Word を markdown として保存する方法、画像の処理方法を学びましょう。 +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: ja +og_description: Aspose.Words for Java を使用して docx を markdown に変換する際に、画像を base64 で埋め込みます。Word + を markdown に変換し、markdown として保存する完全ガイド。 +og_title: DOCXをMarkdownに変換する際に画像をBase64で埋め込む +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: DOCX を Markdown に変換する際に画像を Base64 で埋め込む +url: /ja/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX を Markdown に変換するときに画像を Base64 で埋め込む + +**docx を markdown に変換**しながら **画像を Base64 で埋め込む** 方法を知りたくありませんか?同じ悩みを抱える開発者は多く、画像を別ファイルとして管理せずにインラインで保持したいと常に質問されています。良いニュースは、Aspose.Words for Java を使えば簡単に実現できることです。Word 文書を Markdown に変換し、すべての画像を自動的に Base64 文字列として埋め込むことができます。 + +このチュートリアルでは、画像を含む `.docx` の読み込みから、画像埋め込みの重い処理を行う `MarkdownSaveOptions` コールバックの設定、そして最終的にクリーンな `.md` ファイルとして保存するまでの全工程を解説します。最後まで読めば、**word を markdown に変換**し、**画像を Base64 に変換**し、**word を markdown として保存**する方法が完全に理解でき、余計な画像フォルダーが残らないことが分かります。外部ツールや手動の後処理は不要で、どのプロジェクトにもそのまま組み込める純粋な Java コードだけです。 + +## 必要なもの + +- **Java 17**(または最近の JDK) – コードはラムダ構文を使用していますが、古いバージョンに合わせて書き換えることも可能です。 +- **Aspose.Words for Java** ライブラリ(2026 年時点の最新バージョン)。Maven 依存関係または JAR をクラスパスに追加してください。 +- 画像が少なくとも 1 つ含まれたサンプル **DOCX** ファイル。 +- IDE もしくはシンプルなテキストエディタ – Visual Studio Code、IntelliJ IDEA、あるいは `vim` でも構いません。 + +これらが揃っていれば、さっそく始めましょう。 + +## 手順 1: Word 文書をロードする + +まず、ソースファイルを指す `Document` インスタンスを作成します。これは **docx を markdown に変換**する場合でも、単にファイルを読み込むだけの場合でも同じ手順です。 + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **ポイント:** `Document` オブジェクトはすべての Aspose 操作のエントリーポイントです。画像、テーブル、スタイルなど Word の全構造を保持しているため、後述のコールバックで各リソースを検査できます。 + +## 手順 2: MarkdownSaveOptions を作成し、リソース保存コールバックを登録する + +魔法は `MarkdownSaveOptions` にあります。`IResourceSavingCallback` を添付することで、画像などの外部リソースの書き出し方法を制御できます。 + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: `setSaveToMemory(true)` を使う理由 + +`saveToMemory` を true に設定すると、Aspose は画像バイトをファイルではなくメモリストリームに書き込みます。Markdown エクスポーターはそのストリームを Base64 文字列に変換し、Markdown の画像タグに直接埋め込みます。 + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +これが **画像を Base64 で埋め込む** の核心です。 + +## 手順 3: 文書を Markdown として保存する + +コールバックが設定されたので、最後のステップは単に `save` を呼び出すだけです。ここで実際に **word を markdown に変換**し、コールバックのおかげで **画像を Base64 に変換** しています。 + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **結果:** `out.md` にはすべての画像が `data:` URI として表現された Markdown テキストが含まれます。ディスク上に余分な画像ファイルは生成されないため、フォルダーがすっきり保たれます。 + +## 手順 4: 出力結果の確認とよくある落とし穴 + +生成された `out.md` を任意の Markdown ビューア(VS Code、GitHub、静的サイトジェネレータなど)で開きます。以下のように表示されるはずです。 + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### トラブルシューティングチェックリスト + +| 問題 | 想定原因 | 対策 | +|------|----------|------| +| 画像が壊れたリンクとして表示される | `setSaveToMemory` が設定されていない | コールバック内で `args.setSaveToMemory(true);` を必ず呼び出す | +| Base64 文字列が途中で切れる | 出力ファイルのエンコーディング不一致 | Markdown を UTF‑8(Aspose のデフォルト)で保存する | +| 予期しないファイル名が付く | `setKeepResourceOriginalName(true)` が有効 | `false` のままにしてカスタム命名ロジックを使用する | + +## 手順 5: 応用バリエーション(任意) + +### 特定の画像だけを変換する + +例えば 100 KB 以上の画像だけを埋め込みたい場合は、サイズチェックを追加します。 + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### 別の画像フォーマットを使用する + +`ResourceSavingArgs` から取得した生バイトを利用して、JPEG を PNG に再エンコードして埋め込むことも可能です。Markdown の利用先が PNG を好む場合に便利です。 + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +これらの調整により、**docx を markdown に変換**するときの **画像を Base64 で埋め込む** 手法がいかに柔軟かが分かります。 + +## 結論 + +Aspose.Words for Java を使って **docx を markdown に変換**しながら **画像を Base64 で埋め込む** 方法を学びました。シンプルな `IResourceSavingCallback` を設定するだけで、ライブラリがすべての重い処理を担い、**word を markdown に変換**し、**画像を Base64 に変換**し、最終的に **word を markdown として保存** します。 + +ぜひ色々試してみてください。画像フィルタリングルールを変えたり、HTML 出力に切り替えたり、静的サイトジェネレータと組み合わせたりすると面白いでしょう。同じパターンは HTML や EPUB など他のフォーマットでも使えるので、インラインリソースが必要な場所ならどこでもコールバックを再利用できます。 + +**次のステップ:** +- `HtmlSaveOptions` を調べて、HTML に Base64 画像を埋め込む方法を試す。 +- CI パイプラインに組み込んでドキュメント生成を自動化する。 +- さらに細かい制御が必要な場合は Aspose の `DocumentVisitor` を検討する。 + +コーディングを楽しみながら、クリーンで自己完結型の Markdown ファイルを手に入れましょう! + +## 関連チュートリアル + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/japanese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..bbd1ee71a0 --- /dev/null +++ b/words/japanese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,235 @@ +--- +category: general +date: 2026-05-26 +description: Java と Aspose.Words を使用して docx を txt にエクスポートします。docx をテキストに変換し、Unicode + を保持し、数ステップで Word を txt にエクスポートする方法を学びましょう。 +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: ja +og_description: Javaでdocxをtxtにエクスポートする。このチュートリアルでは、docxをテキストに変換し、プレーンテキストのUnicodeを保持しながら、Wordを効率的にtxtとしてエクスポートする方法を示します。 +og_title: Javaでdocxをtxtにエクスポートする完全ガイド +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Javaでdocxをtxtにエクスポート – 完全プログラミングガイド +url: /ja/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Javaでdocxをtxtにエクスポート – 完全プログラミングガイド + +特別な文字が失われることを心配しながら **export docx to txt** が必要になったことはありませんか? あなただけではありません。Word ドキュメントをプレーンテキストファイルに変換すると、Unicode 記号やテーブル、さらには簡単な書式さえも魔法のように消えてしまうことがあります。 + +このガイドでは、Aspose.Words for Java を使用して **export docx to txt** を確実に行う方法を順を追って説明します。Unicode のすべてのグリフを保持し、テーブルのレイアウトも読みやすく保ちます。最後まで読むと、**convert docx to text**、**convert word to text**、さらには **export word as txt** を問題なく実行できるようになります。 + +## このチュートリアルでカバーする内容 + +* Java プロジェクトへの Aspose.Words の設定 +* DOCX ファイルを読み込み、プレーンテキスト出力の準備 +* `TxtSaveOptions` を使った **plain text unicode** の設定 +* 結果の `.txt` ファイルでテーブルを可読に保つオプション +* ファイルの保存と出力の検証 + +外部スクリプトや不思議なコマンドラインツールは不要です。Maven でも Gradle でも使える純粋な Java コードだけです。 + +> **なぜ重要か?** プレーンテキストファイルは軽量で、バージョン管理に適し、検索インデックスや下流の処理パイプラインに最適です。Word ファイルを `cat` しても文字化けしてしまう経験があるなら、このチュートリアルがその問題を解決します。 + +--- + +## Export docx to txt – 概要 + +コードに入る前に用語を整理しましょう。**Export docx to txt** とは、Microsoft Word の `.docx` パッケージからテキストコンテンツだけを取り出し、シンプルな `.txt` ファイルに書き出すことです。PDF 変換とは異なり、テキストエクスポートはスタイルを除去しますが、改行や段落マーカー、そして正しく設定すれば絵文字やアクセント付き文字、アジア文字などの Unicode 文字も保持できます。 + +Aspose.Words は Word ファイル形式を抽象化し、エンコーディングやテーブル処理などを指定できる `TxtSaveOptions` クラスを提供してくれるので、非常に楽です。 + +### 前提条件 + +* Java 11 以上(API は Java 8+ でも動作しますが、ここでは最新の JDK を前提とします) +* Aspose.Words for Java の JAR(Maven Central から取得可能) +* 多様な Unicode 文字を含むサンプル `unicode.docx`(例: 「こんにちは」、😊、シンプルなテーブル) + +これらが揃ったら、さっそく始めましょう。 + +--- + +## Step 1: Load the DOCX File (Convert docx to text) + +最初に行うべきことは、ソースドキュメントをメモリに読み込むことです。ここから **convert docx to text** のプロセスが正式に始まります。 + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Why this matters:* `Document` は Aspose.Words が Word ファイルを表すクラスです。これをロードすることで、段落、テーブル、隠し要素まですべてにアクセスできます。ファイルが見つからない場合は Aspose が明確な `FileNotFoundException` を投げるので、すぐに原因が分かります。 + +--- + +## Step 2: Configure TxtSaveOptions for Unicode (Plain text unicode) + +プレーンテキストファイルはバイトストリームに過ぎないため、使用する文字セットを Java に指示する必要があります。UTF‑8 は **plain text unicode** の事実上の標準で、すべての Unicode コードポイントをエンコードできます。 + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **プロのコツ:** `setEncoding` 呼び出しを省略すると、Aspose はプラットフォームのデフォルト文字セットを使用します。多くの Windows マシンでは Windows‑1252 になるため、“ß” や “—” といった文字が黙って失われます。 + +--- + +## Step 3: Preserve Table Layout (Optional, but handy for readability) + +**export word as txt** を行うと、テーブルは通常 1 行のテキストに平坦化され、読めなくなります。Aspose.Words には視覚的構造を保持するシンプルなフラグがあります。 + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*When to use it:* ソース DOCX に請求書、スケジュール、またはグリッド状データが含まれる場合、`PreserveTableLayout` を有効にするとタブと改行が挿入され、結果のファイルがテーブルに似た形になります。不要であればこの行を省略して、よりコンパクトな出力にできます。 + +--- + +## Step 4: Save the Document as Plain‑Text (Export word as txt) + +これで重い処理は完了です。バイトを書き出すだけです。 + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +プログラムを実行すると、同じフォルダーに `plain.txt` が生成されます。任意のテキストエディタ(Notepad++、VS Code、端末の `cat` など)で開くと次のようになります: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +日本語の挨拶とスマイリーが無事に残っており、`PreserveTableLayout` によってテーブルの列も保持されています。これがクリーンな **export docx to txt** の本質です。 + +--- + +## Step 5: Verify the Output (Convert word to text sanity check) + +簡単なサニティチェックで、データが黙って失われていないか確認できます。**convert word to text** が正しく行われたかを確かめる方法をいくつか紹介します: + +1. **チェックサム比較** – `.txt` ファイルをラウンドトリップ変換(txt → docx → txt)前後で SHA‑256 ハッシュを計算し、安定性を確認。 +2. **Unicode マーカー検索** – `grep` や IDE のファイル内検索で “😊” などの文字を探す。 +3. **複数エディタで開く** – 古い Windows Notepad は BOM なしの UTF‑8 を誤解釈することがあります。VS Code で開けばエンコーディングが正しいか確認できます。 + +これらのチェックで問題が出た場合は、`saveOptions.setEncoding(StandardCharsets.UTF_8)` が設定されているか、元の DOCX に本当に Unicode テキストが含まれているかを再確認してください。 + +--- + +## Common Pitfalls & How to Avoid Them + +| 問題 | 発生理由 | 対策 | +|------|----------|------| +| **文字が欠落** | デフォルトのシステム文字セット(例: Windows‑1252)が非ASCII文字を削除します。 | `saveOptions.setEncoding` で明示的に UTF‑8 を設定してください。 | +| **テーブルが1行になる** | `PreserveTableLayout` がデフォルトの false のままです。 | `saveOptions.setPreserveTableLayout(true)` を呼び出してください。 | +| **ファイルが見つからない** | パスが間違っているか、読み取り権限がありません。 | 絶対パスを使用するか、`Paths.get(...)` と適切な例外処理を行ってください。 | +| **大きなドキュメントでのパフォーマンス低下** | ドキュメント全体をメモリに読み込んでいるため。 | 特定のセクションだけが必要な場合は、`DocumentBuilder` を使用してドキュメントをチャンクごとにストリームしてください。 | + +--- + +## Bonus: Exporting Multiple DOCX Files in a Batch + +フォルダー全体の **convert docx to text** が必要な場合は、ロジックをループで包みます: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +このスニペットはディレクトリ内のすべてのファイルに対して **export docx to txt** を実行し、手作業の時間を大幅に削減します。 + +--- + +## Conclusion + +Java で **export docx to txt** を行い、すべての Unicode 文字を保持し、テーブルを可読に保ち、プロセスを再現可能にする方法を学びました。`TxtSaveOptions` を UTF‑8 に設定し、必要に応じてテーブルレイアウトを保持すれば、**convert docx to text**、**convert word to text**、**export word as txt** をどんな下流ワークフローでも信頼して使用できます。 + +次のチャレンジは? Markdown(`.md`)や CSV へのエクスポート、あるいは Aspose.Words の PDF 変換機能を試してみてください。明示的なエンコーディング、レイアウト保持、徹底した検証という原則は、すべての形式で共通です。 + +Happy coding, and may your text files always stay Unicode‑rich! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + +## Related Tutorials + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/japanese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..11499a2912 --- /dev/null +++ b/words/japanese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words Java を使用して文書を PDF として保存し、PDF にアクセシビリティを追加します。docx を PDF + に変換し、水平線にタグ付けし、PDF/UA‑2 準拠を確保する方法を学びましょう。 +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: ja +og_description: Aspose.Words Java を使用して文書を PDF として保存し、PDF にアクセシビリティを追加します。docx を PDF + に変換し、PDF/UA‑2 準拠のために水平罫線にタグ付けするステップバイステップガイド。 +og_title: Aspose.Words Javaで文書をPDFとして保存 – アクセシビリティを簡単に +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Aspose.Words Javaで文書をPDFとして保存 – 完全アクセシビリティガイド +url: /ja/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words Java でドキュメントを PDF として保存 – 完全アクセシビリティガイド + +スクリーンリーダーに対応した状態で **save document as PDF** する方法を考えたことはありますか? あなただけではありません。多くの開発者が *convert docx to pdf* を行いながら、特にソースに正しくタグ付けされる必要がある水平線が含まれている場合に、PDF/UA‑2 標準を満たす必要があります。このチュートリアルでは、Aspose.Words for Java を使用して **save document as PDF** する正確な手順を解説し、PDF に自動的に **add accessibility to PDF** を適用し、すべての水平線が **tagged** されてアーティファクトになることを確認します。 + +クリーンな Java プロジェクトから開始し、水平線を含む DOCX を読み込み、PDF/UA‑2 準拠のために PDF 保存オプションを設定し、最終的に完全にアクセシブルな PDF を書き出します。最後まで実行すれば、**save document as pdf** がアクセシビリティチェックに合格することを自信を持って行えるようになります。 + +## 前提条件 + +始める前に、以下がインストールされていることを確認してください。 + +- Java 8 以上(チュートリアルは JDK 17 でテスト済み)。 +- Maven 3.6+(または好みで Gradle)で依存関係を管理。 +- 有効な Aspose.Words for Java ライセンス(無料トライアルでも動作しますが、ライセンスを適用すると評価用の透かしが除去されます)。 +- 水平線が少なくとも 1 本含まれた DOCX ファイル(`input.docx`)。Word の「水平罫線」機能で挿入したシンプルな区切り線を想像してください。 + +> **プロのコツ:** DOCX が手元にない場合は、新規 Word 文書を作成し、数段落入力後に *挿入 → 水平罫線* を追加し、`input.docx` として保存し、任意のフォルダーに配置してください。 + +## Step 1: Set Up the Maven Project + +まず、Maven プロジェクトを新規作成(または既存プロジェクトに追加)します。`pom.xml` に Aspose.Words の依存関係を追加する必要があります。 + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **なぜ重要か:** `aspose-words` アーティファクトを追加することは、*convert docx to pdf* の最初のステップです。これが無いとコンパイラは `Document`、`PdfSaveOptions` などの重要クラスを認識できません。 + +## Step 2: Load the Source DOCX Containing Horizontal Rules + +次に、DOCX を読み込む小さな Java クラスを書きます。ここから **tag horizontal rules** の処理が始まります—Aspose.Words は水平線を罫線付き段落として自動的に扱いますが、PDF/UA エンジンにタグ付けを任せます。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +まだ何も保存していないことに注意してください。**loading** だけを行っており、これは *convert docx to pdf* の前半部分です。`Document` オブジェクトは、挿入した水平線を含むすべての Word コンテンツを保持しています。 + +## Step 3: Configure PDF Save Options for PDF/UA‑2 Compliance + +**add accessibility to PDF** の魔法は `PdfSaveOptions` にあります。コンプライアンスレベルを `PDF_UA_2` に設定することで、Aspose.Words は次のことを行います。 + +1. 構造要素(見出し、表など)にタグ付け。 +2. 水平線のような装飾要素を *artifact* としてマークし、スクリーンリーダーに無視させる。 +3. 必要な PDF/UA メタデータを挿入。 + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **コンプライアンスを設定する理由:** `PDF_UA_2` を指定しない場合、生成された PDF は閲覧は可能ですが、自動アクセシビリティバリデータを通過しません。**tag horizontal rules** の要件は、コンプライアンスフラグが有効になることで自動的に満たされ、水平線は *artifact* として扱われます。 + +## Step 4: Save the Document as a PDF + +いよいよ **save document as pdf** です。この 1 行で DOCX の変換、アクセシビリティタグの適用、ファイルへの書き出しが一括で行われます。 + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +クラスを実行します(`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`)。確認メッセージが表示されます。生成された `ua_compliant.pdf` を Adobe Acrobat で開き、**File → Properties → Description → PDF/A, PDF/UA** を確認すると “PDF/UA‑2” と表示されているはずです。 + +### Expected Output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +PDF を開くと次の点が確認できます。 + +- 文書テキストは選択・検索可能。 +- 水平線はスクリーンリーダーに対して不可視(artifact として扱われる)。 +- PDF は基本的な PDF/UA バリデーションツール(例: PAC 3)をパスします。 + +## Step 5: Verify Accessibility – Quick Checklist + +Aspose.Words がほとんどの作業を自動化しますが、出力結果を確認することは重要です。 + +| チェック項目 | 確認方法 | +|--------------|----------| +| **Document title** | Acrobat → File → Properties → Title フィールド(`pdfOptions.setTitle` と一致していること) | +| **Artifact tagging** | Acrobat の “Reading Order” ツールを使用。水平線が *Artifact*(灰色)として表示されること | +| **Logical reading order** | Acrobat の “Accessibility Checker” を実行し、構造エラーがないこと | +| **Tagged PDF** | Acrobat の “Tags” パネルで階層(Document → Section → Paragraph など)が表示されていること | +| **PDF/UA compliance** | Acrobat の “Standards” タブに “PDF/UA‑2” が表示されていること | + +これらのチェックで問題が出た場合は、最新の Aspose.Words バージョンを使用しているか、`setCompliance(PdfCompliance.PDF_UA_2)` が正しく適用されているかを再確認してください。 + +## Common Pitfalls & How to Avoid Them + +1. **Missing License** – トライアル版は透かしを追加し、PDF/UA の検証に失敗することがあります。`main` メソッドの冒頭でライセンスを適用してください: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` が発生して変換が中断します。絶対パスを使用するか、プロジェクトルートに DOCX を配置し、`new File("input.docx").getAbsolutePath()` で参照してください。 +3. **Using Older Aspose Version** – PDF/UA のサポートはバージョン 22.9 で追加されました。最新リリースにアップグレードして機能欠如を防ぎましょう。 +4. **Horizontal Rule as Image** – 行を画像として挿入した場合、Aspose は通常の画像として扱い、artifact にはなりません。Word の組み込み *Horizontal Line* を使用して正しくタグ付けされるようにしてください。 + +## Extending the Solution – What If You Need More? + +- **Custom Tags**: 装飾アイコンなど他の装飾要素がある場合は、`PdfSaveOptions.setArtifactTaggingEnabled(true)` を使用して手動で artifact とマークできます。 +- **Multiple Documents**: フォルダー内の複数 DOCX をループ処理し、同じ `PdfSaveOptions` インスタンスを再利用してバッチ変換が可能です。 +- **Adding a Language Tag**: 多言語 PDF では `pdfOptions.setLanguage("en-US")` を設定すると、支援技術が適切な音声を選択しやすくなります。 + +## Full Working Example (All Code Together) + +以下に完全な実行可能 Java プログラムを示します。IDE にコピー&ペーストし、パスを調整した上で実行してください。 + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +実行後に生成された PDF を開くと、配布可能なクリーンでアクセシブルなファイルが手に入ります。 + +## Conclusion + +ここまでで、Aspose.Words for Java を使用して **save document as pdf** しながら **add accessibility to pdf** を自動的に適用し、水平線を **tag horizontal rules** してアーティファクト化する方法を実演しました。主なポイントは次の通りです。 + +- `PdfSaveOptions` に `PDF_UA_2` コンプライアンスを設定すれば、アクセシビリティ標準を満たす PDF が生成できます。 +- DOCX を読み込み `doc.save(..., pdfOptions)` を呼び出すだけで **convert docx to pdf** が完了します。 +- 水平線は自動的に処理され、追加コードは不要です。これにより **tag horizontal rules** の要件が満たされます。 +- この手法は **aspose convert docx pdf** に完全準拠し、最新ライブラリで検証可能な PDF を生成します。 + +次のステップに挑戦してみませんか? カスタムメタデータの追加、フォント埋め込み、フォルダー単位のバッチ処理など、ここで示した基盤を活用してさらに拡張できます。 + +PDF/UA コンプライアンス、ライセンス、その他 Word 要素の取り扱いについて質問があればコメントを残すか、Aspose の公式ドキュメントをご覧ください。豊富なサンプルが揃っています。コーディングを楽しみながら、アクセシブルな PDF を作成しましょう! + +![save document as pdf using Aspose.Words Java – accessible PDF example](placeholder-image.png "Aspose.Words Java を使用したドキュメントの PDF 保存 – アクセシブル PDF の例") + +## Related Tutorials + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/japanese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..cbb072744c --- /dev/null +++ b/words/japanese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,253 @@ +--- +category: general +date: 2026-05-26 +description: Word を Markdown として保存し、Aspose.Words for Java を使用して数式を LaTeX にエクスポートする方法を見つけましょう。数行で + Word の数式を LaTeX に変換できます。 +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: ja +og_description: Word を Markdown に保存し、Aspose.Words for Java を使用して数式を LaTeX にエクスポートする方法を学びましょう。完全な実行可能ガイドです。 +og_title: WordをMarkdownとして保存 – Javaで数式をLaTeXにエクスポート +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Word を Markdown として保存 – Java で数式を LaTeX にエクスポート +url: /ja/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word を Markdown に保存 – Java で数式を LaTeX にエクスポート + +Ever needed to **save word as markdown** but worried your equations would turn into a garbled mess? You're not alone. In this guide we’ll walk through **how to export math** from a `.docx` file straight into LaTeX while the rest of the document becomes clean Markdown. + +**Word を Markdown に保存**したいが、数式が乱れた文字列になることを心配したことはありませんか? あなたは一人ではありません。このガイドでは、`.docx` ファイルから**数式のエクスポート方法**を直接 LaTeX にエクスポートし、残りの文書をクリーンな Markdown に変換する方法をご紹介します。 + +We’ll cover everything from setting up the Aspose.Words library to verifying the final `out.md` file. By the end you’ll be able to **convert word equations latex** in a single method call, and you’ll understand the little nuances that make the conversion reliable. + +Aspose.Words ライブラリの設定から最終的な `out.md` ファイルの検証まで、すべてカバーします。最後までに、単一のメソッド呼び出しで **Word の数式を LaTeX に変換** できるようになり、変換を信頼できるものにする細かなニュアンスも理解できるようになります。 + +--- + +## 必要なもの + +- **Java 8+** – コードは最新の JDK で動作します。 +- **Aspose.Words for Java** – Maven/Gradle の依存関係、または手動設定が好みなら JAR を使用できます。 +- Office Math 方程式が少なくとも1つ含まれる Word ドキュメント (`math.docx`)。 +- 好きな IDE でも、シンプルな `javac`/`java` コマンドラインでも構いません。 + +If you already have those, great. If not, the next section shows exactly how to get the library into your project. + +すでに揃っているなら問題ありません。まだの場合は、次のセクションでライブラリをプロジェクトに導入する方法を正確に示します。 + +--- + +## Word を Markdown に保存 – ステップ 1: Aspose.Words をプロジェクトに追加 + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **プロのコツ:** Aspose はテスト用の無料一時ライセンスを提供しています。`license.xml` ファイルを resources フォルダーに配置し、ドキュメントを読み込む前に `License license = new License(); license.setLicense("license.xml");` を呼び出してください。 + +依存関係が解決したら、変換コードを書く準備が整います。 + +--- + +## 数式を LaTeX にエクスポートする方法 + +The heavy lifting is done by `MarkdownSaveOptions`. By switching its `OfficeMathExportMode` to `LATEX`, every Office Math object is rendered as a LaTeX fragment inside the Markdown output. + +`MarkdownSaveOptions` が主な処理を行います。`OfficeMathExportMode` を `LATEX` に切り替えることで、すべての Office Math オブジェクトが Markdown 出力内で LaTeX フラグメントとしてレンダリングされます。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### なぜこれが機能するのか + +- **`Document`** は Aspose のエントリーポイントで、`.docx` ファイルを抽象化し、方程式を含むすべてのノードにアクセスできます。 +- **`MarkdownSaveOptions`** はライブラリに *出力方法* を指示します。デフォルトでは方程式が画像としてレンダリングされ、テキストベースの形式の目的に反します。 +- **`OfficeMathExportMode.LATEX`** はエンジンに各 `OfficeMath` ノードを LaTeX に変換させ、Markdown パーサー(GitHub や Jekyll など)が MathJax プラグインと組み合わせてレンダリングできるようにします。 + +--- + +## Word の数式を LaTeX に変換 – ステップ 2: Markdown 出力を検証 + +After running the program, open `out.md`. You should see something like this: + +プログラムを実行したら、`out.md` を開きます。以下のような内容が表示されるはずです。 + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **注意:** LaTeX フラグメントはインライン数式の場合は `$…$`、ブロック数式の場合は `$$…$$` で囲まれます。これは、MathJax が有効なほとんどの静的サイトジェネレータが理解できる標準構文です。 + +If you prefer the equations to stay inline only, you can tweak the `MarkdownSaveOptions` further: + +数式をインラインのみで表示したい場合は、`MarkdownSaveOptions` をさらに調整できます。 + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx から Markdown LaTeX への変換 – ステップ 3: エッジケースと一般的な落とし穴 + +| Situation | What to watch for | Fix | +|-----------|-------------------|-----| +| **Complex nested equations** | Aspose が余分な波括弧 `{}` を出力することがあり、一部のパーサーはそれを文字通りに扱います。 | Markdown をシンプルな正規表現で後処理し、`{{` を `{` に縮小します。 | +| **Missing MathJax on the target site** | 数式が生の LaTeX コードとして表示されます。 | `` を HTML テンプレートに追加します。 | +| **Large documents** | ドキュメント全体を一度に読み込むため、メモリ使用量が急増します。 | `LoadOptions.setLoadFormat(LoadFormat.DOCX)` を使用し、`OutOfMemoryError` が発生した場合はページをバッチ処理することを検討してください。 | +| **License not set** | 警告が表示され、出力に透かしが入る可能性があります。 | 上記の Maven のヒントに示したように、`main` の早い段階でライセンスをロードしてください。 | + +--- + +## Word を Markdown に保存 – 完全な動作例 + +Below is a self‑contained class you can copy‑paste into any Java project. Just replace `YOUR_DIRECTORY` with the path to your files. + +以下は、任意の Java プロジェクトにコピー&ペーストできる自己完結型クラスです。`YOUR_DIRECTORY` をファイルへのパスに置き換えてください。 + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Run the program (`java MathToLatexMarkdown`) and you’ll see the console message confirming success. Open `out.md` in any editor – the equations should be clean LaTeX snippets ready for rendering. + +プログラムを実行(`java MathToLatexMarkdown`)すると、成功を示すコンソールメッセージが表示されます。任意のエディタで `out.md` を開くと、数式がクリーンな LaTeX スニペットとしてレンダリング準備ができているはずです。 + +--- + +## 期待される出力スナップショット + +![LaTeX 方程式付きの Word を Markdown に保存した出力](https://example.com/images/markdown-latex-output.png "LaTeX 方程式付きの Word を Markdown に保存した出力") + +*この画像は、生成された Markdown のスニペットを示しており、方程式 `\int_{a}^{b} f(x)\,dx` が `$$` で囲まれています。* + +--- + +## 結論 + +We’ve just demonstrated how to **save word as markdown** while preserving every Office Math equation as native LaTeX. The key step was configuring `MarkdownSaveOptions` with `OfficeMathExportMode.LATEX`, which turns a typical Word‑to‑Markdown pipeline into a fully math‑aware conversion tool. + +ここでは、**Word を Markdown に保存**しながら、すべての Office Math 方程式をネイティブ LaTeX として保持する方法を実演しました。重要なステップは `MarkdownSaveOptions` を `OfficeMathExportMode.LATEX` に設定することで、一般的な Word から Markdown へのパイプラインを完全に数式対応の変換ツールに変えました。 + +Now you can: + +1. **How to export math** from any `.docx` without losing fidelity. → 任意の `.docx` から忠実に数式をエクスポートできます。 +2. **Convert word equations latex** for static site generators, documentation, or academic blogs. → 静的サイトジェネレータ、ドキュメント、学術ブログ向けに Word の数式を LaTeX に変換できます。 +3. Extend the approach to batch‑process many files, integrate with CI pipelines, or even build a tiny web service. → このアプローチを拡張して多数のファイルをバッチ処理したり、CI パイプラインに統合したり、さらには小さなウェブサービスを構築したりできます。 + +If you’re curious about the next frontier, try combining this with **docx to markdown latex** for image‑heavy documents, or explore Aspose’s `HtmlSaveOptions` for a web‑ready HTML version. The possibilities are endless—experiment, break things, and then share your findings with the community. + +次のステップに興味があるなら、画像が多いドキュメント向けに **docx to markdown latex** と組み合わせてみたり、Web 用 HTML バージョンのために Aspose の `HtmlSaveOptions` を探ってみてください。可能性は無限です—実験し、失敗し、そしてコミュニティと成果を共有しましょう。 + +Got questions or a tricky equation that didn’t render as expected? Drop a comment below, and happy coding! + +質問や期待通りにレンダリングされなかった難解な方程式がありますか?下にコメントを残してください。ハッピーコーディング! + +## 関連チュートリアル + +- [Word から LaTeX をエクスポートする方法: DOCX を Markdown に変換して PDF として保存](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [docx を markdown に変換 – Aspose.Words で数式を LaTeX にエクスポート](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Aspose.Words for Java を使用して Word を PDF に変換する方法](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/japanese/java/document-loading-and-saving/_index.md index 6a3417af60..b5b5fe2ff9 100644 --- a/words/japanese/java/document-loading-and-saving/_index.md +++ b/words/japanese/java/document-loading-and-saving/_index.md @@ -115,6 +115,8 @@ Aspose.Words for Java の多様性を探り、さまざまな形式でドキュ ### [Aspose.Words for Java で破損した docx を復元 – 完全ガイド](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [破損した Word ドキュメントを開く – Java でリカバリーモードを設定](./open-corrupted-word-document-set-recovery-mode-in-java/) + ### [Java でフォント置換警告を取得する – Aspose.Words 完全ガイド](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## よくある質問 diff --git a/words/japanese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/japanese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..33f0e4e220 --- /dev/null +++ b/words/japanese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words を使用して Java で破損した Word ドキュメントを開く。リカバリーモードの設定方法と、破損した Word + ファイルを確実に復元する方法を学びましょう。 +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: ja +og_description: Aspose.Words を使用して Java で破損した Word ドキュメントを開く。このガイドでは、リカバリモードの設定方法と破損した + Word ファイルを効率的に復元する方法を示します。 +og_title: 破損したWord文書を開く – Javaでリカバリモードを設定 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: 破損したWord文書を開く – Javaでリカバリモードを設定する +url: /ja/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 破損した Word ドキュメントを開く – Java でリカバリモードを設定する + +破損した Word ドキュメントを開こうとして例外でプログラムがクラッシュするのを見たことがありますか? あなた一人ではありません—壊れた .docx ファイルは本当に頭痛の種です。 良いニュースは、Aspose.Words for Java が細かい制御を提供してくれるので、アプリがクラッシュせずに **open corrupted word document** が可能になり、警告を表示するか、サイレントリカバリにするか、あるいはハードリジェクトにするかを選べます。 + +このチュートリアルでは、正しい `LoadOptions` の作成から、適切な **set recovery mode** の値の選択、そしてドキュメントが実際にロードされたことの確認まで、完全なプロセスを順を追って説明します。最後まで読むと、手動でコピー&ペーストすることなく、**how to recover corrupted word file** をプログラムで実行できるようになります。 + +> **必要な環境** +> * Java 8 以降(API は Java 11 でも動作します) +> * Aspose.Words for Java 23.9(または最新バージョン) +> * サンプルの破損 .docx ファイル—手元にない場合は、任意の有効なファイル名を変更して破損をシミュレートしてください + +さっそく始めましょう。 + +## 破損した Word ドキュメントを開く – ステップバイステップ概要 + +以下は実装する高レベルのフローです: + +1. **Create `LoadOptions`** – このオブジェクトは、問題に遭遇したときに Aspose.Words がどのように振る舞うかを指示します。 +2. **Set recovery mode** – `RECOVER_WITH_WARNINGS`、`RECOVER_WITHOUT_WARNINGS`、または `REJECT_CORRUPTED` のいずれかを選択します。 +3. **Load the document** – 設定したオプションを使用してドキュメントをロードします。 +4. **Verify** – ロードが成功したかを確認します(例:ページ数を出力)。 + +各ステップは詳細に説明し、IDE に直接コピー&ペーストできるコードスニペットを添えています。 + +## 異なるシナリオ向けのリカバリモード設定 + +Aspose.Words は `LoadOptions.RecoveryMode` 内に 3 つのリカバリ戦略を定義しています: + +| モード | 動作 | 使用するタイミング | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | ドキュメントの読み込みを試みますが、問題をコンソールに警告として表示します。 | アプリが中断せずに *何が* 問題だったかを確認したいとき。 | +| `RECOVER_WITHOUT_WARNINGS` | 可能な限り静かに修復し、警告を抑制します。 | ログをクリーンに保つ必要がある本番環境。 | +| `REJECT_CORRUPTED` | 破損が検出された瞬間に例外をスローします。 | 失敗を速やかに検出すべき厳格なバリデーションパイプライン。 | + +正しいモードを選択することが **set recovery mode** を正しく設定する本質です。デバッグ時の多くのケースでは `RECOVER_WITH_WARNINGS` が最適で、修復された部分を正確に教えてくれます。 + +## Aspose.Words を使用した破損した Word ファイルのリカバリ方法 + +以下は **完全かつ実行可能な Java プログラム** で、全プロセスをデモします。`RecoveryModeDemo.java` ファイルに貼り付け、パスを調整して実行してください。 + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### 各行の重要ポイント + +* **`LoadOptions loadOptions = new LoadOptions();`** – このオブジェクトがないと Aspose.Words はデフォルトでリカバリを行わず、破損ファイルを *reject* します。作成することで動作を変更できるフックが得られます。 +* **`setRecoveryMode(...)`** – これが **set recovery mode** の呼び出しで、警告を表示するか隠すか、例外を発生させるかを決定します。 +* **`new Document(path, loadOptions);`** – コンストラクタは先ほど設定した `LoadOptions` を受け取り、ライブラリが最初から破損ファイルの扱い方を把握します。 +* **`doc.getPageCount()`** – 簡易的なサニティチェックです。ドキュメントがロードされページ数が返ってくれば、**how to recover corrupted word file** に成功したことになります。 +* **`doc.save(...)`** – 任意ですが便利です。修復されたバージョンをディスクに書き出して後で利用できます。 + +## 一般的なエッジケースの処理 + +### 1. ファイルが見つからない + +パスが間違っていると `Document` は `FileNotFoundException` をスローします。ロード処理を try‑catch で囲み、フレンドリーなメッセージをログに出しましょう: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. 修復不可能な破損 + +`RECOVER_WITH_WARNINGS` を使用していても、構造が修復不能な場合があります。その場合 Aspose.Words は可能な部分だけをロードしますが、 “Cannot read paragraph properties” のような警告がコンソールに表示されます。これらの警告は、手動で再構築が必要な欠落セクションを指し示すことが多いので注意してください。 + +### 3. 大容量ファイルとパフォーマンス + +リカバリは、ライブラリがファイルを 2 回解析する(問題検出と再構築)ため、若干のオーバーヘッドが発生します。マルチギガバイトのドキュメントの場合は、ストリーミングで処理するか、JVM ヒープを `-Xmx2g` などに増やして `OutOfMemoryError` を回避してください。 + +## プロのコツ – リカバリを堅牢にする方法 + +* **警告をファイルに記録** – `System.err` をロガーにリダイレクトして、何が修正されたかの監査ログを残します。 +* **リカバリ後に検証** – `doc.updatePageLayout();` を実行し、再度ページ数をチェックします。破損したセクションを修正した後、レイアウトが変わることがあります。 +* **バッチリカバリを自動化** – デモをループでラップし、フォルダ内の破損ファイルをすべて同じ `LoadOptions` で処理します。 + +## 結論 + +これで Aspose.Words for Java を使って **how to recover corrupted word file** を正確に実行できるようになりました。`LoadOptions` インスタンスを作成し、シナリオに合った **set recovery mode** を設定してそのオプションでドキュメントをロードすれば、アプリケーションをクラッシュさせることなく **open corrupted word document** が可能です。上記のサンプルコードは、ページ数を出力し、クリーンアップされたコピーを保存する完全な実行可能ソリューションです。 + +次は何をしますか?リカバリモードを `RECOVER_WITHOUT_WARNINGS` に切り替えてコンソール出力を比較するか、暗号化されたドキュメントのロードを試してみてください(パスワードは別途指定する必要があります)。 + +## 関連チュートリアル + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/japanese/java/document-styling/_index.md index 297084a69a..7763aba91c 100644 --- a/words/japanese/java/document-styling/_index.md +++ b/words/japanese/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aspose.Words for Javaを使用してドキュメントテーマをカスタマ Aspose.Words for Javaを使って透かしを適用し、ページ設定を行う方法を学びましょう。ソースコード付きの包括的なガイドです。 ### [ドキュメントのヘッダーとフッターのスタイル](./document-header-footer-styling/) この詳細なガイドでは、Aspose.Words for Java を使用してドキュメントのヘッダーとフッターにスタイルを設定する方法を学びます。ステップバイステップの説明とソースコードが含まれています。 +### [Aspose.Words for Javaでデフォルトフォント設定を行う – 完全ガイド](./set-default-font-settings-in-aspose-words-for-java-complete/) +Aspose.Words for Java を使用して、ドキュメント全体のデフォルトフォントを設定する方法をステップバイステップで解説します。 {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/japanese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..f295712af6 --- /dev/null +++ b/words/japanese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Javaでデフォルトのフォント設定を行い、数行のコードでフォント設定の方法と欠落フォントの検出方法を学びましょう。 +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: ja +og_description: Aspose.Words for Javaでデフォルトのフォント設定を行い、フォント設定の方法と欠落フォントの迅速かつ確実な検出方法を学びましょう。 +og_title: Aspose.Words for Java のデフォルトフォント設定を行う +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Aspose.Words for Javaでデフォルトフォント設定を行う – 完全ガイド +url: /ja/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words for Javaでデフォルトフォント設定を設定する – 完全ガイド + +Aspose.Words for JavaでWord文書をロードするときに**set default font settings**する方法を考えたことがありますか? あなたは一人ではありません。欠損したグリフは洗練されたレポートを文字化けした混乱に変えてしまい、フォント置換の警告を早期に捕捉することでデバッグにかかる時間を何時間も節約できます。 + +このチュートリアルでは、**sets default font settings**、プログラムで**set font settings**する方法を示し、レイアウトが崩れる前に**detect missing fonts**する信頼できる方法を実演する、簡潔なエンドツーエンドの例を順に解説します。 + +--- + +## 学習内容 + +- 新しい `FontSettings` インスタンスを使用して `LoadOptions` オブジェクトを作成する方法。 +- ドキュメントのロード中に**detect missing fonts**する警告リスナーを添付する方法。 +- リスナーが置換を静かに報告する間に DOCX ファイルをロードする方法。 +- 本番環境でフォールバックフォントをカスタマイズし、エッジケースを処理するためのヒント。 + +余計なライブラリや不明瞭な設定ファイルは不要です—純粋な Java と Aspose.Words だけです。 + +## 前提条件 + +始める前に、以下が揃っていることを確認してください: + +1. **Aspose.Words for Java**(バージョン 23.10 以上)をクラスパスに配置してください。 +2. Java 17(またはそれ以降)の開発キット – 任意の最新 JDK が使用可能です。 +3. 意図的にインストールされていないフォント(例: *“MissingFont.ttf”*)を使用している DOCX ファイル。 + +Aspose の JAR がない場合は、公式 Maven リポジトリから取得してください: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +以上です—このデモのために追加のフォントをインストールする必要はありません。 + +## 手順 1: LoadOptions を作成し **Set Default Font Settings** を設定する + +最初に必要なのは、未知のフォントに遭遇したときの Aspose の動作を指示するクリーンな `LoadOptions` オブジェクトです。`setFontSettings(new FontSettings())` を呼び出すことで、空のフォールバックリストから始まる**set default font settings**を行います。 + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Why this matters:** +> フォントを明示的に設定しない場合、Aspose はシステムのデフォルトコレクションにフォールバックし、欠損フォントの問題が隠れる可能性があります。新しい `FontSettings` インスタンスから開始することで、どのフォントが有効と見なされるかを完全に制御できます。 + +## 手順 2: Warning Listener を添付して **Detect Missing Fonts** を検出する + +Aspose は実行するすべての置換に対して `WarningInfo` オブジェクトを発生させます。`WarningType.FONT_SUBSTITUTION` をリッスンすることで、ドキュメントが解析されると同時に**detect missing fonts**できます。 + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro tip:** リスナーはドキュメントをロードするのと同じスレッドで実行されるため、実質的なパフォーマンスペナルティはありません。後で分析するために警告を収集する必要がある場合は、直接出力する代わりに `List` にプッシュしてください。 + +## 手順 3: 設定したオプションを使用してドキュメントをロードする + +これで**set font settings**し、リスナーの準備ができたので、単にファイルをロードします。欠損フォントがあると即座にコールバックがトリガーされます。 + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +ソースファイルがインストールされていないフォントを参照している場合、以下のような出力が表示されます: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +この行は、どのフォントが欠損していたか、どのフォールバックが使用されたかを正確に示します—ログやユーザーフィードバックに最適です。 + +## 手順 4: 通常の処理を続行する(オプション) + +この時点でドキュメントは完全にロードされており、編集、PDF への変換、テキスト抽出など、好きな操作を続行できます。警告リスナーは既に役割を果たしているため、追加のチェックは不要です。 + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **What if you want a custom fallback?** +> `FontSettings` を空のままにせず、特定のフォントを追加できます: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +これで、欠損したフォントはすべて *Times New Roman* に置き換えられます—ほとんどの西洋文書に対して信頼できる選択です。 + +## ビジュアル概要 + +![Aspose.Words for Javaでデフォルトフォント設定を行う方法を示す図](image.png "デフォルトフォント設定フローの図") + +*Alt text: Aspose.Words for Javaのデフォルトフォント設定フローチャート* + +この図は、`LoadOptions` の初期化(ここで**set default font settings**)から警告リスナーの添付(**detect missing fonts**)へ、そして最終的にドキュメントをロードするまでのフローを示しています。 + +## よくある落とし穴と回避方法 + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **Forgot to call `setFontSettings`** | Aspose がシステムのデフォルトを使用し、欠損フォントを隠すため。 | 常に新しい `FontSettings` インスタンスを作成し、`LoadOptions` に割り当ててください。 | +| **Listener not triggered** | リスナーがドキュメントのロード後に追加されたため。 | `new Document(...)` を呼び出す*前に*警告リスナーを追加してください。 | +| **Path typo leads to `FileNotFoundException`** | ハードコーディングされたパスが OS の大文字小文字の区別と合わないため。 | `Paths.get("...").toAbsolutePath()` を使用するか、プロジェクトルートからの相対パスを設定してください。 | +| **Multiple missing fonts overwhelm logs** | 大きなドキュメントは多数の警告を生成する可能性があります。 | 出力前に重複を除去するか、`Set` にメッセージを集約してください。 | + +## ソリューションの拡張 + +アプリケーション全体で**set font settings**が必要な場合は、シングルトンの `FontSettings` を作成し、すべての `LoadOptions` で再利用することを検討してください。これにより、一貫したフォールバック戦略を維持し、オブジェクトの再生成を回避できます。 + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +これでコードベースの任意の部分が `FontConfig.getLoadOptions()` を呼び出すだけで、同じ **set default font settings** ロジックの恩恵を即座に受けられます。 + +## 結論 + +ここでは、Aspose.Words for Javaで**set default font settings**を行い、プログラムで**set font settings**し、出力が破損する前に**detect missing fonts**するために必要なすべてをカバーしました。完全な実行可能サンプルは上記のコードスニペットにあり、IDE に貼り付けるだけで警告を実際に確認できます。 + +次のステップは? フォールバックフォントを変更したり、さまざまなドキュメント形式(DOC、RTF、HTML)で実験したり、警告コレクターを監視ダッシュボードに統合したりしてください。`FontSettings` を使いこなせばこそ、生成されたドキュメントが期待通りに表示されるという自信が得られます—驚きもなく、文字化けもありません。 + +質問や難しいフォント置換のシナリオがありますか? 以下にコメントを残してください。ハッピーコーディング! + +## 関連チュートリアル + +- [フォントフォールバック設定](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [フォントフォールバック設定](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [フォントフォールバック設定](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/java/images-shapes/_index.md b/words/japanese/java/images-shapes/_index.md index ed88d356ae..b35b2451f3 100644 --- a/words/japanese/java/images-shapes/_index.md +++ b/words/japanese/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aspose.Words for Java を使って、Word 文書の高品質なサムネイル ### [JavaでWord文書を作成 – 影付き長方形シェイプを追加](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) JavaでWord文書に影効果付きの長方形シェイプを追加し、視覚的に魅力的なレイアウトを作成する方法を学びます。 +### [Java の Word 文書で長方形シェイプを作成する – 完全ステップバイステップガイド](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Java で Word 文書に長方形シェイプを挿入し、プロパティ設定や配置方法をステップバイステップで解説します。 + ## 追加リソース - [Aspose.Words for Java ドキュメント](https://reference.aspose.com/words/java/) diff --git a/words/japanese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/japanese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..c08e1b3e82 --- /dev/null +++ b/words/japanese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-26 +description: JavaのWord文書で長方形の図形を作成し、影効果を適用します。図形に影を追加し、影の距離を設定し、ファイルを保存する方法を学びましょう。 +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: ja +og_description: Java の Word ドキュメントで長方形の図形を作成し、影効果を適用し、図形の影を追加し、Aspose.Words で影の距離を設定します。 +og_title: JavaのWord文書で矩形シェイプを作成する – 完全ガイド +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: JavaのWord文書で長方形シェイプを作成する – 完全ステップバイステップガイド +url: /ja/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java Word ドキュメントで矩形シェイプを作成 – 完全ステップバイステップガイド + +Java Word ドキュメントで **create rectangle shape** を作成したいと思ったことはありますか?しかし、どこから始めればよいか分からないことも多いでしょう。プログラムでレポートや請求書を生成する際、多くの開発者がこの壁にぶつかります。このチュートリアルでは、**create rectangle shape** の作成方法、洗練された影の適用方法、そして影の距離を微調整してプロフェッショナルな仕上がりにする手順を詳しく解説します。 + +Aspose.Words for Java を使用します。この堅牢なライブラリを使えば、Microsoft Office をインストールせずに Word ファイルを操作できます。本ガイドの最後までに、**create word document java** プロジェクトで **add shape shadow**、**apply shadow effect**、**set shadow distance** を数行のコードで実装できるようになります。 + +--- + +## 作成するもの + +- シアンの矩形を含む新しい `.docx` ファイル。 +- ぼかしがかかり、角度が付いており、部分的に透明なリアルなドロップシャドウ。 +- シェイプから影までの距離を完全に制御。 +- Maven または Gradle プロジェクトにそのまま組み込める、すぐに実行可能な Java クラス。 + +外部ツール不要、手動の UI 操作も不要—純粋にコードだけです。 + +## 前提条件 + +- Java 8 以上(コードは Java 11、Java 17 でも動作します)。 +- Aspose.Words for Java ライブラリ(Maven Central から入手可能)。 +- お好みの IDE またはテキストエディタ(IntelliJ IDEA、Eclipse、VS Code など)。 +- Java 構文の基本的な知識。 + +Maven の依存関係を追加したことがない場合は、以下の簡単なスニペットをご覧ください: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +それでは、始めましょう。 + +## ステップ 1: Word ドキュメントで矩形シェイプを作成 + +最初に必要なのは空のドキュメントと `DocumentBuilder` です。builder はドキュメントに書き込むペンのようなものです。これが用意できたら、単一のメソッド呼び出しで **create rectangle shape** が可能です。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **重要な理由:** `insertShape` メソッドはジオメトリを作成するだけでなく、シェイプをドキュメントの内部コレクションに追加するため、すぐにスタイリングを開始できます。 + +## ステップ 2: シェイプに影効果を適用 + +矩形がページ上に配置されたので、**apply shadow effect** を行います。影は奥行きを与え、シェイプがページから浮き上がっているように見せ、レポートの可読性を向上させる微妙な UI 改善です。 + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **プロのコツ:** `5.0` のぼかしは画面表示のドキュメントで自然に見えます。印刷する場合は、ぼやけた外観を防ぐためにやや低めの値にすると良いでしょう。 + +## ステップ 3: 影の距離を設定 – 配置の微調整 + +影はぼかしだけでなく、適切なオフセットも必要です。ここで **set shadow distance** を行います。`7.0` ポイントの距離は、目立ちすぎず、しかし確実に見えるほどの控えめなオフセットを作ります。 + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **もっと大きなオフセットが必要な場合は?** 値を上げ、よりタイトにしたい場合は下げます。距離は角度と組み合わせて影を正しく配置することを忘れないでください。 + +## ステップ 4: ドキュメントを保存 – 作業を永続化 + +最後に、ドキュメントをディスクに書き込みます。ファイルの保存先は好きなパスに変更してください。 + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +クラスを実行すると `shadow.docx` ファイルが作成され、Microsoft Word や LibreOffice で開くと、45° の角度で 7 ポイントオフセットされたソフトなグレーの影付きシアン矩形が表示されます。 + +## 完全な動作例 + +以下に、コピー&ペースト可能な完全なコードを示します。すべてのインポート、コメント、最終的な `save` 呼び出しが含まれています。 + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**期待される出力:** `shadow.docx` を開くと、1 ページ目の中央にシアンの矩形が表示され、右下にわずかにオフセットされた微妙なグレーの影が落ちます。影のぼかしと透明度により、自然光のように見えます。 + +## よくある質問とエッジケース + +### 「別のシェイプを使用できますか?」 + +もちろんです。`ShapeType.RECTANGLE` を `ShapeType.OVAL`、`ShapeType.LINE`、または他のサポートされている enum に置き換えてください。影のコードはそのままです。 + +### 「複数の影が必要な場合は?」 + +Aspose.Words はシェイプごとに単一の影しかサポートしていません。複数の影をシミュレートするには、シェイプを複製し、各コピーをオフセットし、透明度を調整します。 + +### 「LibreOffice でも影は表示されますか?」 + +はい。Aspose.Words は標準的な OOXML を出力するため、LibreOffice でも正しく解釈されます。レンダリングエンジンの違いにより若干見え方が変わることがありますが、効果は維持されます。 + +### 「ブランドに合わせて影の色を変更するには?」 + +`java.awt.Color.GRAY` を任意の `java.awt.Color` に置き換えるだけです。例えば、企業のブルーにしたい場合は `new java.awt.Color(0, 120, 215)` を使用します。 + +## 画像イラスト + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** のイラストで、Word ドキュメント内にシアンの矩形とグレーのドロップシャドウが表示されています。 + +## まとめと次のステップ + +ここでは、Aspose.Words for Java を使用して **create rectangle shape**、**apply shadow effect**、**add shape shadow**、**set shadow distance** を行う方法を解説しました。コードは自己完結型で、最新の JDK で動作し、配布可能な洗練された `.docx` ファイルを生成します。 + +さらに進めたいですか?以下を試してみてください: + +- `builder.moveTo(rectangleShape.getAbsolutePosition())` を使用して矩形内にテキストを追加する。 +- シェイプのテーブルを作成して図を構築する。 +- ドキュメントを PDF にエクスポートする(`doc.save("output.pdf", SaveFormat.PDF);`)。 + +これらはすべて、先ほど学んだ基本に基づいているため、例を拡張するのが容易に感じられるでしょう。 + +## 最後に + +**create word document java** のようなシェイプや影付けのタスクをマスターすれば、レポート、契約書、マーケティング資料の自動化で大きな優位性を得られます。ここで示したアプローチはクリーンで保守性が高く、何よりも必要なビジュアルスタイルに合わせて簡単に調整できます。 + +コードを実行し、ぼかし、角度、距離を調整して、ドキュメントが平凡から洗練されたものへと変化する様子をご覧ください。問題が発生したら下にコメントを残してください。喜んでお手伝いします。 + +コーディングを楽しんで! + +## 関連チュートリアル + +- [Create Word Document Java – 影効果付き矩形シェイプの追加](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Aspose.Words for Java の DocumentBuilder を使用してフォームフィールドを作成しコンテンツを追加する方法](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Aspose.Words for Java でバーコード生成付き Word から PDF を作成](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/korean/java/document-conversion-and-export/_index.md index f6bf9254e0..01b20fa9d8 100644 --- a/words/korean/java/document-conversion-and-export/_index.md +++ b/words/korean/java/document-conversion-and-export/_index.md @@ -89,18 +89,32 @@ Aspose.Words for Java를 사용해 DOCX 파일을 PDF 형식으로 변환하는 ### [DOCX에서 접근성 PDF 만들기 – 완전 가이드](./create-accessible-pdf-from-docx-complete-guide/) DOCX 파일을 접근성 PDF로 변환하는 전체 단계별 가이드. +### [Aspose.Words Java로 문서를 PDF로 저장 – 전체 접근성 가이드](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Aspose.Words for Java를 사용해 PDF로 저장하면서 접근성을 완전하게 보장하는 단계별 가이드. + ### [Java용 Aspose.Words에서 테이블 및 테이블 스타일 서식 지정](./formatting-tables-and-table-styles/) Aspose.Words for Java에서 표를 포맷하고 표 스타일을 적용하는 방법. 테이블 서식을 설명하는 동안 가이드와 소스를 제공하여 문서 표시를 개선합니다. ### [docx를 markdown으로 변환 – Aspose.Words로 수학 방정식을 LaTeX로 내보내기](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Aspose.Words를 사용해 DOCX 파일을 Markdown으로 변환하고, 수학 방정식을 LaTeX 형식으로 내보내는 방법을 배웁니다. +### [Word를 마크다운으로 저장 – Java로 수학을 LaTeX로 내보내기](./save-word-as-markdown-export-math-to-latex-with-java/) +Aspose.Words for Java를 이용해 Word 문서를 마크다운으로 저장하고, 수학 방정식을 LaTeX 형식으로 내보내는 방법을 단계별로 안내합니다. + ### [DOCX 변환 시 Markdown에 이미지 삽입하는 방법](./how-to-embed-images-in-markdown-when-converting-docx/) DOCX 파일을 Markdown으로 변환하면서 이미지 파일을 올바르게 포함하는 방법을 단계별로 안내합니다. +### [DOCX를 Markdown으로 변환할 때 이미지를 Base64로 삽입하기](./embed-images-as-base64-when-converting-docx-to-markdown/) +DOCX를 Markdown으로 변환하면서 이미지 파일을 Base64 인코딩으로 삽입하는 방법을 단계별로 안내합니다. + ### [문서를 TXT로 저장 – Word 수식 내보내기 빠른 가이드](./save-document-as-txt-quick-guide-to-exporting-word-math/) Aspose.Words for Java를 사용하여 문서를 TXT 형식으로 저장하고 Word 수식을 내보내는 방법을 단계별로 안내합니다. +### [Java로 docx를 txt로 내보내기 – 완전 프로그래밍 가이드](./export-docx-to-txt-with-java-complete-programming-guide/) +Aspose.Words for Java를 사용해 DOCX 파일을 TXT 형식으로 변환하고, 텍스트와 수식 내보내기를 단계별로 안내합니다. + +### [Java용 Aspose.Words에서 접근성 PDF 전체 태깅 가이드](./create-accessible-pdf-in-java-full-tagging-guide/) + ## 자주 묻는 질문 **Q: Aspose.Words를 사용해 기존 PDF에 워터마크를 어떻게 추가하나요?** diff --git a/words/korean/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/korean/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..9a963ecb21 --- /dev/null +++ b/words/korean/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-05-26 +description: Java에서 단계별 코드로 접근성 PDF 만들기. 접근성을 위해 PDF에 태그를 추가하는 방법과 PdfSaveOptions를 + 사용하여 PDF 태깅을 활성화하는 방법을 배웁니다. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: ko +og_description: Java에서 단계별 코드를 사용해 접근성 PDF를 생성하세요. PDF에 접근성 태그를 추가하고 PdfSaveOptions를 + 사용해 PDF 태깅을 활성화하는 방법을 배워보세요. +og_title: Java에서 접근성 PDF 만들기 – 전체 태깅 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Java로 접근성 PDF 만들기 – 전체 태깅 가이드 +url: /ko/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java에서 접근 가능한 PDF 만들기 – 전체 태깅 가이드 + +Java 코드에서 직접 **접근 가능한 PDF** 파일을 만드는 방법이 궁금했나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 스크린 리더에 의존하는 사용자들을 지원해야 하며, 일반 PDF와 접근 가능한 PDF의 차이는 매우 큽니다. 이 튜토리얼에서는 **PDF를 접근성을 위해 태깅하는 방법**을 살펴보고, Aspose PDF for Java를 사용하여 **태그가 있는 PDF를 만드는 방법**을 보여드리며, 모든 독자가 동일한 정보를 얻을 수 있도록 **PDF에 접근성 태그를 추가하는** 정확한 단계들을 공개합니다. + +우리는 또한 **PDF 태깅 활성화** 모범 사례, 일반적인 함정, 그리고 오늘 바로 프로젝트에 넣어 사용할 수 있는 완전한 실행 가능한 예제를 다룰 것입니다. 모호한 참고 자료는 없습니다—구체적인 코드, 설명, 그리고 태그를 확인하기 위해 Adobe Acrobat에서 열 수 있는 최종 파일만 제공합니다. + +## 배울 내용 + +- PDF 태깅 및 접근성 준수의 이유. +- 전제 조건 및 라이브러리 설정 (Aspose PDF for Java 23.10 이상). +- 처음부터 **접근 가능한 PDF**를 **단계별**로 만드는 방법. +- 기본 `setTagDocumentStructure` 호출을 넘어 **PDF에 접근성 태그를 추가하는** 방법. +- 출력 테스트 및 일반적인 문제 해결을 위한 팁. + +이 가이드를 마치면 WCAG 2.1 AA 검사를 통과하고 동시에 전문적인 모습을 갖춘 PDF를 생성할 수 있게 됩니다. + +--- + +## 전제 조건 + +시작하기 전에 다음을 확인하십시오: + +| 요구 사항 | 이유 | +|-------------|--------| +| **Java 8+** | 현대적인 언어 기능과 향상된 유니코드 처리. | +| **Aspose PDF for Java** (v23.10 or newer) | `PdfSaveOptions` 클래스와 태깅 지원을 제공합니다. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | 쉽게 컴파일하고 디버깅할 수 있도록. | +| **Write permission** to a folder where the PDF will be saved | `doc.save` 호출에 쓰기 가능한 경로가 필요합니다. | + +아직 프로젝트에 Aspose PDF를 추가하지 않았다면, 다음 Maven 의존성을 `pom.xml`에 넣으세요: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** 최신 버전을 사용하세요; 최신 릴리스는 태깅 정확성을 향상시키고 언어별 접근성 기능을 추가합니다. + +## 단계 1: 문서 골격 설정 + +먼저, 새로운 `Document` 객체를 생성합니다. 이것은 나중에 접근성을 위해 필요한 태그를 담게 될 빈 캔버스로 생각하면 됩니다. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**왜 중요한가:** 내용이 없으면 태깅할 것이 없습니다. 간단한 `TextFragment`를 추가하면 태깅 엔진이 작업할 수 있는 것이 생기며, 이후 구조 태깅을 활성화하면 자동으로 `

` (단락) 태그가 생성됩니다. + +## 단계 2: PDF 저장 옵션 생성 (태깅의 핵심) + +이제 Aspose PDF에게 파일 내부에 논리적 구조 트리를 삽입하도록 지시하는 옵션을 준비합니다. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +`setTagDocumentStructure(true)` 호출은 **PDF 태깅 활성화** 스위치입니다. true로 설정하면 라이브러리가 시각적 레이아웃을 반영하는 태그 트리를 구축하여 보조 기술이 PDF를 읽을 수 있게 합니다. + +> **Note:** 이것은 **태그가 있는 PDF를 만드는 방법** 중 가장 간단한 방법입니다. 더 세밀한 제어(예: 언어 설정이나 사용자 정의 태그)를 원한다면 `pdfOptions.setTagLanguage("en-US")`와 `pdfOptions.setTagStructureTreeRoot(...)`를 살펴볼 수 있습니다. + +## 단계 3: 접근 가능한 PDF 저장 + +마지막으로, 방금 구성한 옵션을 사용하여 문서를 디스크에 저장합니다. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +`doc.save`가 완료되면 `output` 폴더에 `accessible.pdf`가 생성됩니다. Adobe Acrobat에서 열고 **File → Properties → Description → Tags**를 확인하면 채워진 태그 트리를 볼 수 있습니다. + +## PDF를 접근성을 위해 태깅하는 방법 – 기본을 넘어 + +위의 3단계 스니펫은 이미 **PDF에 접근성 태그를 추가**하지만, 실제 문서는 종종 더 다듬기가 필요합니다. 다음은 추가할 수 있는 몇 가지 향상 사항입니다: + +### 1. 문서 언어 설정 + +스크린 리더는 언어 속성을 사용해 텍스트를 올바르게 발음합니다. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. 제목 및 주제 제공 + +메타데이터는 사용자가 파일을 열기 전에도 보조 도구가 컨텍스트를 제공하도록 돕습니다. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. 이미지에 대체 텍스트 태그 지정 + +이미지를 삽입한다면 `alt` 설명이 필요합니다. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. 표 헤더 표시 + +표는 헤더 행을 표시하지 않으면 독자를 혼란스럽게 만드는 것으로 악명이 높습니다. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +이러한 추가 단계는 PDF를 단순히 *기술적으로* 태그하는 것을 넘어, 다양한 독자를 위해 진정으로 **접근 가능**하게 만듭니다. + +## PDF 태깅을 활성화할 때 흔히 발생하는 함정 + +| 증상 | 가능한 원인 | 해결 방법 | +|---------|--------------|-----| +| Acrobat에서 태그가 없음 | `setTagDocumentStructure`가 `false`로 남아 있음 | `pdfOptions.setTagDocumentStructure(true)`를 호출했는지 확인하십시오. | +| 잘못된 읽기 순서 | 명시적인 태그 없이 복잡한 레이아웃 | 맞춤 순서를 정의하려면 `pdfOptions.setTagStructureTreeRoot(...)`를 사용하십시오. | +| 이미지가 설명 없이 “image”로 읽힘 | 대체 텍스트가 설정되지 않음 | `image.getAlternativeText().setValue("...")`를 호출하십시오. | +| 언어가 인식되지 않음 | `setTagLanguage`가 누락되었거나 잘못된 로케일 | BCP‑47 언어 코드를 제공하십시오 (`en-US`, `fr-FR`). | + +이러한 문제를 인식하고 있으면 나중에 디버깅에 소요되는 시간을 크게 절약할 수 있습니다. + +## 결과 확인 – 기대되는 사항 + +프로그램을 실행한 후, Adobe Acrobat Reader에서 `output/accessible.pdf`를 엽니다: + +1. **Tags 패널** (`View → Show/Hide → Navigation Panes → Tags`)에 `/Document → /Part → /Sect → /Para`와 같은 계층 구조가 표시되어야 합니다. +2. **읽기 순서**는 시각적 흐름을 따라야 합니다 (텍스트 먼저, 그 다음 이미지). +3. **스크린 리더** (NVDA, VoiceOver)는 단순히 “Page 1” 대신 “Hello, accessible PDF!”를 읽습니다. + +위 항목 중 하나라도 누락되었다면, 위 단계들을 다시 확인하십시오—특히 `setTagDocumentStructure` 호출을. + +## 전체 작업 예제 (복사‑붙여넣기 준비 완료) + + + +## 관련 튜토리얼 + +- [Word에서 접근 가능한 PDF 만들기 – PDF/UA로 변환](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [DOCX에서 접근 가능한 PDF 만들기 – 완전 가이드](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Aspose.Words for Java로 문서를 PDF로 저장하는 방법](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/korean/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..02160b6f5f --- /dev/null +++ b/words/korean/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-26 +description: Java용 Aspose.Words로 docx를 markdown으로 변환하면서 이미지를 base64로 삽입하세요. Word를 + markdown으로 변환하고, Word를 markdown으로 저장하며, 이미지를 처리하는 방법을 배워보세요. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: ko +og_description: Aspose.Words for Java를 사용하여 docx를 markdown으로 변환할 때 이미지를 base64로 삽입합니다. + 워드를 markdown으로 변환하고 markdown으로 저장하는 완전 가이드. +og_title: DOCX를 Markdown으로 변환할 때 이미지를 Base64로 삽입 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: DOCX를 Markdown으로 변환할 때 이미지를 Base64로 삽입하기 +url: /ko/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX를 Markdown으로 변환할 때 이미지 Base64로 삽입하기 + +DOCX를 Markdown으로 변환하면서 **이미지를 Base64로 삽입**하는 방법이 궁금하셨나요? 여러분만 그런 것이 아닙니다—개발자들은 별도의 파일을 관리하지 않고 이미지를 인라인으로 유지하는 방법을 자주 묻습니다. 좋은 소식은 Aspose.Words for Java를 사용하면 손쉽게 Word 문서를 Markdown으로 변환하고 모든 그림을 자동으로 Base64 문자열로 삽입할 수 있다는 것입니다. + +이 튜토리얼에서는 그림이 포함된 `.docx` 파일을 로드하는 것부터, 무거운 작업을 수행하는 `MarkdownSaveOptions` 콜백을 설정하고, 최종적으로 결과를 깔끔한 `.md` 파일로 저장하는 전체 과정을 단계별로 살펴봅니다. 끝까지 읽으면 **word를 markdown으로 변환**, **이미지를 base64로 변환**, 그리고 **word를 markdown으로 저장**하는 방법을 정확히 알게 됩니다. 별도의 이미지 폴더가 남지 않으며, 외부 도구나 수동 후처리 없이 순수 Java 코드만으로 어떤 프로젝트에도 바로 적용할 수 있습니다. + +## 필요 사항 + +- **Java 17** (또는 최신 JDK) – 코드가 람다 구문을 사용하지만, 이전 버전에도 적용할 수 있습니다. +- **Aspose.Words for Java** 라이브러리 (2026년 현재 최신 버전). Maven 의존성을 추가하거나 JAR 파일을 클래스패스에 포함시키세요. +- 최소 하나의 이미지를 포함한 샘플 **DOCX** 파일. +- IDE 또는 간단한 텍스트 편집기—Visual Studio Code, IntelliJ IDEA, 혹은 `vim`도 충분합니다. + +이미 준비되었다면, 좋습니다—바로 시작해봅시다. + +## 단계 1: Word 문서 로드하기 + +먼저 소스 파일을 가리키는 `Document` 인스턴스를 생성합니다. 이는 **docx를 markdown으로 변환**하든, 파일을 다른 용도로 읽든 동일한 단계입니다. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **왜 중요한가:** `Document` 객체는 모든 Aspose 작업의 진입점입니다. 이미지, 표, 스타일 등을 포함한 전체 Word 구조를 보유하고 있어, 이후 콜백에서 각 리소스를 검사할 수 있습니다. + +## 단계 2: MarkdownSaveOptions 생성 및 Resource‑Saving 콜백 등록 + +`MarkdownSaveOptions`에 마법이 숨어 있습니다. `IResourceSavingCallback`을 연결하면 각 외부 리소스(예: 이미지)가 저장되는 방식을 제어할 수 있습니다. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: `setSaveToMemory(true)`를 사용하는 이유 + +`saveToMemory`가 true이면, Aspose는 이미지 바이트를 파일이 아닌 메모리 스트림에 기록합니다. 그 후 Markdown 내보내기 기능이 해당 스트림을 Base64 문자열로 변환하여 Markdown 이미지 태그에 직접 삽입합니다: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +이것이 **이미지를 Base64로 삽입**하는 핵심입니다. + +## 단계 3: 문서를 Markdown으로 저장하기 + +콜백이 설정되었으니, 마지막 단계는 간단히 `save`를 호출하는 것입니다. 여기서 실제로 **word를 markdown으로 변환**하고, 콜백 덕분에 **이미지를 base64로 변환**합니다. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **결과:** `out.md`에는 모든 이미지가 `data:` URI 형태로 표현된 Markdown 텍스트가 포함됩니다. 디스크에 별도의 이미지 파일이 생성되지 않아 폴더가 깔끔하게 유지됩니다. + +## 단계 4: 출력 확인 및 일반적인 함정 + +생성된 `out.md`를 any Markdown 뷰어(VS Code, GitHub, 정적 사이트 생성기 등)에서 열어보세요. 다음과 같은 내용이 표시될 것입니다: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### 문제 해결 체크리스트 + +| 문제 | 가능한 원인 | 해결 방법 | +|------|-------------|-----------| +| 이미지가 깨진 링크로 표시됨 | `setSaveToMemory`가 누락됨 | `args.setSaveToMemory(true);`가 콜백 안에 포함되어 있는지 확인하세요 | +| Base64 문자열이 잘림 | 출력 파일 인코딩 불일치 | Markdown을 UTF‑8( Aspose 기본값)로 저장하세요 | +| 예상치 못한 파일 이름 | `setKeepResourceOriginalName(true)` | `false`로 설정하여 사용자 지정 명명 로직을 강제하세요 | + +## 단계 5: 고급 변형 (선택 사항) + +### 선택된 이미지만 변환하기 + +특정 이미지(예: 100 KB 이상)만 삽입하고 싶다면, 크기 검사를 추가하세요: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### 다른 이미지 포맷 사용하기 + +`ResourceSavingArgs`는 원시 바이트를 제공하므로, 삽입하기 전에 JPEG를 PNG로 재인코딩할 수 있습니다—대상 Markdown 뷰어가 PNG를 선호할 때 유용합니다. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +이러한 조정은 **docx를 markdown으로 변환**할 때 **이미지를 Base64로 삽입** 접근 방식이 얼마나 유연한지 보여줍니다. + +## 결론 + +이제 Aspose.Words for Java를 사용하여 **docx를 markdown으로 변환**하면서 **이미지를 Base64로 삽입**하는 방법을 배웠습니다. 간단한 `IResourceSavingCallback`을 연결하면 라이브러리가 모든 복잡한 작업을 수행합니다: **word를 markdown으로 변환**, **이미지를 base64로 변환**, 그리고 최종적으로 단일 `save` 호출로 **word를 markdown으로 저장**합니다. + +자유롭게 실험해 보세요—다양한 이미지 필터링 규칙을 시도하거나 HTML 출력으로 전환하고, 이 단계를 정적 사이트 생성기와 연결할 수 있습니다. 동일한 패턴은 다른 포맷(HTML, EPUB)에도 적용 가능하므로, 인라인 리소스가 필요한 곳 어디에서든 콜백을 재사용할 수 있습니다. + +**다음 단계:** +- HTML‑with‑Base64 이미지를 위한 `HtmlSaveOptions` 탐색하기. +- CI 파이프라인과 결합하여 문서 생성을 자동화하기. +- 변환 프로세스를 보다 세밀하게 제어하려면 Aspose의 `DocumentVisitor`를 살펴보기. + +코딩을 즐기시고, 깔끔하고 자체 포함된 Markdown 파일을 만끽하세요! + +## 관련 튜토리얼 + +- [DOCX 변환 시 Markdown에 이미지 삽입 방법](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [docx를 markdown으로 변환 – Aspose.Words로 수식 내보내기(LaTeX)](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Word에서 이미지 저장 – Aspose.Words for Java 가이드](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/korean/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..5b6ab32381 --- /dev/null +++ b/words/korean/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: Java와 Aspose.Words를 사용하여 docx를 txt로 내보내기. docx를 텍스트로 변환하고, 유니코드를 보존하며, + 몇 단계만에 워드를 txt로 내보내는 방법을 배워보세요. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: ko +og_description: Java에서 docx를 txt로 내보내기. 이 튜토리얼은 docx를 텍스트로 변환하고, 평문 유니코드를 유지하며, 워드를 + 효율적으로 txt로 내보내는 방법을 보여줍니다. +og_title: Java로 docx를 txt로 내보내기 – 완전 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Java로 docx를 txt로 내보내기 – 완전 프로그래밍 가이드 +url: /ko/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java로 docx를 txt로 내보내기 – 완전 프로그래밍 가이드 + +특수 문자가 사라질까 걱정하면서 **export docx to txt**가 필요했던 적이 있나요? 당신만 그런 것이 아닙니다. Word 문서를 일반 텍스트 파일로 변환하면 Unicode 기호, 표, 심지어 간단한 서식까지 마법처럼 사라질 수 있습니다. + +이 가이드에서는 Aspose.Words for Java를 사용하여 **export docx to txt**를 신뢰할 수 있는 방법으로 진행하면서 모든 Unicode 글리프를 보존하고 표 레이아웃을 읽기 쉽게 유지하는 방법을 안내합니다. 끝까지 읽으면 **convert docx to text**, **convert word to text**, 그리고 **export word as txt**를 문제 없이 수행하는 방법도 알게 됩니다. + +## 이 튜토리얼에서 다루는 내용 + +* Java 프로젝트에 Aspose.Words 설정하기 +* DOCX 파일을 로드하고 일반 텍스트 출력 준비하기 +* `TxtSaveOptions`를 사용하여 **plain text unicode** 지원 구성하기 +* 결과 `.txt` 파일에서 표를 읽기 쉽게 유지하는 선택적 트릭 +* 파일 저장 및 출력 확인 + +외부 스크립트도, 신비한 명령줄 도구도 없습니다—그냥 Maven이나 Gradle 프로젝트에 바로 넣을 수 있는 순수 Java 코드만 있습니다. + +> **왜 신경 써야 할까요?** 일반 텍스트 파일은 가볍고 버전 관리에 친화적이며 검색 인덱싱이나 다운스트림 처리 파이프라인에 최적입니다. Word 파일을 `cat` 명령으로 열어봤는데 의미 없는 문자열이 나왔다면, 이 튜토리얼이 그 문제를 해결합니다. + +--- + +## Export docx to txt – 개요 + +코드에 들어가기 전에 용어를 정리해 봅시다. **Export docx to txt**는 Microsoft Word `.docx` 패키지를 가져와 그 텍스트 내용을 간단한 `.txt` 파일에 쓰는 것을 의미합니다. PDF 변환과 달리 텍스트 내보내기는 스타일을 제거하지만 줄 바꿈, 단락 표시, 그리고—올바르게 설정하면—이모지, 악센트가 있는 문자, 아시아 스크립트와 같은 Unicode 문자들을 유지할 수 있습니다. + +Aspose.Words는 Word 파일 형식을 추상화하고 인코딩, 표 처리 등을 지정할 수 있는 `TxtSaveOptions` 클래스를 제공하므로 이 작업이 간편합니다. + +### 전제 조건 + +* Java 11 이상 (API는 Java 8+에서도 작동하지만 최신 JDK를 가정합니다) +* Aspose.Words for Java JAR (Maven Central에서 제공) +* 다양한 Unicode 문자를 포함한 샘플 `unicode.docx` 파일—예: “こんにちは”, “😊”, 그리고 간단한 표 + +준비가 되었다면 시작해 봅시다. + +--- + +## Step 1: DOCX 파일 로드하기 (Convert docx to text) + +첫 번째로 해야 할 일은 소스 문서를 메모리로 읽어들이는 것입니다. 여기서 **convert docx to text** 프로세스가 공식적으로 시작됩니다. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*왜 중요한가:* `Document`는 Aspose.Words가 Word 파일을 나타내는 객체입니다. 이를 로드하면 모든 단락, 표, 숨겨진 요소까지 접근할 수 있습니다. 파일을 찾을 수 없으면 Aspose는 명확한 `FileNotFoundException`을 발생시켜 어떤 문제가 발생했는지 즉시 알 수 있습니다. + +--- + +## Step 2: Unicode용 TxtSaveOptions 설정하기 (Plain text unicode) + +일반 텍스트 파일은 단순히 바이트 스트림이므로 Java에 어떤 문자 집합을 사용할지 알려야 합니다. UTF‑8은 모든 Unicode 코드 포인트를 인코딩할 수 있기 때문에 **plain text unicode**의 사실상 표준입니다. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **팁:** `setEncoding` 호출을 생략하면 Aspose는 플랫폼의 기본 문자 집합을 사용합니다. 많은 Windows 머신에서는 기본이 Windows‑1252이며, 이 경우 “ß”나 “—”와 같은 문자가 조용히 사라집니다. + +--- + +## Step 3: 표 레이아웃 보존하기 (선택 사항이지만 가독성에 유용) + +**export word as txt**를 수행하면 표가 보통 한 줄의 텍스트로 평탄화되어 읽기 어려워집니다. Aspose.Words는 시각적 구조를 유지할 수 있는 간단한 플래그를 제공합니다. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*사용 시점:* 소스 DOCX에 청구서, 일정표 또는 그리드 형태 데이터가 포함되어 있다면 `PreserveTableLayout`을 활성화하면 탭과 줄 바꿈이 삽입되어 결과 파일이 여전히 표와 비슷하게 보입니다. 필요 없으면 해당 라인을 생략해 더 간결한 출력물을 얻을 수 있습니다. + +--- + +## Step 4: 문서를 일반 텍스트로 저장하기 (Export word as txt) + +이제 무거운 작업은 끝났으니 바이트를 디스크에 기록하면 됩니다. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +프로그램을 실행하면 같은 폴더에 `plain.txt`가 생성됩니다. Notepad++, VS Code, 심지어 터미널의 `cat` 등 어떤 텍스트 편집기로 열어도 다음과 같이 보일 것입니다: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +일본어 인사와 이모지가 그대로 유지되고, `PreserveTableLayout` 덕분에 표가 열을 유지한 것을 확인하세요. 이것이 깔끔한 **export docx to txt**의 핵심입니다. + +--- + +## Step 5: 출력 확인하기 (Convert word to text sanity check) + +간단한 검증을 통해 무언가가 조용히 손실되는 것을 방지할 수 있습니다. 다음은 **convert word to text**가 올바르게 수행됐는지 확인하는 몇 가지 방법입니다: + +1. **Checksum 비교** – 라운드 트립 변환 (txt → docx → txt) 전후에 `.txt` 파일의 SHA‑256 해시를 계산해 안정성을 확인합니다. +2. **Unicode 마커 검색** – `grep`이나 IDE의 파일 내 찾기 기능을 사용해 “😊”와 같은 문자를 찾습니다. +3. **여러 편집기에서 열기** – 일부 오래된 Windows Notepad는 BOM 없이 UTF‑8을 잘못 해석할 수 있습니다; VS Code에서 열어 보면 인코딩이 올바른지 확인할 수 있습니다. + +이 중 하나라도 실패하면 `saveOptions.setEncoding(StandardCharsets.UTF_8)`가 설정되어 있는지, 그리고 소스 DOCX에 실제로 Unicode 텍스트가 포함되어 있는지 다시 확인하세요. + +--- + +## 일반적인 함정 및 회피 방법 + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **문자 누락** | 기본 시스템 문자 집합(예: Windows‑1252)이 ASCII가 아닌 글리프를 삭제합니다. | `saveOptions.setEncoding`을 사용해 명시적으로 UTF‑8을 설정합니다. | +| **표가 한 줄로 변환** | `PreserveTableLayout`이 기본값 `false`로 남아 있습니다. | `saveOptions.setPreserveTableLayout(true)`를 호출합니다. | +| **파일을 찾을 수 없음** | 경로가 잘못되었거나 읽기 권한이 없습니다. | 절대 경로를 사용하거나 적절한 예외 처리를 포함한 `Paths.get(...)`를 사용합니다. | +| **대용량 문서에서 성능 저하** | 전체 문서를 메모리로 로드하기 때문입니다. | 특정 섹션만 필요하다면 `DocumentBuilder`를 사용해 문서를 청크 단위로 스트리밍합니다. | + +--- + +## 보너스: 여러 DOCX 파일을 배치로 내보내기 + +전체 폴더에 대해 **convert docx to text**가 필요하다면, 로직을 루프로 감싸세요: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +이 스니펫은 디렉터리의 모든 파일에 대해 **export docx to txt**를 수행하여 수작업 시간을 크게 절감합니다. + +--- + +## 결론 + +당신은 이제 Java로 **export docx to txt**하는 방법을 배웠으며, 모든 Unicode 문자를 그대로 유지하고, 표를 읽기 가능하게 하며, 전체 프로세스를 반복 가능하게 만들었습니다. `TxtSaveOptions`를 UTF‑8로 설정하고 필요에 따라 표 레이아웃을 보존함으로써, 어떤 다운스트림 워크플로우에서도 신뢰성 있게 **convert docx to text**, **convert word to text**, 그리고 **export word as txt**를 수행할 수 있습니다. + +다음 도전에 준비가 되셨나요? 마크다운(`.md`)이나 CSV와 같은 다른 일반 텍스트 형식으로 내보내기를 시도하거나 Aspose.Words의 PDF 변환 기능을 살펴보세요. 명시적 인코딩, 레이아웃 보존, 철저한 검증이라는 동일한 원칙이 모든 경우에 적용됩니다. + +코딩을 즐기세요, 그리고 여러분의 텍스트 파일이 언제나 Unicode‑풍부하게 유지되길 바랍니다! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + +## 관련 튜토리얼 + +- [Docx를 Txt로 변환](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Java에서 DOCX를 PDF로 변환](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Docx를 마크다운으로 변환 – Aspose.Words로 수학 방정식을 LaTeX로 내보내기](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/korean/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..30138bf581 --- /dev/null +++ b/words/korean/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words Java를 사용하여 문서를 PDF로 저장하고 PDF에 접근성을 추가합니다. docx를 PDF로 변환하고, + 수평선을 태그하며, PDF/UA‑2 준수를 보장하는 방법을 배워보세요. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: ko +og_description: Aspose.Words Java를 사용하여 문서를 PDF로 저장하면서 접근성을 추가합니다. docx를 PDF로 변환하고 + PDF/UA‑2 준수를 위해 가로 구분선을 태그하는 단계별 가이드. +og_title: Aspose.Words Java로 문서를 PDF로 저장 – 접근성을 쉽게 구현 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Aspose.Words Java를 사용하여 문서를 PDF로 저장하기 – 완전한 접근성 가이드 +url: /ko/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words Java로 문서를 PDF로 저장 – 전체 접근성 가이드 + +스크린 리더에서도 접근 가능하도록 **문서를 PDF로 저장**하는 방법이 궁금하셨나요? 혼자가 아닙니다. 많은 개발자들이 *docx를 pdf로 변환*하면서도 PDF/UA‑2 표준을 충족해야 합니다, 특히 소스에 수평 구분선이 포함되어 올바르게 태그되어야 할 때. 이 튜토리얼에서는 Aspose.Words for Java를 사용해 **문서를 PDF로 저장**하고 자동으로 **PDF에 접근성 추가**, 그리고 모든 수평 구분선을 **artifact**로 **태그**하는 정확한 단계를 안내합니다. + +우리는 깨끗한 Java 프로젝트를 시작하고, 이미 수평 구분선이 포함된 DOCX를 로드한 뒤, PDF/UA‑2 준수를 위한 PDF 저장 옵션을 구성하고, 최종적으로 완전한 접근성 PDF를 작성합니다. 끝까지 진행하면 **문서를 pdf로 저장**하면서 접근성 검사를 통과한다는 확신을 가질 수 있습니다. + +## 사전 요구 사항 + +- Java 8 이상 설치 (튜토리얼은 JDK 17에서 테스트되었습니다). +- Maven 3.6+ (또는 선호한다면 Gradle)로 의존성 관리. +- 유효한 Aspose.Words for Java 라이선스 (무료 체험판도 동작하지만, 라이선스를 적용하면 평가 워터마크가 제거됩니다). +- 최소 하나의 수평 구분선이 포함된 DOCX 파일 (`input.docx`) – Word에서 추가하는 간단한 선 구분자를 생각해 보세요. + +> **Pro tip:** DOCX 파일이 없으면 새 Word 문서를 만들고, 몇 개의 단락을 입력한 뒤 *Insert → Horizontal Line*을 삽입하고 `input.docx`로 저장한 뒤 원하는 폴더에 배치하면 됩니다. + +## 단계 1: Maven 프로젝트 설정 + +먼저 새 Maven 프로젝트를 만들거나 기존 프로젝트에 추가합니다. `pom.xml`에 Aspose.Words 의존성을 추가해야 합니다: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** `aspose-words` 아티팩트를 추가하는 것은 *convert docx to pdf*의 첫 번째 단계입니다. 이 없이는 컴파일러가 `Document`, `PdfSaveOptions` 및 기타 핵심 클래스를 인식하지 못합니다. + +## 단계 2: 수평 구분선이 포함된 원본 DOCX 로드 + +이제 DOCX를 로드하는 작은 Java 클래스를 작성합니다. 여기서 **tag horizontal rules** 작업이 시작됩니다—Aspose.Words는 수평 구분선을 테두리가 있는 단락으로 자동 처리하지만, PDF/UA 엔진이 태깅을 담당하도록 합니다. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +아직 아무것도 저장하지 않았습니다—우리는 **DOCX를 로드**하고 있을 뿐이며, 이는 *convert docx to pdf*의 첫 번째 절반에 해당합니다. `Document` 객체는 이제 삽입한 모든 Word 콘텐츠와 수평 구분선을 포함하고 있습니다. + +## 단계 3: PDF/UA‑2 준수를 위한 PDF 저장 옵션 구성 + +**add accessibility to PDF**의 마법은 `PdfSaveOptions`에 있습니다. 준수 수준을 `PDF_UA_2`로 설정하면 Aspose.Words는 다음을 수행합니다: + +1. 구조 요소(제목, 표 등)를 태그합니다. +2. 수평 구분선과 같은 장식 요소를 *artifact*로 표시하여 스크린 리더가 무시하도록 합니다. +3. 필요한 PDF/UA 메타데이터를 삽입합니다. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** `PDF_UA_2`가 없으면 결과 PDF는 읽을 수는 있지만 자동 접근성 검증을 통과하지 못합니다. **tag horizontal rules** 요구 사항은 준수 플래그가 켜져 있을 때 PDF/UA가 자동으로 *artifact*로 처리하므로 자동으로 만족됩니다. + +## 단계 4: 문서를 PDF로 저장 + +이제 드디어 **save document as pdf**를 수행합니다. 이 한 줄이 변환, 접근성 태그 적용, 파일 디스크 쓰기 등 모든 무거운 작업을 수행합니다. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +클래스를 실행합니다(`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`)하면 확인 메시지가 표시됩니다. 생성된 `ua_compliant.pdf`를 Adobe Acrobat에서 열고 **File → Properties → Description → PDF/A, PDF/UA**를 확인하면 “PDF/UA‑2”가 표시됩니다. + +### Expected Output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +PDF를 열면 다음을 확인할 수 있습니다: + +- 문서 텍스트가 선택 가능하고 검색 가능합니다. +- 수평선은 스크린 리더에 보이지 않으며 (artifact로 처리됩니다). +- PDF가 기본 PDF/UA 검증 도구(e.g., PAC 3)를 통과합니다. + +## 단계 5: 접근성 검증 – 빠른 체크리스트 + +Aspose.Words가 대부분의 작업을 수행하지만, 출력물을 검증하는 것이 좋은 습관입니다. + +| 체크 | 검증 방법 | +|-------|----------------| +| **문서 제목** | Acrobat → File → Properties → Title 필드 확인 (`pdfOptions.setTitle`과 일치해야 함). | +| **Artifact 태깅** | Acrobat의 “Reading Order” 도구 사용. 수평 구분선이 *Artifact* (회색)으로 표시되어야 함. | +| **논리적 읽기 순서** | Acrobat에서 “Accessibility Checker” 실행; 구조 오류가 없어야 함. | +| **Tagged PDF** | Acrobat의 “Tags” 패널 확인 – Document → Section → Paragraph 등 계층 구조가 보여야 함. | +| **PDF/UA 준수** | Acrobat의 “Standards” 탭에 “PDF/UA‑2”가 표시되는지 확인. | + +이 중 하나라도 실패하면 최신 Aspose.Words 버전을 사용했는지, `setCompliance(PdfCompliance.PDF_UA_2)`가 올바르게 적용됐는지 다시 확인하세요. + +## Common Pitfalls & How to Avoid Them + +1. **Missing License** – 체험판은 워터마크를 추가해 PDF/UA 검증을 깨뜨릴 수 있습니다. `main` 초기에 라이선스를 적용하세요: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException`이 발생하면 변환이 중단됩니다. 절대 경로를 사용하거나 프로젝트 루트에 DOCX를 두고 `new File("input.docx").getAbsolutePath()`로 참조하세요. +3. **Using Older Aspose Version** – PDF/UA 지원은 버전 22.9에서 추가되었습니다. 최신 릴리스를 업그레이드하여 누락된 기능을 방지하세요. +4. **Horizontal Rule as Image** – 선을 이미지로 삽입하면 Aspose는 일반 이미지로 처리해 artifact가 되지 않습니다. Word의 기본 *Horizontal Line*을 사용해 올바르게 태깅되도록 교체하세요. + +## Extending the Solution – What If You Need More? + +- **Custom Tags**: 다른 장식 요소(예: 장식 아이콘)가 있으면 `PdfSaveOptions.setArtifactTaggingEnabled(true)`를 사용해 수동으로 artifact로 표시할 수 있습니다. +- **Multiple Documents**: DOCX 파일이 들어 있는 폴더를 순회하며 배치 변환하고, 성능을 위해 동일한 `PdfSaveOptions` 인스턴스를 재사용합니다. +- **Adding a Language Tag**: 다국어 PDF의 경우 `pdfOptions.setLanguage("en-US")`를 설정해 보조 기술이 올바른 음성을 선택하도록 돕습니다. + +## Full Working Example (All Code Together) + +아래는 완전한 실행 가능한 Java 프로그램입니다. IDE에 복사‑붙여넣기하고 경로를 조정한 뒤 실행하세요. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +실행하고 생성된 PDF를 열면 배포 준비가 된 깔끔하고 접근 가능한 파일을 얻을 수 있습니다. + +## Conclusion + +우리는 Aspose.Words for Java를 사용해 **save document as pdf**하면서 자동으로 **add accessibility to pdf**하고 **tag horizontal rules**를 artifact로 처리하는 방법을 시연했습니다. 주요 포인트는 다음과 같습니다: + +- `PdfSaveOptions`에 `PDF_UA_2` 준수를 설정해 접근성 표준을 만족합니다. +- DOCX를 로드하고 `doc.save(..., pdfOptions)`를 호출하면 **convert docx to pdf**에 필요한 모든 작업이 완료됩니다. +- 수평 구분선은 자동으로 처리되어 별도 코드가 필요 없으며, **tag horizontal rules** 요구 사항을 충족합니다. +- 이 접근 방식은 완전한 **aspose convert docx pdf** 호환성을 제공하며 최신 라이브러리 버전에서 동작하고 검증 준비가 된 PDF를 생성합니다. + +다음 도전 과제가 준비되셨나요? 사용자 정의 메타데이터 추가, 글꼴 임베드, 혹은 전체 DOCX 폴더를 배치 처리해 보세요. 여기서 소개한 기반 위에 모든 확장이 구축됩니다. + +PDF/UA 준수, 라이선스, 기타 Word 요소 처리에 대한 질문이 있나요? 댓글을 남기거나 Aspose 공식 문서를 확인하세요—다양한 예제가 준비되어 있습니다. 즐거운 코딩 되시고, 접근 가능한 PDF 만들기를 즐기세요! + +![Aspose.Words Java를 사용하여 문서를 PDF로 저장 – 접근 가능한 PDF 예시](placeholder-image.png "Aspose.Words Java를 사용하여 문서를 PDF로 저장 – 접근 가능한 PDF 예시") + +## Related Tutorials + +- [Aspose.Words for Java로 문서를 PDF로 저장하는 방법](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Aspose.Words for Java를 사용해 Word를 PDF로 변환하는 방법](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Java에서 DOCX를 PDF로 변환](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/korean/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..ee4dab9863 --- /dev/null +++ b/words/korean/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-05-26 +description: Word를 마크다운으로 저장하고 Aspose.Words for Java를 사용하여 수학 방정식을 LaTeX로 내보내는 방법을 + 알아보세요. 몇 줄만으로 Word 방정식을 LaTeX로 변환합니다. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: ko +og_description: Aspose.Words for Java를 사용하여 워드를 마크다운으로 저장하고 수학 방정식을 LaTeX로 내보내는 방법을 + 배워보세요. 완전하고 실행 가능한 가이드. +og_title: 워드를 마크다운으로 저장 – Java로 수학을 LaTeX로 내보내기 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: 워드를 마크다운으로 저장 – Java로 수학을 LaTeX로 내보내기 +url: /ko/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 워드 파일을 마크다운으로 저장 – Java로 수학을 LaTeX로 내보내기 + +Ever needed to **save word as markdown** but worried your equations would turn into a garbled mess? You're not alone. In this guide we’ll walk through **how to export math** from a `.docx` file straight into LaTeX while the rest of the document becomes clean Markdown. + +워드를 마크다운으로 저장해야 할 때, 수식이 엉망이 될까 걱정한 적이 있나요? 혼자가 아닙니다. 이 가이드에서는 `.docx` 파일에서 수식을 바로 LaTeX로 **내보내는 방법**을 살펴보면서 문서의 나머지 부분은 깔끔한 마크다운이 되도록 합니다. + +We’ll cover everything from setting up the Aspose.Words library to verifying the final `out.md` file. By the end you’ll be able to **convert word equations latex** in a single method call, and you’ll understand the little nuances that make the conversion reliable. + +우리는 Aspose.Words 라이브러리 설정부터 최종 `out.md` 파일 검증까지 모두 다룰 것입니다. 끝까지 읽으면 단일 메서드 호출로 **워드 수식을 LaTeX로 변환**할 수 있게 되고, 변환을 안정적으로 만드는 작은 차이점들을 이해하게 됩니다. + +--- + +## 필요 사항 + +- **Java 8+** – 코드는 최신 JDK에서 실행됩니다. +- **Aspose.Words for Java** – Maven/Gradle 의존성이나 수동 설정을 원한다면 JAR 파일을 사용할 수 있습니다. +- 최소 하나의 Office Math 수식이 포함된 워드 문서 (`math.docx`). +- 익숙한 IDE 또는 일반 `javac`/`java` 명령줄. + +이미 준비되어 있다면 좋습니다. 그렇지 않다면, 다음 섹션에서 라이브러리를 프로젝트에 추가하는 방법을 정확히 보여줍니다. + +## 워드 파일을 마크다운으로 저장 – 단계 1: 프로젝트에 Aspose.Words 추가 + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose는 테스트용 무료 임시 라이선스를 제공합니다. `license.xml` 파일을 리소스 폴더에 넣고 문서를 로드하기 전에 `License license = new License(); license.setLicense("license.xml");` 를 호출하세요. + +의존성이 해결되면 변환 코드를 작성할 준비가 된 것입니다. + +## 수학 수식을 LaTeX로 내보내는 방법 + +`MarkdownSaveOptions`가 핵심 역할을 합니다. `OfficeMathExportMode`를 `LATEX`로 전환하면 모든 Office Math 객체가 마크다운 출력 안에 LaTeX 조각으로 렌더링됩니다. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### 왜 이렇게 동작하는가 + +- **`Document`**는 Aspose의 진입점으로, `.docx` 파일을 추상화하고 수식을 포함한 모든 노드에 접근할 수 있게 합니다. +- **`MarkdownSaveOptions`**는 라이브러리에 출력 *방법*을 알려줍니다. 기본 동작은 수식을 이미지로 렌더링하는데, 이는 텍스트 기반 형식의 목적에 어긋납니다. +- **`OfficeMathExportMode.LATEX`**는 엔진이 각 `OfficeMath` 노드를 LaTeX 형태로 변환하도록 강제하며, 이렇게 변환된 LaTeX는 MathJax 플러그인과 함께 사용할 때 GitHub나 Jekyll 같은 마크다운 파서가 렌더링할 수 있습니다. + +## 워드 수식을 LaTeX로 변환 – 단계 2: 마크다운 출력 검증 + +프로그램을 실행한 후 `out.md`를 열어보세요. 다음과 같은 내용이 보일 것입니다: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** LaTeX 조각은 인라인 수식은 `$…$` 로, 블록 수식은 `$$…$$` 로 감싸집니다. 이는 MathJax가 활성화된 대부분의 정적 사이트 생성기가 이해하는 표준 문법입니다. + +수식을 인라인만 유지하고 싶다면 `MarkdownSaveOptions`를 추가로 조정할 수 있습니다: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx를 마크다운 LaTeX로 변환 – 단계 3: 엣지 케이스 및 일반적인 함정 + +| 상황 | 주의할 점 | 해결 방법 | +|-----------|-------------------|-----| +| **복잡한 중첩 수식** | Aspose가 일부 파서가 문자 그대로 해석하는 추가 중괄호 `{}` 를 출력할 수 있습니다. | 간단한 정규식으로 `{{` → `{` 로 축소하여 마크다운을 후처리합니다. | +| **대상 사이트에 MathJax가 없음** | 수식이 원시 LaTeX 코드로 표시됩니다. | HTML 템플릿에 `` 를 추가하세요. | +| **대용량 문서** | 전체 문서를 한 번에 로드하기 때문에 메모리 사용량이 급증합니다. | `LoadOptions.setLoadFormat(LoadFormat.DOCX)` 를 사용하고 `OutOfMemoryError` 가 발생하면 페이지를 배치 처리하는 것을 고려하세요. | +| **라이선스 미설정** | 경고가 표시되고 출력에 워터마크가 붙을 수 있습니다. | 위 Maven 팁에 나온 대로 `main` 초기에 라이선스를 로드하세요. | + +## 워드 파일을 마크다운으로 저장 – 전체 작업 예제 + +아래는 어떤 Java 프로젝트에도 복사‑붙여넣기 할 수 있는 독립형 클래스입니다. `YOUR_DIRECTORY` 를 파일 경로로 교체하면 됩니다. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +프로그램을 실행(`java MathToLatexMarkdown`)하면 성공을 알리는 콘솔 메시지가 표시됩니다. 아무 편집기에서든 `out.md`를 열면 수식이 렌더링 준비가 된 깔끔한 LaTeX 스니펫으로 나타납니다. + +## 예상 출력 스냅샷 + +![LaTeX 수식이 포함된 워드 파일을 마크다운으로 저장한 출력](https://example.com/images/markdown-latex-output.png "LaTeX 수식이 포함된 워드 파일을 마크다운으로 저장한 출력") + +*이미지는 생성된 마크다운의 일부를 보여주며, 수식 `\int_{a}^{b} f(x)\,dx` 가 `$$` 로 감싸져 있음을 나타냅니다.* + +## 결론 + +우리는 **워드를 마크다운으로 저장**하면서 모든 Office Math 수식을 원시 LaTeX로 보존하는 방법을 보여주었습니다. 핵심 단계는 `MarkdownSaveOptions`를 `OfficeMathExportMode.LATEX` 로 설정하는 것이었으며, 이는 일반적인 Word‑to‑Markdown 파이프라인을 완전한 수학 인식 변환 도구로 바꿉니다. + +이제 할 수 있습니다: + +1. **How to export math**를 사용해 어떤 `.docx`에서도 정확도를 잃지 않고 내보낼 수 있습니다. +2. **Convert word equations latex**를 정적 사이트 생성기, 문서, 학술 블로그용으로 수행합니다. +3. 이 접근 방식을 확장하여 다수의 파일을 배치 처리하고, CI 파이프라인에 통합하거나 작은 웹 서비스를 구축할 수 있습니다. + +다음 단계에 관심이 있다면 이미지가 많은 문서에 대해 **docx to markdown latex**와 결합해 보거나, 웹용 HTML 버전을 위해 Aspose의 `HtmlSaveOptions`를 탐색해 보세요. 가능성은 무한합니다—실험하고, 문제를 일으키고, 그 결과를 커뮤니티와 공유하세요. + +궁금한 점이나 예상대로 렌더링되지 않은 복잡한 수식이 있나요? 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +## 관련 튜토리얼 + +- [워드에서 LaTeX 내보내기: DOCX를 마크다운으로 변환 및 PDF로 저장](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [docx를 마크다운으로 변환 – Aspose.Words로 수학 수식을 LaTeX로 내보내기](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Aspose.Words for Java를 사용해 워드를 PDF로 변환하는 방법](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/korean/java/document-loading-and-saving/_index.md index 9a3cc05f19..56081fd5c0 100644 --- a/words/korean/java/document-loading-and-saving/_index.md +++ b/words/korean/java/document-loading-and-saving/_index.md @@ -99,6 +99,7 @@ Aspose.Words for Java의 다재다능함을 살펴보며 다양한 형식으로 ### [Aspose.Words for Java에서 문서 형식 판별](./determining-document-format/) ### [손상된 docx 복구 – 문서 복구 및 처리 완전 가이드](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) ### [Java에서 Aspose.Words로 글꼴 대체 경고 캡처 – 완전 가이드](./capture-font-substitution-warnings-in-java-with-aspose-words/) +### [손상된 Word 문서 열기 – Java에서 복구 모드 설정](./open-corrupted-word-document-set-recovery-mode-in-java/) ## 자주 묻는 질문 diff --git a/words/korean/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/korean/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..24285aa4c6 --- /dev/null +++ b/words/korean/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words를 사용하여 Java에서 손상된 Word 문서를 엽니다. 복구 모드를 설정하고 손상된 Word 파일을 + 신뢰성 있게 복구하는 방법을 배워보세요. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: ko +og_description: Aspose.Words를 사용하여 Java에서 손상된 Word 문서를 엽니다. 이 가이드는 복구 모드를 설정하고 손상된 + Word 파일을 효율적으로 복구하는 방법을 보여줍니다. +og_title: 손상된 워드 문서 열기 – Java에서 복구 모드 설정 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: 손상된 워드 문서 열기 – Java에서 복구 모드 설정 +url: /ko/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 손상된 Word 문서 열기 – Java에서 복구 모드 설정 + +손상된 Word 문서를 열어보고 프로그램이 예외로 중단되는 것을 본 적이 있나요? 당신만 그런 것이 아닙니다—그런 .docx 파일은 정말 골칫거리일 수 있습니다. 좋은 소식은 Aspose.Words for Java가 세밀한 제어를 제공하여 **open corrupted word document** 없이 앱이 충돌하지 않게 하고, 경고를 표시할지, 조용히 복구할지, 혹은 강제 거부할지를 결정할 수 있다는 것입니다. + +이 튜토리얼에서는 전체 과정을 단계별로 살펴보겠습니다: 올바른 `LoadOptions` 생성, 적절한 **set recovery mode** 값 선택, 그리고 문서가 실제로 로드되었는지 확인합니다. 마지막까지 진행하면 **how to recover corrupted word file**을 프로그래밍 방식으로 수행하는 방법을 알게 되며, 수동 복사‑붙여넣기는 필요하지 않습니다. + +> **필요한 사항** +> * Java 8 이상 (API는 Java 11 에서도 작동) +> * Aspose.Words for Java 23.9 (또는 최신 버전) +> * 샘플 손상된 .docx 파일 — 손상된 파일이 없으면 유효한 파일을 이름만 바꿔서 시뮬레이션할 수 있습니다 + +시작해 보겠습니다. + +## 손상된 Word 문서 열기 – 단계별 개요 + +아래는 구현할 고수준 흐름입니다: + +1. **Create `LoadOptions`** – 이 객체는 Aspose.Words가 문제를 만나면 어떻게 행동할지를 알려줍니다. +2. **Set recovery mode** – `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, 또는 `REJECT_CORRUPTED` 중 하나를 선택합니다. +3. **Load the document** using the configured options. +4. **Verify** the load succeeded (예: 페이지 수 출력). + +각 단계는 자세히 설명되며, IDE에 바로 복사‑붙여넣기 할 수 있는 코드 스니펫이 포함됩니다. + +## 다양한 시나리오를 위한 복구 모드 설정 + +Aspose.Words는 `LoadOptions.RecoveryMode` 안에 세 가지 복구 전략을 정의합니다: + +| 모드 | 동작 | 사용 시기 | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | 문서를 로드하려 시도하지만, 발생한 문제를 콘솔에 경고로 표시합니다. | 중단 없이 *무엇이* 잘못됐는지 보고 싶을 때 | +| `RECOVER_WITHOUT_WARNINGS` | 가능한 부분을 조용히 복구하고 경고를 억제합니다. | 로그를 깔끔하게 유지해야 하는 프로덕션 환경 | +| `REJECT_CORRUPTED` | 손상이 감지되는 즉시 예외를 발생시킵니다. | 빠르게 실패해야 하는 엄격한 검증 파이프라인 | + +올바른 모드를 선택하는 것이 **set recovery mode**를 정확히 설정하는 핵심입니다. 대부분의 디버깅 세션에서는 `RECOVER_WITH_WARNINGS`가 최적이며, 어떤 부분이 복구되었는지 정확히 알려줍니다. + +## Aspose.Words를 사용하여 손상된 Word 파일 복구하기 + +아래는 전체 실행 가능한 Java 프로그램 **전체 실행 가능한 Java 프로그램**의 예시입니다. `RecoveryModeDemo.java` 파일에 붙여넣고, 경로만 조정한 뒤 실행해 보세요. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### 각 라인의 의미 + +* **`LoadOptions loadOptions = new LoadOptions();`** – 이 객체가 없으면 Aspose.Words는 기본 복구 방식을 사용해 손상된 파일을 *거부*합니다. 객체를 생성하면 동작을 변경할 수 있는 후크가 생깁니다. +* **`setRecoveryMode(...)`** – 경고를 표시할지, 숨길지, 혹은 예외를 발생시킬지를 결정하는 **set recovery mode** 호출입니다. +* **`new Document(path, loadOptions);`** – 생성자는 방금 설정한 `LoadOptions`를 받아들여, 라이브러리가 처음부터 손상된 파일을 어떻게 처리할지 알게 됩니다. +* **`doc.getPageCount()`** – 간단한 정상 확인. 문서가 로드되고 페이지 수가 반환되면 **how to recover corrupted word file**에 성공한 것입니다. +* **`doc.save(...)`** – 선택 사항이지만 유용합니다; 복구된 버전을 디스크에 저장해 나중에 사용할 수 있습니다. + +## 일반적인 엣지 케이스 처리 + +### 1. 파일을 찾을 수 없음 + +경로가 잘못되면 `Document`가 `FileNotFoundException`을 발생시킵니다. 로드를 try‑catch 블록으로 감싸고 친절한 메시지를 로그에 남기세요: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. 복구 불가능한 손상 + +`RECOVER_WITH_WARNINGS`를 사용하더라도 일부 구조는 복구할 수 없습니다. 이 경우 Aspose.Words는 가능한 부분만 로드하지만 “Cannot read paragraph properties”와 같은 경고가 콘솔에 표시됩니다. 이러한 경고는 누락된 섹션을 수동으로 재구성해야 할 가능성을 알려줍니다. + +### 3. 대용량 파일 및 성능 + +복구 과정은 파일을 두 번 파싱하기 때문에 약간의 오버헤드가 발생합니다—한 번은 문제를 감지하고, 다시 한 번은 재구성합니다. 수기가바이트 규모의 문서라면 파일 스트리밍을 고려하거나 JVM 힙을 (`-Xmx2g`) 늘려 `OutOfMemoryError`를 방지하세요. + +## 전문가 팁 – 복구를 견고하게 만들기 + +* **경고를 파일에 기록** – `System.err`를 로거로 리다이렉트해 어떤 부분이 수정됐는지 감사 로그를 남깁니다. +* **복구 후 검증** – `doc.updatePageLayout();`을 실행한 뒤 페이지 수를 다시 확인합니다; 깨진 섹션을 고친 뒤 레이아웃이 변경될 수 있습니다. +* **배치 복구 자동화** – 데모 코드를 루프로 감싸 폴더에 있는 손상된 파일들을 한 번에 처리하고, 매번 동일한 `LoadOptions`를 재사용합니다. + +## 결론 + +이제 Aspose.Words for Java를 사용해 **how to recover corrupted word file**을 정확히 수행하는 방법을 알게 되었습니다. `LoadOptions` 인스턴스를 만들고, 상황에 맞는 **set recovery mode**를 설정한 뒤 해당 옵션으로 문서를 로드하면 애플리케이션이 중단되지 않고 **open corrupted word document**를 열 수 있습니다. 위 샘플 코드는 페이지 수를 출력하고 정리된 복사본을 저장하는 완전한 실행 가능한 솔루션입니다. + +다음은? 복구 모드를 `RECOVER_WITHOUT_WARNINGS`로 바꿔 콘솔 출력을 비교해 보거나, 암호화된 문서를 로드해 보는 실험을 해보세요(비밀번호는 ... + +## 관련 튜토리얼 + +- [Aspose.Words Java: Word 문서 처리 종합 가이드](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Aspose.Words for Java를 사용하여 Word를 PDF로 변환하는 방법](/words/english/java/document-converting/using-document-converting/) +- [Aspose.Words for Java로 두 Word 파일 비교하는 방법](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/korean/java/document-styling/_index.md index e168c93c9f..f2ca35ea4c 100644 --- a/words/korean/java/document-styling/_index.md +++ b/words/korean/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aspose.Words for Java를 사용하여 문서 테마를 사용자 지정하는 Aspose.Words for Java를 사용하여 워터마크를 적용하고 페이지 구성을 설정하는 방법을 알아보세요. 소스 코드가 포함된 종합 가이드입니다. ### [문서 머리글 및 바닥글 스타일](./document-header-footer-styling/) 이 자세한 가이드에서 Aspose.Words for Java를 사용하여 문서 머리글과 바닥글의 스타일을 지정하는 방법을 알아보세요. 단계별 지침과 소스 코드가 포함되어 있습니다. +### [Aspose.Words for Java에서 기본 글꼴 설정 – 완전 가이드](./set-default-font-settings-in-aspose-words-for-java-complete/) +Aspose.Words for Java를 사용해 문서의 기본 글꼴을 설정하고 적용하는 방법을 단계별 예제로 확인하세요. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/korean/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..f30de69759 --- /dev/null +++ b/words/korean/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java에서 기본 글꼴 설정을 지정하고, 몇 줄의 코드만으로 글꼴 설정 방법과 누락된 글꼴을 + 감지하는 방법을 배워보세요. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: ko +og_description: Aspose.Words for Java에서 기본 글꼴 설정을 지정하고, 글꼴 설정 방법과 누락된 글꼴을 빠르고 신뢰성 + 있게 감지하는 방법을 배우세요. +og_title: Aspose.Words for Java에서 기본 글꼴 설정하기 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Aspose.Words for Java에서 기본 글꼴 설정하기 – 완전 가이드 +url: /ko/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words for Java에서 기본 글꼴 설정 지정 – 완전 가이드 + +Aspose.Words for Java로 Word 문서를 로드할 때 **기본 글꼴 설정을 지정**하는 방법이 궁금하셨나요? 혼자만 그런 것이 아닙니다. 누락된 글리프는 깔끔한 보고서를 엉망진창으로 만들 수 있으며, 글꼴 대체 경고를 일찍 포착하면 디버깅 시간을 크게 절약할 수 있습니다. + +이 튜토리얼에서는 **기본 글꼴 설정을 지정**하는 간결한 엔드‑투‑엔드 예제를 단계별로 살펴보고, 프로그래밍 방식으로 **글꼴 설정을 지정**하는 방법을 보여주며, 레이아웃이 깨지기 전에 **누락된 글꼴을 감지**하는 신뢰할 만한 방법을 시연합니다. + +--- + +## 배울 내용 + +- `LoadOptions` 객체를 새 `FontSettings` 인스턴스로 생성하는 방법. +- 문서 로드 중 **누락된 글꼴을 감지**하는 경고 리스너를 연결하는 방법. +- 리스너가 대체를 조용히 보고하도록 하면서 DOCX 파일을 로드하는 방법. +- 프로덕션 환경에서 폴백 글꼴을 사용자 정의하고 엣지 케이스를 처리하는 팁. + +추가 라이브러리나 복잡한 설정 파일이 필요 없습니다—그냥 순수 Java와 Aspose.Words만 있으면 됩니다. + +--- + +## 사전 요구 사항 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +1. **Aspose.Words for Java** (버전 23.10 이상) 를 클래스패스에 포함. +2. Java 17(또는 그 이상) 개발 키트 – 최신 JDK라면 모두 사용 가능. +3. 설치되지 않은 글꼴을 의도적으로 사용하는 DOCX 파일 (예: *“MissingFont.ttf”*). + +Aspose JAR가 없으시면 공식 Maven 저장소에서 받아오세요: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +이것으로 끝—데모를 위해 추가 글꼴을 설치할 필요가 없습니다. + +--- + +## 단계 1: LoadOptions 생성 및 **기본 글꼴 설정 지정** + +먼저 필요한 것은 알 수 없는 서체를 만나면 Aspose가 어떻게 동작할지 알려주는 깨끗한 `LoadOptions` 객체입니다. `setFontSettings(new FontSettings())`를 호출하면 빈 폴백 목록으로 시작하는 **기본 글꼴 설정을 지정**하게 됩니다. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **왜 중요한가:** +> 글꼴을 명시적으로 설정하지 않으면 Aspose가 시스템 기본 컬렉션을 폴백으로 사용하게 되며, 이 경우 누락된 글꼴 문제가 가려질 수 있습니다. 새 `FontSettings` 인스턴스로 시작하면 유효한 글꼴을 완전히 제어할 수 있습니다. + +--- + +## 단계 2: **누락된 글꼴을 감지**하기 위한 경고 리스너 연결 + +Aspose는 수행하는 각 대체에 대해 `WarningInfo` 객체를 발생시킵니다. `WarningType.FONT_SUBSTITUTION`을 청취하면 문서가 파싱되는 즉시 **누락된 글꼴을 감지**할 수 있습니다. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **프로 팁:** 리스너는 문서를 로드하는 동일한 스레드에서 실행되므로 실질적인 성능 저하가 없습니다. 나중에 분석을 위해 경고를 수집해야 한다면, 직접 출력하는 대신 `List`에 저장하세요. + +--- + +## 단계 3: 구성된 옵션으로 문서 로드 + +이제 **글꼴 설정을 지정**하고 리스너를 준비했으니 파일을 간단히 로드합니다. 누락된 글꼴이 있으면 콜백이 즉시 호출됩니다. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +소스 파일이 설치되지 않은 글꼴을 참조하면 다음과 유사한 출력이 표시됩니다: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +해당 줄은 어떤 글꼴이 누락되었고 어떤 폴백이 사용되었는지 정확히 알려주므로 로그 기록이나 사용자 피드백에 적합합니다. + +--- + +## 단계 4: 정상 처리 계속 (선택 사항) + +이 시점에서 문서는 완전히 로드되었으며, 원하는 어떤 조작도 진행할 수 있습니다—편집, PDF 변환, 텍스트 추출 등. 경고 리스너가 이미 역할을 수행했으므로 추가 검사가 필요 없습니다. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **맞춤 폴백을 원한다면?** +> `FontSettings`를 비워 두는 대신 특정 글꼴을 추가할 수 있습니다: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +이제 누락된 서체는 *Times New Roman*으로 대체됩니다—대부분의 서구 문서에 신뢰할 수 있는 선택입니다. + +--- + +## 시각적 개요 + +![Aspose.Words for Java에서 기본 글꼴 설정을 지정하는 방법을 보여주는 다이어그램](image.png "기본 글꼴 설정 흐름도") + +*Alt text: Aspose.Words for Java에서 기본 글꼴 설정 흐름도.* + +다이어그램은 `LoadOptions` 초기화(여기서 **기본 글꼴 설정을 지정**)에서 경고 리스너 연결(**누락된 글꼴을 감지**)까지, 그리고 최종적으로 문서를 로드하는 흐름을 보여줍니다. + +--- + +## 흔히 발생하는 실수와 회피 방법 + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **`setFontSettings` 호출을 잊음** | Aspose가 시스템 기본값을 사용해 누락된 글꼴이 감춰집니다. | 항상 새 `FontSettings` 인스턴스를 생성하고 이를 `LoadOptions`에 할당하세요. | +| **리스너가 트리거되지 않음** | 문서를 로드한 뒤에 리스너를 추가했기 때문입니다. | `new Document(...)` 호출 *이전에* 경고 리스너를 추가하세요. | +| **경로 오타로 `FileNotFoundException` 발생** | 하드코딩된 경로가 OS의 대소문자 구분과 맞지 않습니다. | `Paths.get("...").toAbsolutePath()`를 사용하거나 프로젝트 루트 기준의 상대 경로를 설정하세요. | +| **다수의 누락된 글꼴이 로그를 압도** | 큰 문서는 수십 개의 경고를 생성할 수 있습니다. | 출력하기 전에 중복을 필터링하거나 `Set`에 메시지를 집계하세요. | + +--- + +## 솔루션 확장 + +전체 애플리케이션에 대해 **글꼴 설정을 지정**해야 한다면, 싱글톤 `FontSettings`를 생성하고 모든 `LoadOptions`에서 재사용하는 것을 고려하세요. 이렇게 하면 일관된 폴백 전략을 유지하고 객체 생성을 반복하지 않아도 됩니다. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +이제 코드베이스 어디서든 `FontConfig.getLoadOptions()`를 호출하면 동일한 **기본 글꼴 설정 지정** 로직을 즉시 활용할 수 있습니다. + +--- + +## 결론 + +이제 Aspose.Words for Java에서 **기본 글꼴 설정을 지정**, 프로그래밍 방식으로 **글꼴 설정을 지정**, 그리고 출력이 손상되기 전에 **누락된 글꼴을 감지**하는 데 필요한 모든 내용을 다루었습니다. 완전하고 실행 가능한 예제는 위의 코드 스니펫에 포함되어 있으며, IDE에 바로 붙여넣어 경고가 어떻게 발생하는지 확인할 수 있습니다. + +다음 단계는? 폴백 글꼴을 교체해 보거나 다양한 문서 형식(DOC, RTF, HTML)을 실험해 보고, 경고 수집기를 모니터링 대시보드에 통합해 보세요. `FontSettings`를 많이 활용할수록 생성된 문서가 의도한 대로 정확히 표시된다는 확신을 가질 수 있습니다—예기치 않은 상황이나 깨진 글리프 없이. + +질문이 있거나 까다로운 글꼴 대체 상황이 있나요? 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +## 관련 튜토리얼 + +- [글꼴 폴백 설정](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [글꼴 폴백 설정](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [글꼴 폴백 설정](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/java/images-shapes/_index.md b/words/korean/java/images-shapes/_index.md index 701756f815..defe167538 100644 --- a/words/korean/java/images-shapes/_index.md +++ b/words/korean/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aspose.Words for Java를 사용하여 Word 문서의 고품질 썸네일과 사 ### [Java에서 Word 문서 만들기 – 그림자 효과가 있는 사각형 도형 추가](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Java를 사용해 Word 문서에 그림자 효과가 적용된 사각형 도형을 삽입하는 방법을 단계별로 안내합니다. +### [Java Word 문서에 사각형 도형 만들기 – 전체 단계별 가이드](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Java를 사용해 Word 문서에 사각형 도형을 삽입하고 사용자 지정하는 전체 단계별 가이드를 제공합니다. + ## 추가 자료 - [Java 문서용 Aspose.Words](https://reference.aspose.com/words/java/) diff --git a/words/korean/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/korean/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..2937b337b3 --- /dev/null +++ b/words/korean/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,261 @@ +--- +category: general +date: 2026-05-26 +description: Java Word 문서에 사각형 모양을 만들고 그림자 효과를 적용합니다. 모양 그림자를 추가하고 그림자 거리를 설정하며 파일을 + 저장하는 방법을 배웁니다. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: ko +og_description: Java Word 문서에서 사각형 모양을 만들고, 그림자 효과를 적용하며, 모양 그림자를 추가하고, Aspose.Words를 + 사용하여 그림자 거리를 설정합니다. +og_title: Java 워드 문서에서 사각형 도형 만들기 – 완전 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Java 워드 문서에서 사각형 도형 만들기 – 전체 단계별 가이드 +url: /ko/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java Word 문서에서 사각형 도형 만들기 – 전체 단계별 가이드 + +Java Word 문서에서 **사각형 도형 만들기**가 필요했지만 어디서 시작해야 할지 몰랐던 적이 있나요? 여러분만 그런 것이 아닙니다—많은 개발자들이 보고서나 청구서를 프로그래밍으로 생성할 때 이 문제에 부딪힙니다. 이 튜토리얼에서는 **사각형 도형 만들기** 방법, 세련된 그림자 적용, 그리고 그림자 거리를 미세 조정하여 결과를 전문적으로 보이게 하는 과정을 단계별로 안내합니다. + +우리는 Microsoft Office가 설치되지 않아도 Word 파일을 조작할 수 있는 강력한 라이브러리인 Aspose.Words for Java를 사용할 것입니다. 이 가이드를 마치면 **create word document java** 프로젝트에서 **add shape shadow**, **apply shadow effect**, **set shadow distance**를 몇 줄의 코드만으로 구현할 수 있게 됩니다. + +--- + +## 만들게 될 것 + +- 시안 색상의 사각형이 포함된 새 `.docx` 파일. +- 흐림, 각도, 부분 투명도가 적용된 현실적인 드롭 섀도우. +- 그림자와 도형 사이 거리의 전체 제어. +- Maven 또는 Gradle 프로젝트에 바로 넣어 실행할 수 있는 준비된 Java 클래스. + +외부 도구 없이, 수동 UI 단계 없이—오직 순수 코드만 사용합니다. + +--- + +## 사전 요구 사항 + +- Java 8 이상 (코드는 Java 11, Java 17 등에서도 작동합니다). +- Aspose.Words for Java 라이브러리 (Maven Central에서 제공). +- 선호하는 IDE 또는 텍스트 편집기 (IntelliJ IDEA, Eclipse, VS Code 등). +- Java 구문에 대한 기본적인 이해. + +Maven 의존성을 한 번도 추가해 본 적이 없다면, 아래 간단한 스니펫을 참고하세요: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +이제 시작해 봅시다. + +--- + +## 단계 1: Word 문서에서 사각형 도형 만들기 + +먼저 필요한 것은 빈 문서와 `DocumentBuilder`입니다. Builder를 문서에 쓰는 펜이라고 생각하면 됩니다. 이를 확보하면 단 한 번의 메서드 호출로 **create rectangle shape**를 할 수 있습니다. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **왜 중요한가:** `insertShape` 메서드는 기하학적 형태를 생성할 뿐만 아니라 도형을 문서의 내부 컬렉션에 추가하므로 바로 스타일링을 시작할 수 있습니다. + +--- + +## 단계 2: 도형에 그림자 효과 적용 + +이제 사각형이 페이지에 존재하므로 **apply shadow effect**를 적용합니다. 그림자는 깊이를 부여해 도형이 페이지에서 떠 있는 듯한 느낌을 주며, 보고서 가독성을 높이는 미묘한 UI 개선 효과가 있습니다. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **프로 팁:** `5.0`의 블러 값은 대부분 화면에 표시되는 문서에 자연스럽게 보입니다. 인쇄할 경우 흐릿해 보이지 않도록 약간 낮은 값을 사용할 수 있습니다. + +--- + +## 단계 3: 그림자 거리 설정 – 위치 미세 조정 + +그림자는 블러뿐만 아니라 올바른 오프셋도 필요합니다. 여기서 **set shadow distance**를 수행합니다. `7.0` 포인트의 거리는 눈에 띄지만 과하지 않은 적당한 오프셋을 만들어 줍니다. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **더 큰 오프셋이 필요하면?** 값을 늘리고, 더 촘촘한 느낌을 원하면 줄이세요. 거리 값은 각도와 함께 작동해 그림자를 정확히 배치한다는 점을 기억하세요. + +--- + +## 단계 4: 문서 저장 – 작업 내용 영구 저장 + +마지막으로 문서를 디스크에 저장합니다. 파일이 저장될 경로를 원하는 위치로 변경하세요. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +클래스를 실행하면 `shadow.docx` 파일이 생성되며, Microsoft Word 또는 LibreOffice에서 열면 45° 각도로 기울어지고 7 포인트 오프셋된 부드러운 회색 그림자가 있는 시안 색 사각형이 표시됩니다. + +--- + +## 전체 작동 예제 + +아래는 복사‑붙여넣기 바로 사용할 수 있는 전체 코드입니다. 모든 import, 주석, 최종 `save` 호출이 포함되어 있습니다. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**예상 출력:** `shadow.docx`를 열면 첫 페이지 중앙에 시안 색 사각형이 표시되고, 오른쪽 아래로 약간 오프셋된 미묘한 회색 그림자가 드리워집니다. 그림자의 블러와 투명도가 자연스러운 조명처럼 보이게 합니다. + +--- + +## 자주 묻는 질문 및 엣지 케이스 + +### “다른 도형을 사용할 수 있나요?” + +물론 가능합니다. `ShapeType.RECTANGLE`을 `ShapeType.OVAL`, `ShapeType.LINE` 또는 지원되는 다른 enum으로 교체하면 됩니다. 나머지 그림자 코드는 동일하게 유지됩니다. + +### “여러 개의 그림자가 필요하면 어떻게 하나요?” + +Aspose.Words는 도형당 하나의 그림자만 지원합니다. 여러 그림자를 시뮬레이션하려면 도형을 복제하고 각 복제본을 오프셋한 뒤 투명도를 조정하세요. + +### “LibreOffice에서도 그림자가 보이나요?” + +네—Aspose.Words는 표준 OOXML을 작성하므로 LibreOffice가 올바르게 해석합니다. 렌더링 엔진 차이로 그림자가 약간 다르게 보일 수 있지만 효과는 유지됩니다. + +### “브랜드에 맞게 그림자 색을 바꾸려면 어떻게 하나요?” + +`java.awt.Color.GRAY`를 원하는 `java.awt.Color`로 교체하면 됩니다. 예를 들어 기업용 파란색은 `new java.awt.Color(0, 120, 215)`와 같이 사용할 수 있습니다. + +--- + +## 이미지 일러스트레이션 + +![Java Word 문서에서 사각형 도형 만들기](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** 일러스트레이션으로, Word 문서에 시안 색 사각형과 회색 드롭 섀도우가 표시됩니다. + +--- + +## 요약 및 다음 단계 + +우리는 Aspose.Words for Java를 사용하여 **create rectangle shape**, **apply shadow effect**, **add shape shadow**, **set shadow distance**를 구현하는 방법을 다루었습니다. 코드는 독립적이며 최신 JDK에서 실행되고 배포 준비가 된 깔끔한 `.docx` 파일을 생성합니다. + +더 나아가고 싶나요? 다음을 시도해 보세요: + +- `builder.moveTo(rectangleShape.getAbsolutePosition())`를 사용해 사각형 안에 텍스트 추가하기. +- 도형 테이블을 만들어 다이어그램 구성하기. +- 문서를 PDF로 내보내기 (`doc.save("output.pdf", SaveFormat.PDF);`). + +이러한 작업은 방금 살펴본 기본 원칙을 기반으로 하므로 예제를 확장하는 데 익숙해질 것입니다. + +--- + +## 최종 생각 + +**create word document java**와 같은 도형 및 그림자 작업을 마스터하면 보고서, 계약서, 마케팅 자료 등을 자동화할 때 큰 경쟁력을 얻을 수 있습니다. 여기서 제시한 방법은 깔끔하고 유지보수가 쉬우며, 무엇보다도 필요한 시각 스타일에 맞게 쉽게 조정할 수 있습니다. + +코드를 실행해 보고, 블러, 각도, 거리 값을 조정해 보세요. 그러면 문서가 평범함에서 세련됨으로 변하는 것을 확인할 수 있습니다. 문제가 발생하면 아래에 댓글을 남겨 주세요. 기꺼이 도와드리겠습니다. + +행복한 코딩 되세요! + +## 관련 튜토리얼 + +- [Word 문서 Java 만들기 – 그림자 효과가 있는 사각형 도형 추가](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Aspose.Words for Java에서 DocumentBuilder를 사용해 폼 필드 생성 및 내용 추가 방법](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Word에서 바코드 생성으로 PDF 만들기 – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/polish/java/document-conversion-and-export/_index.md index 0c16270a87..aedd07d2c6 100644 --- a/words/polish/java/document-conversion-and-export/_index.md +++ b/words/polish/java/document-conversion-and-export/_index.md @@ -90,18 +90,33 @@ Learn how to format tables and apply table styles in Aspose.Words for Java. Expl ### [Konwertuj docx do markdown – Eksportuj równania matematyczne do LaTeX przy użyciu Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Dowiedz się, jak konwertować pliki DOCX do Markdown i eksportować równania matematyczne jako LaTeX przy użyciu biblioteki Aspose.Words dla Javy. +### [Zapisz Word jako markdown – eksportuj równania do LaTeX w Javie](./save-word-as-markdown-export-math-to-latex-with-java/) +Dowiedz się, jak zapisać dokument Word w formacie markdown i wyeksportować równania matematyczne do LaTeX przy użyciu Aspose.Words for Java. + ### [Jak osadzić obrazy w Markdown podczas konwersji DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Dowiedz się, jak zachować obrazy przy konwersji DOCX do Markdown, aby były poprawnie wstawione w wynikowy plik. +### [Osadzanie obrazów jako Base64 przy konwertowaniu DOCX do Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Dowiedz się, jak osadzać obrazy jako Base64 przy konwertowaniu DOCX do Markdown przy użyciu Aspose.Words for Java. + ### [Zapisz dokument jako TXT – szybki przewodnik po eksportowaniu równań Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Dowiedz się, jak wyeksportować dokumenty Word do formatu TXT, zachowując równania matematyczne przy użyciu Aspose.Words for Java. +### [Eksport docx do txt w Javie – Kompletny przewodnik programistyczny](./export-docx-to-txt-with-java-complete-programming-guide/) +Dowiedz się, jak przy użyciu Aspose.Words for Java wyeksportować plik DOCX do formatu TXT w pełnym przewodniku programistycznym. + ### [Aspose.Words do PDF – konwertuj DOCX do PDF w Javie](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Dowiedz się, jak w prosty sposób konwertować pliki DOCX do PDF w Javie przy użyciu biblioteki Aspose.Words. ### [Tworzenie dostępnego PDF z DOCX – kompletny przewodnik](./create-accessible-pdf-from-docx-complete-guide/) Dowiedz się, jak z dokumentu DOCX wygenerować PDF spełniający standardy dostępności, w tym tagowanie, strukturę i kontrast. +### [Zapisz dokument jako PDF przy użyciu Aspose.Words Java – kompletny przewodnik po dostępności](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Pełny przewodnik, jak zapisać dokument jako PDF z pełną dostępnością przy użyciu Aspose.Words for Java. + +### [Tworzenie dostępnego PDF w Javie – pełny przewodnik tagowania](./create-accessible-pdf-in-java-full-tagging-guide/) +Dowiedz się, jak w pełni otagować dokument PDF w Javie, aby spełniał standardy dostępności i był przyjazny dla czytników ekranowych. + ## Najczęściej zadawane pytania **Q: Jak dodać znak wodny do istniejącego PDF przy użyciu Aspose.Words?** diff --git a/words/polish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/polish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..4a851530d4 --- /dev/null +++ b/words/polish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Utwórz dostępny PDF w Javie z kodem krok po kroku. Dowiedz się, jak oznaczyć + PDF pod kątem dostępności i włączyć tagowanie PDF przy użyciu PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: pl +og_description: Utwórz dostępny PDF w Javie z kodem krok po kroku. Dowiedz się, jak + oznaczyć PDF pod kątem dostępności i włączyć tagowanie PDF przy użyciu PdfSaveOptions. +og_title: Tworzenie dostępnych plików PDF w Javie – Kompletny przewodnik po tagowaniu +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Tworzenie dostępnego PDF w Javie – Kompletny przewodnik po tagowaniu +url: /pl/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie dostępnych plików PDF w Javie – Kompletny przewodnik po tagowaniu + +Zastanawiałeś się kiedyś, jak **tworzyć dostępne pliki PDF** bezpośrednio w kodzie Java? Nie jesteś sam. Wielu programistów musi obsługiwać użytkowników korzystających z czytników ekranu, a różnica między zwykłym PDF a dostępny może być ogromna. W tym samouczku przeprowadzimy Cię przez **to, jak tagować PDF pod kątem dostępności**, pokażemy **jak tworzyć PDF z tagami** przy użyciu Aspose PDF for Java oraz ujawnimy dokładne kroki **dodawania tagów dostępności do PDF**, aby każdy czytnik otrzymał te same informacje. + +Omówimy także **włączanie tagowania PDF** – najlepsze praktyki, typowe pułapki oraz kompletny, gotowy do uruchomienia przykład, który możesz od razu dodać do swojego projektu. Bez niejasnych odniesień — tylko konkretny kod, wyjaśnienia i finalny plik, który możesz otworzyć w Adobe Acrobat, aby zweryfikować tagi. + +## Czego się nauczysz + +- Dlaczego tagowanie PDF i zgodność z dostępnością są ważne. +- Wymagania wstępne i konfiguracja biblioteki (Aspose PDF for Java 23.10 lub nowszy). +- Jak **tworzyć dostępny PDF** od podstaw, krok po kroku. +- Sposoby **dodawania tagów dostępności do PDF** poza podstawowym wywołaniem `setTagDocumentStructure`. +- Wskazówki dotyczące testowania wyniku i rozwiązywania typowych problemów. + +Po zakończeniu tego przewodnika będziesz w stanie generować pliki PDF, które przechodzą testy WCAG 2.1 AA i jednocześnie wyglądają profesjonalnie. + +--- + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Nowoczesne funkcje języka i lepsze obsługiwanie Unicode. | +| **Aspose PDF for Java** (v23.10 lub nowszy) | Dostarcza klasę `PdfSaveOptions` oraz wsparcie tagowania. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, itp.) | Ułatwia kompilację i debugowanie. | +| **Write permission** do folderu, w którym zostanie zapisany PDF | Wywołanie `doc.save` wymaga ścieżki zapisywalnej. | + +Jeśli jeszcze nie dodałeś Aspose PDF do swojego projektu, wstaw następującą zależność Maven do pliku `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Wskazówka:** Używaj najnowszej wersji; nowsze wydania poprawiają dokładność tagowania i dodają funkcje dostępności specyficzne dla języka. + +--- + +## Krok 1: Przygotowanie szkieletu dokumentu + +Najpierw tworzymy nowy obiekt `Document`. Traktuj go jak czyste płótno, które później będzie zawierało tagi potrzebne do dostępności. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Dlaczego to ważne:** Bez żadnej treści nie ma czego tagować. Dodanie nawet prostego `TextFragment` daje silnikowi tagowania coś, z czym może pracować, i automatycznie tworzy tag `

` (paragraf), gdy później włączymy tagowanie struktury. + +## Krok 2: Utworzenie opcji zapisu PDF (rdzeń tagowania) + +Teraz przygotowujemy opcje, które instruują Aspose PDF, aby osadził logiczne drzewo struktury w pliku. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Wywołanie `setTagDocumentStructure(true)` jest przełącznikiem **włączania tagowania PDF**. Gdy jest ustawione na true, biblioteka buduje drzewo tagów odzwierciedlające układ wizualny, co sprawia, że PDF jest czytelny dla technologii wspomagających. + +> **Uwaga:** To najprostszy sposób na **jak stworzyć PDF z tagami**. Dla bardziej szczegółowej kontroli (np. ustawiania języka lub własnych tagów) możesz zbadać `pdfOptions.setTagLanguage("en-US")` oraz `pdfOptions.setTagStructureTreeRoot(...)`. + +## Krok 3: Zapisz dostępny PDF + +Na koniec zapisujemy dokument na dysku, używając właśnie skonfigurowanych opcji. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Gdy `doc.save` zakończy się, znajdziesz plik `accessible.pdf` w folderze `output`. Otwórz go w Adobe Acrobat i przejdź do **Plik → Właściwości → Opis → Tagowanie** – powinieneś zobaczyć wypełnione drzewo tagów. + +## Jak tagować PDF pod kątem dostępności – poza podstawami + +Powyższy fragment w trzech krokach już **dodaje tagi dostępności do PDF**, ale dokumenty w rzeczywistym świecie często wymagają dodatkowego dopracowania. Oto kilka ulepszeń, które możesz dodać: + +### 1. Ustaw język dokumentu + +Czytniki ekranu używają atrybutu języka, aby poprawnie wymówić tekst. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Dodaj tytuł i temat + +Metadane pomagają narzędziom wspomagającym podać kontekst przed otwarciem pliku przez użytkownika. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Taguj obrazy opisem alternatywnym + +Jeśli osadzasz obrazy, muszą mieć opisy `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Oznacz nagłówki tabel + +Tabele są znane z wprowadzania zamieszania wśród czytników, chyba że oznaczysz wiersze nagłówków. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Te dodatkowe kroki sprawiają, że Twój PDF nie jest tylko *technicznie* otagowany, ale naprawdę **dostępny** dla różnorodnej publiczności. + +--- + +## Typowe problemy przy włączaniu tagowania PDF + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Brak tagów w Acrobat | `setTagDocumentStructure` ustawione na `false` | Upewnij się, że wywołujesz `pdfOptions.setTagDocumentStructure(true)`. | +| Nieprawidłowa kolejność odczytu | Złożony układ bez wyraźnych tagów | Użyj `pdfOptions.setTagStructureTreeRoot(...)`, aby zdefiniować własną kolejność. | +| Obrazy odczytywane jako „image” bez opisu | Nie ustawiono tekstu alternatywnego | Wywołaj `image.getAlternativeText().setValue("...")`. | +| Język nie rozpoznany | Pominięto `setTagLanguage` lub podano niewłaściwy kod | Podaj kod języka BCP‑47 (`en-US`, `fr-FR`). | + +Świadomość tych problemów zaoszczędzi Ci godziny debugowania później. + +--- + +## Zweryfikuj wynik – czego się spodziewać + +Po uruchomieniu programu otwórz `output/accessible.pdf` w Adobe Acrobat Reader: + +1. **Panel tagów** (`View → Show/Hide → Navigation Panes → Tags`) powinien wyświetlać hierarchię taką jak `/Document → /Part → /Sect → /Para`. +2. **Kolejność odczytu** powinna odpowiadać wizualnemu przepływowi (najpierw tekst, potem obrazy). +3. **Czytnik ekranu** (NVDA, VoiceOver) odczyta „Hello, accessible PDF!” zamiast samego „Page 1”. + +Jeśli którykolwiek z tych elementów brakuje, sprawdź ponownie powyższe kroki — szczególnie wywołanie `setTagDocumentStructure`. + +--- + +## Pełny działający przykład (gotowy do kopiowania i wklejenia) + + + +## Powiązane samouczki + +- [Utwórz dostępny PDF z Word – konwersja do PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Utwórz dostępny PDF z DOCX – kompletny przewodnik](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Jak zapisać dokument jako PDF przy użyciu Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/polish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/polish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..5b958531cc --- /dev/null +++ b/words/polish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Osadzaj obrazy jako base64 podczas konwertowania plików docx na markdown + przy użyciu Aspose.Words for Java. Dowiedz się, jak konwertować Word na markdown, + zapisywać Word jako markdown oraz obsługiwać obrazy. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: pl +og_description: Osadzaj obrazy jako base64 podczas konwertowania docx na markdown + przy użyciu Aspose.Words dla Javy. Kompletny przewodnik konwersji Worda na markdown + i zapisywania Worda jako markdown. +og_title: Osadzaj obrazy jako Base64 przy konwertowaniu DOCX na Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Osadzaj obrazy jako Base64 przy konwertowaniu DOCX na Markdown +url: /pl/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wstaw obrazy jako Base64 podczas konwertowania DOCX do Markdown + +Zastanawiałeś się kiedyś, jak **embed images as base64** podczas **convert docx to markdown**? Nie jesteś jedyny — programiści ciągle pytają, jak zachować obrazy w linii bez zarządzania oddzielnymi plikami. Dobrą wiadomością jest to, że Aspose.Words for Java robi to łatwo: możesz konwertować dokument Word do Markdown i automatycznie wstawiać każde zdjęcie jako ciąg Base64. + +W tym samouczku przeprowadzimy Cię przez cały proces — od wczytania pliku `.docx` zawierającego obrazy, po skonfigurowanie wywołania zwrotnego `MarkdownSaveOptions`, które wykonuje ciężką pracę, aż po zapisanie wyniku jako czystego pliku `.md`. Po zakończeniu dokładnie wiesz, jak **convert word to markdown**, **convert images to base64** i **save word as markdown** bez pozostawiania niepotrzebnych folderów z obrazami. Bez zewnętrznych narzędzi, bez ręcznego przetwarzania — tylko czysty kod Java, który możesz wkleić do dowolnego projektu. + +## Czego będziesz potrzebować + +- **Java 17** (lub dowolny nowszy JDK) – kod używa składni lambda, ale możesz go dostosować do starszych wersji. +- Biblioteka **Aspose.Words for Java** (najnowsza wersja na 2026). Dodaj zależność Maven lub plik JAR do classpath. +- Przykładowy plik **DOCX**, który zawiera przynajmniej jeden obraz. +- IDE lub prosty edytor tekstu — Visual Studio Code, IntelliJ IDEA, a nawet `vim` się sprawdzą. + +Jeśli już je masz, świetnie — zanurzmy się od razu. + +## Krok 1: Wczytaj dokument Word + +Najpierw tworzymy instancję `Document`, która wskazuje na plik źródłowy. To ten sam krok, niezależnie od tego, czy **convert docx to markdown**, czy po prostu czytasz plik w innych celach. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Dlaczego to ważne:** Obiekt `Document` jest punktem wejścia dla każdej operacji Aspose. Przechowuje całą strukturę Word — w tym obrazy, tabele i style — dzięki czemu późniejsze wywołanie zwrotne może przeglądać każdy zasób. + +## Krok 2: Utwórz MarkdownSaveOptions i zarejestruj wywołanie zwrotne zapisywania zasobów + +Magia tkwi w `MarkdownSaveOptions`. Dołączając `IResourceSavingCallback`, uzyskujemy kontrolę nad tym, jak każdy zewnętrzny zasób (np. obraz) jest zapisywany. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Dlaczego używać `setSaveToMemory(true)`? + +Gdy `saveToMemory` jest ustawione na true, Aspose zapisuje bajty obrazu do strumienia pamięci zamiast do pliku. Eksporter Markdown następnie konwertuje ten strumień na ciąg Base64 i wstawia go bezpośrednio do znacznika obrazu w Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +To jest sedno **embed images as base64**. + +## Krok 3: Zapisz dokument jako Markdown + +Teraz, gdy wywołanie zwrotne jest gotowe, ostatnim krokiem jest po prostu wywołanie `save`. To tutaj naprawdę **convert word to markdown**, a dzięki wywołaniu zwrotnemu także **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Wynik:** `out.md` zawiera tekst Markdown, w którym każdy obraz jest przedstawiony jako `data:` URI. Nie są tworzone dodatkowe pliki obrazów na dysku, więc folder pozostaje uporządkowany. + +## Krok 4: Zweryfikuj wynik i typowe pułapki + +Otwórz wygenerowany `out.md` w dowolnym przeglądarce Markdown (VS Code, GitHub lub generatorze statycznych stron). Powinieneś zobaczyć coś w rodzaju: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Lista kontrolna rozwiązywania problemów + +| Problem | Prawdopodobna przyczyna | Rozwiązanie | +|-------|--------------|-----| +| Obraz wyświetla się jako uszkodzony link | `setSaveToMemory` został pominięty | Upewnij się, że `args.setSaveToMemory(true);` znajduje się w wywołaniu zwrotnym | +| Ciąg Base64 jest obcięty | Niepasujące kodowanie pliku wyjściowego | Zapisz Markdown używając UTF‑8 (domyślnie w Aspose) | +| Nieoczekiwane nazwy plików | `setKeepResourceOriginalName(true)` | Ustaw na `false`, aby wymusić własną logikę nazewnictwa | + +## Krok 5: Zaawansowane warianty (opcjonalnie) + +### Konwertuj tylko wybrane obrazy + +Jeśli chcesz wstawić tylko niektóre obrazy (np. te większe niż 100 KB), dodaj sprawdzenie rozmiaru: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Użyj innego formatu obrazu + +`ResourceSavingArgs` dostarcza surowe bajty, więc możesz ponownie zakodować JPEGy jako PNG przed wstawieniem — przydatne, gdy odbiorca Markdown preferuje PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Te modyfikacje pokazują, jak elastyczne jest podejście **embed images as base64**, gdy **convert docx to markdown**. + +## Zakończenie + +Właśnie nauczyłeś się, jak **embed images as base64** podczas **convert docx to markdown** przy użyciu Aspose.Words for Java. Poprzez podłączenie prostego `IResourceSavingCallback`, biblioteka wykonuje całą ciężką pracę: **convert word to markdown**, **convert images to base64**, a na końcu **save word as markdown** jednym wywołaniem `save`. + +Śmiało eksperymentuj — wypróbuj różne reguły filtrowania obrazów, przełącz na wyjście HTML lub połącz ten krok z generatorem statycznych stron. Ten sam wzorzec działa również dla innych formatów (HTML, EPUB), więc możesz ponownie używać wywołania zwrotnego tam, gdzie potrzebne są zasoby w linii. + +**Kolejne kroki:** +- Zbadaj `HtmlSaveOptions` dla HTML‑z‑Base64 obrazami. +- Połącz to z pipeline CI, aby zautomatyzować generowanie dokumentacji. +- Zagłęb się w `DocumentVisitor` Aspose, jeśli potrzebujesz jeszcze dokładniejszej kontroli nad procesem konwersji. + +Miłego kodowania i ciesz się czystymi, samodzielnymi plikami Markdown! + +## Powiązane samouczki + +- [Jak wstawić obrazy w Markdown podczas konwertowania DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Eksport równań matematycznych do LaTeX przy użyciu Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Zapisz obrazy z Word — Przewodnik Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/polish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..907877eee4 --- /dev/null +++ b/words/polish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Eksportuj docx do txt przy użyciu Javy i Aspose.Words. Dowiedz się, jak + konwertować docx na tekst, zachować Unicode i wyeksportować dokument Word jako txt + w kilku krokach. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: pl +og_description: Eksportuj docx do txt w Javie. Ten poradnik pokazuje, jak przekonwertować + docx na tekst, zachować zwykły tekst Unicode i efektywnie wyeksportować dokument + Word jako txt. +og_title: Eksportuj docx do txt w Javie – Kompletny przewodnik +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Eksportuj docx do txt w Javie – Kompletny przewodnik programistyczny +url: /pl/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Eksport docx do txt w Javie – Kompletny przewodnik programistyczny + +Kiedykolwiek potrzebowałeś **eksportować docx do txt**, ale obawiałeś się utraty znaków specjalnych? Nie jesteś sam. Gdy konwertujesz dokumenty Worda na pliki tekstowe, symbole Unicode, tabele i nawet proste formatowanie mogą zniknąć jak za dotknięciem czarodziejskiej różdżki. + +W tym przewodniku pokażemy niezawodny sposób na **eksportowanie docx do txt** przy użyciu Aspose.Words for Java, zachowując każdy znak Unicode i utrzymując układ tabel czytelny. Po zakończeniu będziesz także wiedział, jak **konwertować docx na tekst**, **konwertować word na tekst**, a nawet **eksportować word jako txt** bez problemów. + +## Co obejmuje ten tutorial + +* Konfiguracja Aspose.Words w projekcie Java +* Ładowanie pliku DOCX i przygotowanie go do wyjścia w formacie plain‑text +* Konfigurowanie wsparcia **plain text unicode** za pomocą `TxtSaveOptions` +* Opcjonalne triki, aby tabele były czytelne w powstałym pliku `.txt` +* Zapis pliku i weryfikacja wyniku + +Bez zewnętrznych skryptów, bez tajemniczych narzędzi wiersza poleceń — po prostu czysty kod Java, który możesz wkleić do dowolnego projektu Maven lub Gradle. + +> **Dlaczego to ważne?** Pliki tekstowe są lekkie, przyjazne systemom kontroli wersji i idealne do indeksowania wyszukiwarek lub dalszych potoków przetwarzania. Jeśli kiedykolwiek próbowałeś `cat` pliku Word i otrzymałeś bełkot, ten tutorial rozwiąże problem. + +--- + +## Eksport docx do txt – Przegląd + +Zanim zanurkujemy w kod, wyjaśnijmy terminologię. **Eksport docx do txt** oznacza wzięcie pakietu Microsoft Word `.docx` i zapisanie jego treści tekstowej do prostego pliku `.txt`. W przeciwieństwie do konwersji PDF, eksport tekstowy usuwa stylizację, ale może zachować podziały wierszy, znaczniki akapitów i — jeśli odpowiednio skonfigurujesz — znaki Unicode, takie jak emoji, litery z akcentami czy skrypty azjatyckie. + +Aspose.Words upraszcza to zadanie, ponieważ abstrahuje format pliku Word i oferuje klasę `TxtSaveOptions`, w której możesz określić kodowanie, obsługę tabel i nie tylko. + +### Wymagania wstępne + +* Java 11 lub nowsza (API działa z Java 8+, ale przyjmujemy najnowszy JDK) +* Aspose.Words for Java JAR (dostępny w Maven Central) +* Przykładowy plik `unicode.docx` zawierający różnorodne znaki Unicode — np. „こんにちは”, „😊” oraz prostą tabelę + +Jeśli masz wszystko gotowe, zaczynamy. + +--- + +## Krok 1: Załaduj plik DOCX (Convert docx to text) + +Pierwsze, co musisz zrobić, to wczytać źródłowy dokument do pamięci. To właśnie tutaj oficjalnie rozpoczyna się proces **convert docx to text**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Dlaczego to ważne:* `Document` jest reprezentacją Aspose.Words pliku Word. Ładując go, uzyskujesz dostęp do wszystkich akapitów, tabel i nawet ukrytych elementów. Jeśli plik nie zostanie znaleziony, Aspose wyrzuci czytelny `FileNotFoundException`, więc od razu wiesz, co poszło nie tak. + +--- + +## Krok 2: Skonfiguruj TxtSaveOptions dla Unicode (Plain text unicode) + +Pliki tekstowe to po prostu strumienie bajtów, więc musisz powiedzieć Javie, którego zestawu znaków użyć. UTF‑8 jest de‑facto standardem dla **plain text unicode**, ponieważ potrafi zakodować każdy punkt kodowy Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro tip:** Jeśli pominiesz wywołanie `setEncoding`, Aspose domyślnie użyje zestawu znaków platformy, który na wielu maszynach Windows jest Windows‑1252. To domyślne ustawienie cicho odrzuci znaki takie jak „ß” czy „—”. + +--- + +## Krok 3: Zachowaj układ tabel (Opcjonalnie, ale przydatne dla czytelności) + +Podczas **export word as txt** tabele zazwyczaj spłaszczają się do jednej linii tekstu, co czyni je nieczytelnymi. Aspose.Words oferuje prostą flagę, aby zachować strukturę wizualną. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Kiedy używać:* Jeśli Twój źródłowy DOCX zawiera faktury, harmonogramy lub jakiekolwiek dane w formie siatki, włączenie `PreserveTableLayout` wstawi tabulatory i podziały wierszy, tak aby wynikowy plik nadal przypominał tabelę. Jeśli nie potrzebujesz tego, możesz pominąć tę linię i uzyskać bardziej zwarty wynik. + +--- + +## Krok 4: Zapisz dokument jako plain‑text (Export word as txt) + +Teraz najcięższa część jest już zrobiona — wystarczy zapisać bajty na dysku. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Uruchomienie programu tworzy `plain.txt` w tym samym folderze. Otwórz go w dowolnym edytorze tekstu (Notepad++, VS Code, nawet `cat` w terminalu) i zobaczysz: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Zauważ, że japońskie powitanie i emotikona przetrwały, a tabela zachowała kolumny dzięki `PreserveTableLayout`. To istota czystego **export docx to txt**. + +--- + +## Krok 5: Zweryfikuj wynik (Convert word to text sanity check) + +Szybka kontrola zapobiega cichej utracie danych. Oto kilka sposobów, aby upewnić się, że naprawdę **convert word to text** działa poprawnie: + +1. **Porównanie sum kontrolnych** – oblicz hash SHA‑256 pliku `.txt` przed i po konwersji w obie strony (txt → docx → txt), aby zapewnić stabilność. +2. **Wyszukiwanie znaczników Unicode** – użyj `grep` lub funkcji znajdź‑w‑pliku w IDE, aby zlokalizować znaki takie jak „😊”. +3. **Otwórz w kilku edytorach** – niektóre stare wersje Windows Notepad nadal źle interpretują UTF‑8 bez BOM; otwarcie pliku w VS Code potwierdzi prawidłowe kodowanie. + +Jeśli którykolwiek z tych testów nie przejdzie, sprawdź, czy w kodzie znajduje się `saveOptions.setEncoding(StandardCharsets.UTF_8)` oraz czy Twój źródłowy DOCX rzeczywiście zawiera tekst Unicode. + +--- + +## Typowe pułapki i jak ich unikać + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| **Brakujące znaki** | Domyślny zestaw znaków systemu (np. Windows‑1252) usuwa znaki nie‑ASCII. | Jawnie ustaw UTF‑8 poprzez `saveOptions.setEncoding`. | +| **Tabele stają się jedną linią** | `PreserveTableLayout` pozostaje w domyślnym stanie `false`. | Wywołaj `saveOptions.setPreserveTableLayout(true)`. | +| **Plik nie znaleziony** | Nieprawidłowa ścieżka lub brak uprawnień do odczytu. | Użyj ścieżek bezwzględnych lub `Paths.get(...)` z odpowiednią obsługą wyjątków. | +| **Spowolnienie przy dużych dokumentach** | Ładowanie całego dokumentu do pamięci. | Strumieniuj dokument w partiach przy użyciu `DocumentBuilder`, jeśli potrzebujesz tylko wybranych sekcji. | + +--- + +## Bonus: Eksportowanie wielu plików DOCX w partii + +Jeśli musisz **convert docx to text** dla całego folderu, opakuj logikę w pętlę: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Ten fragment **export docx to txt** każdy plik w katalogu, oszczędzając godziny ręcznej pracy. + +--- + +## Zakończenie + +Właśnie nauczyłeś się, jak **export docx to txt** w Javie, zapewniając, że każdy znak Unicode pozostaje nienaruszony, tabele są czytelne, a cały proces powtarzalny. Konfigurując `TxtSaveOptions` na UTF‑8 i opcjonalnie zachowując układ tabel, możesz niezawodnie **convert docx to text**, **convert word to text** i **export word as txt** dla dowolnego dalszego przepływu pracy. + +Gotowy na kolejny wyzwanie? Spróbuj eksportować do innych formatów tekstowych, takich jak markdown (`.md`) lub CSV, albo odkryj możliwości konwersji PDF w Aspose.Words. Te same zasady — jawne kodowanie, zachowanie układu i dokładna weryfikacja — obowiązują wszędzie. + +Miłego kodowania i niech Twoje pliki tekstowe zawsze pozostają bogate w Unicode! + +--- + +![Diagram pokazujący pipeline eksportu docx do txt](/images/export-docx-to-txt-pipeline.png){alt="diagram pipeline eksportu docx do txt"} + +## Powiązane tutoriale + +- [Konwertuj Docx na Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Konwertuj DOCX do PDF w Javie](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Konwertuj docx na markdown – Eksportuj równania matematyczne do LaTeX przy użyciu Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/polish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..111e616b82 --- /dev/null +++ b/words/polish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Zapisz dokument jako PDF przy użyciu Aspose.Words Java i dodaj dostępność + do PDF. Dowiedz się, jak konwertować docx na PDF, oznaczać poziome linie oraz zapewnić + zgodność z PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: pl +og_description: Zapisz dokument jako PDF przy użyciu Aspose.Words Java, dodając dostępność + do PDF. Przewodnik krok po kroku, jak przekonwertować docx na PDF i oznaczyć poziome + linie dla zgodności z PDF/UA‑2. +og_title: Zapisz dokument jako PDF przy użyciu Aspose.Words Java – Dostępność w prosty + sposób +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Zapisz dokument jako PDF przy użyciu Aspose.Words Java – Kompletny przewodnik + po dostępności +url: /pl/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< 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 Java – Kompletny przewodnik po dostępności + +Zastanawiałeś się kiedyś, jak **zapisać dokument jako PDF** zachowując jego dostępność dla czytników ekranu? Nie jesteś sam. Wielu programistów musi *konwertować docx na pdf* i jednocześnie spełniać standardy PDF/UA‑2, szczególnie gdy źródło zawiera poziome linie, które muszą być poprawnie oznaczone. W tym samouczku przeprowadzimy Cię krok po kroku przez dokładne instrukcje, jak **zapisać dokument jako PDF** przy użyciu Aspose.Words dla Javy, automatycznie **dodać dostępność do PDF** i zapewnić, że każda pozioma linia jest **oznaczona** jako artefakt. + +Zaczniemy od czystego projektu Java, załadujemy plik DOCX, który już zawiera poziome linie, skonfigurujemy opcje zapisu PDF pod kątem zgodności z PDF/UA‑2 i w końcu wygenerujemy w pełni dostępny PDF. Po zakończeniu będziesz w stanie **zapisać dokument jako pdf** z pewnością, że przechodzi on kontrole dostępności. + +## Wymagania wstępne + +- Zainstalowana Java 8 lub nowsza (samouczek testowano na JDK 17). +- Maven 3.6+ (lub Gradle, jeśli wolisz) do zarządzania zależnościami. +- Ważna licencja Aspose.Words dla Java (wersja próbna działa, ale licencja usuwa znaki wodne ewaluacji). +- Plik DOCX (`input.docx`) zawierający co najmniej jedną poziomą linię — myśl o prostym separatorze linii, który dodałbyś w Wordzie. + +> **Wskazówka:** Jeśli nie masz pod ręką pliku DOCX, po prostu utwórz nowy dokument Word, wpisz kilka akapitów, wstaw *Wstaw → Pozioma linia*, zapisz jako `input.docx` i umieść go w wybranym folderze. + +## Krok 1: Konfiguracja projektu Maven + +Najpierw utwórz nowy projekt Maven (lub dodaj do istniejącego). Plik `pom.xml` wymaga zależności Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Dlaczego to ważne:** Dodanie artefaktu `aspose-words` jest pierwszym krokiem do *konwertowania docx na pdf*. Bez niego kompilator nie rozpozna klas `Document`, `PdfSaveOptions` i innych kluczowych. + +## Krok 2: Załaduj źródłowy DOCX zawierający poziome linie + +Teraz napiszemy małą klasę Java, która ładuje DOCX. To jest miejsce, w którym zaczyna się część **oznaczania poziomych linii** — Aspose.Words automatycznie traktuje poziomą linię jako akapit z obramowaniem, ale pozwolimy silnikowi PDF/UA obsłużyć oznaczanie. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Zauważ, że nie zapisaliśmy jeszcze nic — po prostu **ładujemy** DOCX, co jest pierwszą połową *konwertowania docx na pdf*. Obiekt `Document` zawiera teraz całą treść Worda, w tym wszystkie wstawione przez Ciebie poziome linie. + +## Krok 3: Skonfiguruj opcje zapisu PDF pod kątem zgodności z PDF/UA‑2 + +Magia **dodawania dostępności do PDF** tkwi w `PdfSaveOptions`. Ustawiając poziom zgodności na `PDF_UA_2`, Aspose.Words: + +1. Oznaczyć elementy strukturalne (nagłówki, tabele itp.). +2. Oznaczyć elementy dekoracyjne — takie jak poziome linie — jako *artefakty*, aby czytniki ekranu je ignorowały. +3. Wstawić niezbędne metadane PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Dlaczego ustawia się zgodność?** Bez `PDF_UA_2` wygenerowany PDF może być czytelny, ale nie przejdzie automatycznych walidatorów dostępności. Wymóg **oznaczania poziomych linii** jest spełniony automatycznie, ponieważ PDF/UA traktuje je jako *artefakty*, gdy włączona jest flaga zgodności. + +## Krok 4: Zapisz dokument jako PDF + +Teraz w końcu **zapisujemy dokument jako pdf**. Ta pojedyncza linia wykonuje najcięższą pracę — konwertuje DOCX, stosuje tagi dostępności i zapisuje plik na dysku. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Uruchom klasę (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) i zobaczysz komunikat potwierdzający. Otwórz wygenerowany `ua_compliant.pdf` w Adobe Acrobat i sprawdź **Plik → Właściwości → Opis → PDF/A, PDF/UA** — powinieneś zobaczyć wpis „PDF/UA‑2”. + +### Oczekiwany wynik + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Otwórz PDF i zauważysz: + +- Tekst dokumentu jest zaznaczalny i przeszukiwalny. +- Pozioma linia jest niewidoczna dla czytników ekranu (traktowana jako artefakt). +- PDF przechodzi podstawowe narzędzia walidacji PDF/UA (np. PAC 3). + +## Krok 5: Weryfikacja dostępności – szybka lista kontrolna + +Mimo że Aspose.Words wykonuje większość pracy, dobrą praktyką jest weryfikacja wyniku. + +| Sprawdzenie | Jak zweryfikować | +|------------|-------------------| +| **Tytuł dokumentu** | Otwórz Acrobat → Plik → Właściwości → Pole Tytuł (powinien odpowiadać `pdfOptions.setTitle`). | +| **Oznaczanie artefaktów** | Użyj narzędzia „Kolejność czytania” w Acrobat. Poziome linie powinny pojawić się jako *Artefakt* (szare). | +| **Logiczna kolejność czytania** | Uruchom „Sprawdzacz dostępności” w Acrobat; upewnij się, że nie ma błędów strukturalnych. | +| **PDF z tagami** | W Acrobat, w panelu „Tagi” – powinieneś zobaczyć hierarchię (Document → Section → Paragraph, itp.). | +| **Zgodność PDF/UA** | Acrobat wyświetli „PDF/UA‑2” w zakładce „Standardy”. | + +Jeśli którykolwiek z tych testów nie powiedzie się, sprawdź ponownie, czy używasz najnowszej wersji Aspose.Words oraz czy `setCompliance(PdfCompliance.PDF_UA_2)` jest poprawnie zastosowane. + +## Typowe pułapki i jak ich uniknąć + +1. **Brak licencji** – Wersja próbna dodaje znak wodny, który może złamać walidację PDF/UA. Zastosuj licencję wcześnie w metodzie `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Nieprawidłowa ścieżka wejściowa** – `FileNotFoundException` zatrzyma konwersję. Użyj ścieżek bezwzględnych lub umieść DOCX w katalogu głównym projektu i odwołuj się do niego za pomocą `new File("input.docx").getAbsolutePath()`. +3. **Używanie starszej wersji Aspose** – Obsługa PDF/UA została dodana w wersji 22.9. Zaktualizuj do najnowszej wersji, aby uniknąć brakujących funkcji. +4. **Pozioma linia jako obraz** – Jeśli wstawiłeś linię jako obraz zamiast natywnej poziomej linii Worda, Aspose traktuje ją jako zwykły obraz, nie jako artefakt. Zamień obraz na wbudowaną w Word *Poziomą linię* dla prawidłowego oznaczania. + +## Rozszerzanie rozwiązania – co zrobić, jeśli potrzebujesz więcej? + +- **Niestandardowe tagi**: Jeśli masz inne elementy dekoracyjne (np. ikony dekoracyjne), możesz ręcznie oznaczyć je jako artefakty używając `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Wiele dokumentów**: Przejdź pętlą po folderze plików DOCX i konwertuj je wsadowo, ponownie używając tej samej instancji `PdfSaveOptions` dla wydajności. +- **Dodanie tagu języka**: Dla wielojęzycznych PDF‑ów ustaw `pdfOptions.setLanguage("en-US")`, aby pomóc technologiom wspomagającym wybrać odpowiedni głos. + +## Pełny działający przykład (cały kod razem) + +Poniżej znajduje się kompletny, gotowy do uruchomienia program Java. Skopiuj‑wklej go do swojego IDE, dostosuj ścieżki i uruchom. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Uruchom go, otwórz wygenerowany PDF i będziesz mieć czysty, dostępny plik gotowy do dystrybucji. + +## Podsumowanie + +Właśnie pokazaliśmy, jak **zapisać dokument jako pdf** przy użyciu Aspose.Words dla Java, automatycznie **dodając dostępność do pdf** i **oznaczając poziome linie** jako artefakty. Najważniejsze wnioski: + +- Użyj `PdfSaveOptions` z zgodnością `PDF_UA_2`, aby spełnić standardy dostępności. +- Załadowanie DOCX i wywołanie `doc.save(..., pdfOptions)` to wszystko, czego potrzebujesz, aby **konwertować docx na pdf**. +- Poziome linie są obsługiwane automatycznie — nie wymaga dodatkowego kodu, spełniając wymóg **oznaczania poziomych linii**. +- Podejście jest w pełni zgodne z **aspose convert docx pdf**, działa z najnowszą wersją biblioteki i generuje PDF gotowy do walidacji. + +Gotowy na kolejne wyzwanie? Spróbuj dodać własne metadane, osadzić czcionki lub przetwarzać wsadowo cały folder plików DOCX. Każde z tych rozszerzeń opiera się na tej samej podstawie, którą tutaj przedstawiliśmy. + +Masz pytania dotyczące zgodności z PDF/UA, licencjonowania lub obsługi innych elementów Worda? Zostaw komentarz lub sprawdź oficjalną dokumentację Aspose — znajdziesz tam mnóstwo przykładów do przestudiowania. Szczęśliwego kodowania i przyjemnego tworzenia dostępnych PDF‑ów! + +![zapisz dokument jako pdf przy użyciu Aspose.Words Java – przykład dostępnego PDF](placeholder-image.png "zapisz dokument jako pdf przy użyciu Aspose.Words Java – przykład dostępnego PDF") + +## Powiązane samouczki + +- [Jak zapisać dokument jako pdf przy użyciu Aspose.Words dla Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Jak konwertować Word na PDF przy użyciu Aspose.Words dla Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – konwersja DOCX do PDF w Javie](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/polish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..4ba0826415 --- /dev/null +++ b/words/polish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Zapisz dokument Word jako markdown i odkryj, jak eksportować równania + matematyczne do LaTeX przy użyciu Aspose.Words dla Javy. Konwertuj równania Worda + na LaTeX w zaledwie kilku linijkach. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: pl +og_description: Zapisz dokument Word jako markdown i dowiedz się, jak eksportować + równania matematyczne do LaTeX przy użyciu Aspose.Words for Java. Kompletny, gotowy + do uruchomienia przewodnik. +og_title: Zapisz Word jako markdown – Eksportuj matematykę do LaTeX w Javie +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Zapisz Worda jako markdown – Eksportuj matematykę do LaTeX w Javie +url: /pl/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Zapisz Word jako markdown – Eksportuj równania do LaTeX w Javie + +Czy kiedykolwiek potrzebowałeś **save word as markdown**, ale obawiałeś się, że twoje równania zamienią się w nieczytelny bałagan? Nie jesteś sam. W tym przewodniku pokażemy **how to export math** z pliku `.docx` bezpośrednio do LaTeX, podczas gdy reszta dokumentu stanie się czystym Markdownem. + +Omówimy wszystko, od skonfigurowania biblioteki Aspose.Words po weryfikację końcowego pliku `out.md`. Po zakończeniu będziesz mógł **convert word equations latex** w jednym wywołaniu metody i zrozumiesz drobne niuanse, które sprawiają, że konwersja jest niezawodna. + +--- + +## Czego będziesz potrzebować + +- **Java 8+** – kod działa na dowolnym nowoczesnym JDK. +- **Aspose.Words for Java** – zależność Maven/Gradle lub plik JAR, jeśli wolisz ręczną konfigurację. +- Dokument Word (`math.docx`) zawierający przynajmniej jedno równanie Office Math. +- IDE lub zwykła linia poleceń `javac`/`java` – cokolwiek jest dla Ciebie wygodne. + +Jeśli już je masz, świetnie. Jeśli nie, kolejna sekcja pokazuje dokładnie, jak dodać bibliotekę do projektu. + +--- + +## Zapisz Word jako markdown – Krok 1: Dodaj Aspose.Words do swojego projektu + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose oferuje darmową tymczasową licencję do testów. Umieść plik `license.xml` w folderze resources i wywołaj `License license = new License(); license.setLicense("license.xml");` przed załadowaniem jakiegokolwiek dokumentu. + +Gdy zależność zostanie rozwiązana, możesz przystąpić do pisania kodu konwersji. + +--- + +## Jak wyeksportować równania matematyczne do LaTeX + +Ciężka praca jest wykonywana przez `MarkdownSaveOptions`. Przełączając jego `OfficeMathExportMode` na `LATEX`, każdy obiekt Office Math jest renderowany jako fragment LaTeX w wyjściowym Markdownzie. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Dlaczego to działa + +- **`Document`** jest punktem wejścia Aspose; abstrahuje plik `.docx` i daje dostęp do każdego węzła, w tym równań. +- **`MarkdownSaveOptions`** informuje bibliotekę, *jak* ma wyglądać wyjście. Domyślne zachowanie to renderowanie równań jako obrazy, co przeczy celowi formatu tekstowego. +- **`OfficeMathExportMode.LATEX`** zmusza silnik do przetłumaczenia każdego węzła `OfficeMath` na jego odpowiednik w LaTeX, który parsery Markdown (takie jak GitHub czy Jekyll) mogą renderować w połączeniu z wtyczką MathJax. + +--- + +## Konwertuj równania Word do LaTeX – Krok 2: Zweryfikuj wyjście Markdown + +Po uruchomieniu programu otwórz `out.md`. Powinieneś zobaczyć coś podobnego: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Uwaga:** Fragmenty LaTeX są otoczone `$…$` dla matematyki w linii oraz `$$…$$` dla matematyki blokowej. To standardowa składnia, którą rozumie większość generatorów stron statycznych, gdy włączony jest MathJax. + +Jeśli wolisz, aby równania pozostały tylko w linii, możesz dodatkowo dostosować `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx do markdown latex – Krok 3: Przypadki brzegowe i typowe pułapki + +| Sytuacja | Na co zwrócić uwagę | Rozwiązanie | +|-----------|-------------------|-----| +| **Złożone zagnieżdżone równania** | Aspose może wygenerować dodatkowe nawiasy `{}`, które niektóre parsery traktują dosłownie. | Przetwórz Markdown prostym wyrażeniem regularnym, aby zredukować `{{` → `{`. | +| **Brak MathJax na docelowej stronie** | Równania wyświetlają się jako surowy kod LaTeX. | Add `` to your HTML template. | +| **Duże dokumenty** | Zużycie pamięci rośnie, ponieważ cały dokument jest ładowany jednocześnie. | Use `LoadOptions.setLoadFormat(LoadFormat.DOCX)` and consider processing pages in batches if you hit `OutOfMemoryError`. | +| **Licencja nie ustawiona** | Otrzymasz ostrzeżenie i wyjście może być oznaczone znakiem wodnym. | Load the license early in `main` as shown in the Maven tip above. | + +--- + +## Zapisz Word jako markdown – Pełny działający przykład + +Poniżej znajduje się samodzielna klasa, którą możesz skopiować i wkleić do dowolnego projektu Java. Po prostu zamień `YOUR_DIRECTORY` na ścieżkę do swoich plików. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Uruchom program (`java MathToLatexMarkdown`) i zobaczysz komunikat w konsoli potwierdzający sukces. Otwórz `out.md` w dowolnym edytorze – równania powinny być czystymi fragmentami LaTeX gotowymi do renderowania. + +--- + +## Oczekiwany zrzut ekranu wyniku + +![zapisz word jako markdown wynik z równaniami LaTeX](https://example.com/images/markdown-latex-output.png "zapisz word jako markdown wynik z równaniami LaTeX") + +*Obraz przedstawia fragment wygenerowanego Markdownu, w którym równanie `\int_{a}^{b} f(x)\,dx` jest otoczone `$$`.* + +--- + +## Zakończenie + +Właśnie pokazaliśmy, jak **save word as markdown** zachowując każde równanie Office Math jako natywny LaTeX. Kluczowym krokiem było skonfigurowanie `MarkdownSaveOptions` z `OfficeMathExportMode.LATEX`, co przekształca typowy proces konwersji Word‑do‑Markdown w w pełni świadome matematyki narzędzie konwersji. + +Teraz możesz: + +1. **How to export math** z dowolnego `.docx` bez utraty dokładności. +2. **Convert word equations latex** dla generatorów stron statycznych, dokumentacji lub blogów akademickich. +3. Rozszerz podejście, aby przetwarzać wsadowo wiele plików, integrować z pipeline’ami CI lub nawet zbudować małą usługę webową. + +Jeśli jesteś ciekawy kolejnych możliwości, spróbuj połączyć to z **docx to markdown latex** dla dokumentów z dużą ilością obrazów lub zbadaj `HtmlSaveOptions` Aspose dla wersji HTML gotowej do sieci. Możliwości są nieograniczone — eksperymentuj, łam rzeczy i potem podziel się swoimi odkryciami ze społecznością. + +Masz pytania lub trudne równanie, które nie zostało poprawnie wyrenderowane? Dodaj komentarz poniżej i powodzenia w kodowaniu! + +## Powiązane tutoriale + +- [Jak wyeksportować LaTeX z Worda: konwertuj DOCX do Markdown i zapisz jako PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Konwertuj docx do markdown – Eksportuj równania matematyczne do LaTeX przy użyciu Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Jak konwertować Word do PDF przy użyciu Aspose.Words dla Javy](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/polish/java/document-loading-and-saving/_index.md index b7a7941009..d34b580c7a 100644 --- a/words/polish/java/document-loading-and-saving/_index.md +++ b/words/polish/java/document-loading-and-saving/_index.md @@ -46,7 +46,7 @@ Poniżej znajduje się zwięzły opis typowego przepływu pracy. (Rzeczywisty ko 1. **Utwórz instancję `Document`** – załaduj źródłowy plik Word (`.docx`, `.doc` itp.). 2. **Iteruj przez `NodeCollection` dokumentu** aby znaleźć węzły `Shape` zawierające obrazy. -3. **Wyodrębnij każdy obraz** za pomocą API `Shape.getImageData()` i zapisz go do pliku używając `ImageData.save()`. +3. **Wyodrębnij każdy obraz** za pomocą API `Shape.getImageData()` i zapisz go do pliku użyjąc `ImageData.save()`. > *Wskazówka:* Użyj `Document.getChildNodes(NodeType.SHAPE, true)`, aby pobrać wszystkie kształty, w tym znajdujące się w nagłówkach, stopkach i przypisach. @@ -136,6 +136,8 @@ Kompletny przewodnik, jak naprawić uszkodzone pliki DOCX i przywrócić ich zaw ### [Rejestrowanie ostrzeżeń o podstawianiu czcionek w Javie przy użyciu Aspose.Words – Kompletny przewodnik](./capture-font-substitution-warnings-in-java-with-aspose-words/) Dowiedz się, jak przechwytywać i obsługiwać ostrzeżenia o podstawianiu czcionek w dokumentach Word przy użyciu Aspose.Words for Java. +### [Otwórz uszkodzony dokument Word – ustaw tryb odzyskiwania w Javie](./open-corrupted-word-document-set-recovery-mode-in-java/) + ## Najczęściej zadawane pytania **Q:** Jak programowo **save images from word** dokumenty? diff --git a/words/polish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/polish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..83a8c64f54 --- /dev/null +++ b/words/polish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Otwórz uszkodzony dokument Word w Javie przy użyciu Aspose.Words. Dowiedz + się, jak ustawić tryb odzyskiwania i niezawodnie przywrócić uszkodzone pliki Word. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: pl +og_description: Otwórz uszkodzony dokument Word w Javie przy użyciu Aspose.Words. + Ten przewodnik pokazuje, jak ustawić tryb odzyskiwania i skutecznie przywrócić uszkodzone + pliki Word. +og_title: Otwórz uszkodzony dokument Word – ustaw tryb odzyskiwania w Javie +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Otwórz uszkodzony dokument Word – ustaw tryb odzyskiwania w Javie +url: /pl/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Otwieranie uszkodzonego dokumentu Word – ustaw tryb odzyskiwania w Javie + +Czy kiedykolwiek próbowałeś otworzyć uszkodzony dokument Word i zobaczyłeś, jak program wywala wyjątek? Nie jesteś sam — te zepsute pliki .docx mogą być prawdziwą uciążliwością. Dobrą wiadomością jest to, że Aspose.Words for Java daje Ci precyzyjną kontrolę, dzięki czemu możesz **otworzyć uszkodzony dokument Word** bez awarii aplikacji i samodzielnie zdecydować, czy chcesz otrzymywać ostrzeżenia, ciche odzyskiwanie, czy twarde odrzucenie. + +W tym samouczku przeprowadzimy Cię przez cały proces: od stworzenia odpowiedniego `LoadOptions`, przez wybranie właściwej wartości **set recovery mode**, aż po potwierdzenie, że dokument został rzeczywiście załadowany. Po zakończeniu będziesz wiedział, **jak odzyskać uszkodzony plik Word** programowo, bez ręcznego kopiowania‑wklejania. + +> **Czego potrzebujesz** +> * Java 8 lub nowsza (API działa również z Java 11) +> * Aspose.Words for Java 23.9 (lub najnowsza wersja) +> * Przykładowy uszkodzony .docx ‑ po prostu zmień nazwę dowolnego prawidłowego pliku, aby zasymulować uszkodzenie, jeśli nie masz takiego pod ręką + +Zanurzmy się. + +## Otwieranie uszkodzonego dokumentu Word – przegląd krok po kroku + +Poniżej znajduje się wysokopoziomowy przepływ, który zaimplementujemy: + +1. **Utwórz `LoadOptions`** – ten obiekt informuje Aspose.Words, jak zachować się w sytuacji problemowej. +2. **Ustaw tryb odzyskiwania** – wybierz `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` lub `REJECT_CORRUPTED`. +3. **Załaduj dokument** używając skonfigurowanych opcji. +4. **Zweryfikuj**, że ładowanie się powiodło (np. wypisz liczbę stron). + +Każdy krok jest wyjaśniony szczegółowo, wraz z fragmentami kodu, które możesz skopiować i wkleić bezpośrednio do swojego IDE. + +## Ustawianie trybu odzyskiwania dla różnych scenariuszy + +Aspose.Words definiuje trzy strategie odzyskiwania w `LoadOptions.RecoveryMode`: + +| Tryb | Zachowanie | Kiedy używać | +|------|------------|--------------| +| `RECOVER_WITH_WARNINGS` | Próbuje załadować dokument, ale wyświetla wszelkie problemy jako ostrzeżenia w konsoli. | Chcesz zobaczyć *co* poszło nie tak, nie przerywając działania. | +| `RECOVER_WITHOUT_WARNINGS` | Cicho naprawia, co się da, i tłumi ostrzeżenia. | Środowiska produkcyjne, w których logi muszą pozostać czyste. | +| `REJECT_CORRUPTED` | Rzuca wyjątek w momencie wykrycia uszkodzenia. | Ścisłe potoki walidacji, które muszą szybko zakończyć się niepowodzeniem. | + +Wybranie właściwego trybu jest istotą **set recovery mode**. W większości sesji debugowania `RECOVER_WITH_WARNINGS` jest optymalnym wyborem, ponieważ dokładnie informuje, które części zostały naprawione. + +## Jak odzyskać uszkodzony plik Word przy użyciu Aspose.Words + +Poniżej znajduje się **kompletny, gotowy do uruchomienia program w Javie**, który demonstruje cały proces. Wystarczy, że wkleisz go do pliku `RecoveryModeDemo.java`, dostosujesz ścieżkę i uruchomisz. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Dlaczego każdy wiersz ma znaczenie + +* **`LoadOptions loadOptions = new LoadOptions();`** – bez tego obiektu Aspose.Words używa domyślnego odzyskiwania, które *odrzuca* uszkodzone pliki. Utworzenie go daje Ci punkt zaczepienia do zmiany tego zachowania. +* **`setRecoveryMode(...)`** – to wywołanie **set recovery mode**, które decyduje, czy ostrzeżenia będą wyświetlane, ukryte, czy spowodują wyjątek. +* **`new Document(path, loadOptions);`** – konstruktor przyjmuje właśnie skonfigurowane `LoadOptions`, więc biblioteka od razu wie, jak traktować uszkodzony plik. +* **`doc.getPageCount()`** – szybka kontrola poprawności. Jeśli dokument się załaduje i zwróci liczbę stron, udało Ci się **jak odzyskać uszkodzony plik Word**. +* **`doc.save(...)`** – opcjonalne, ale przydatne; możesz zapisać naprawioną wersję na dysku do późniejszego użycia. + +## Obsługa typowych przypadków brzegowych + +### 1. Plik nie został znaleziony + +Jeśli ścieżka jest nieprawidłowa, `Document` rzuca `FileNotFoundException`. Owiń ładowanie w blok try‑catch i zaloguj przyjazny komunikat: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Nieodwracalne uszkodzenie + +Nawet przy `RECOVER_WITH_WARNINGS` niektóre struktury mogą być poza naprawą. W takim wypadku Aspose.Words i tak załaduje to, co się da, ale zobaczysz ostrzeżenia typu „Cannot read paragraph properties”. Zwróć uwagę na wyjście konsoli; te ostrzeżenia często wskazują brakujące sekcje, które możesz musieć odtworzyć ręcznie. + +### 3. Duże pliki i wydajność + +Odzyskiwanie wprowadza niewielki narzut, ponieważ biblioteka parsuje plik dwa razy — raz, aby wykryć problemy, drugi raz, aby je odbudować. Dla dokumentów wielogigabajtowych rozważ strumieniowe przetwarzanie pliku lub zwiększenie pamięci JVM (`-Xmx2g`), aby uniknąć `OutOfMemoryError`. + +## Pro Tips – jak uczynić odzyskiwanie odpornym + +* **Loguj ostrzeżenia do pliku** – przekieruj `System.err` do loggera, aby mieć ślad audytowy tego, co zostało naprawione. +* **Waliduj po odzyskaniu** – wywołaj `doc.updatePageLayout();` i ponownie sprawdź liczbę stron; czasami układ zmienia się po naprawie uszkodzonych sekcji. +* **Automatyzuj wsadowe odzyskiwanie** – otocz demo pętlą, która przetwarza folder z uszkodzonymi plikami, używając tego samego `LoadOptions` przy każdym przebiegu. + +## Podsumowanie + +Teraz wiesz dokładnie, **jak odzyskać uszkodzony plik Word** przy użyciu Aspose.Words for Java. Tworząc instancję `LoadOptions`, **set recovery mode** na strategię pasującą do Twojego scenariusza i ładując dokument z tymi opcjami, możesz bezpiecznie **otworzyć uszkodzony dokument Word** bez wywoływania awarii aplikacji. Powyższy przykładowy kod to kompletny, gotowy do uruchomienia zestaw, który wypisuje liczbę stron i nawet zapisuje oczyszczoną kopię. + +Co dalej? Spróbuj zamienić tryb odzyskiwania na `RECOVER_WITHOUT_WARNINGS` i porównaj wyjście konsoli, albo poeksperymentuj z ładowaniem zaszyfrowanych dokumentów (będziesz musiał podać hasło poprzez + +## Powiązane samouczki + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/polish/java/document-styling/_index.md index d2b9cfd45c..fbca813e2c 100644 --- a/words/polish/java/document-styling/_index.md +++ b/words/polish/java/document-styling/_index.md @@ -43,6 +43,8 @@ Dowiedz się, jak dostosować motywy dokumentów za pomocą Aspose.Words for Jav Dowiedz się, jak stosować znaki wodne i konfigurować strony za pomocą Aspose.Words dla Java. Kompleksowy przewodnik z kodem źródłowym. ### [Stylizacja nagłówka i stopki dokumentu](./document-header-footer-styling/) Dowiedz się, jak stylizować nagłówki i stopki dokumentów za pomocą Aspose.Words for Java w tym szczegółowym przewodniku. Dołączono instrukcje krok po kroku i kod źródłowy. +### [Ustaw domyślne ustawienia czcionki w Aspose.Words dla Javy – Kompletny przewodnik](./set-default-font-settings-in-aspose-words-for-java-complete/) +Dowiedz się, jak ustawić domyślne czcionki w dokumentach przy użyciu Aspose.Words dla Javy. Przewodnik krok po kroku z przykładami kodu. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/polish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..09ac56e402 --- /dev/null +++ b/words/polish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: Ustaw domyślne ustawienia czcionki w Aspose.Words for Java i dowiedz + się, jak konfigurować ustawienia czcionki oraz wykrywać brakujące czcionki w zaledwie + kilku linijkach kodu. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: pl +og_description: Ustaw domyślne ustawienia czcionki w Aspose.Words for Java, dowiedz + się, jak konfigurować ustawienia czcionki i szybko oraz niezawodnie wykrywać brakujące + czcionki. +og_title: Ustaw domyślne ustawienia czcionki w Aspose.Words dla Javy +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Ustaw domyślne ustawienia czcionki w Aspose.Words dla Javy – Kompletny przewodnik +url: /pl/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ustaw domyślne ustawienia czcionki w Aspose.Words dla Javy – Kompletny przewodnik + +Zastanawiałeś się kiedyś, jak **ustawić domyślne ustawienia czcionki** podczas ładowania dokumentu Word przy użyciu Aspose.Words dla Javy? Nie jesteś sam. Brakujące glify mogą zamienić dopracowany raport w zniekształcony bałagan, a wczesne wykrywanie ostrzeżeń o zamianie czcionek oszczędza godziny debugowania. + +W tym samouczku przeprowadzimy Cię przez zwięzły, kompleksowy przykład, który **ustawia domyślne ustawienia czcionki**, pokazuje, jak **ustawić ustawienia czcionki** programowo, oraz demonstruje niezawodny sposób na **wykrywanie brakujących czcionek** zanim zepsują one układ. + +--- + +## Co się nauczysz + +- Jak utworzyć obiekt `LoadOptions` z nową instancją `FontSettings`. +- Jak dołączyć nasłuchiwacz ostrzeżeń, który **wykryje brakujące czcionki** podczas ładowania dokumentu. +- Jak załadować plik DOCX, podczas gdy nasłuchiwacz cicho raportuje wszelkie zamiany. +- Porady dotyczące dostosowywania czcionek zastępczych i obsługi przypadków brzegowych w środowisku produkcyjnym. + +Bez dodatkowych bibliotek, bez niejasnych plików konfiguracyjnych — tylko czysta Java i Aspose.Words. + +--- + +## Wymagania wstępne + +1. **Aspose.Words for Java** (wersja 23.10 lub nowsza) w classpath. +2. Zestaw programistyczny Java 17 (lub nowszy) — dowolny nowoczesny JDK działa. +3. Plik DOCX, który celowo używa czcionki, której nie masz zainstalowanej (np. *„MissingFont.ttf”*). + +Jeśli brakuje Ci pliku JAR Aspose, pobierz go z oficjalnego repozytorium Maven: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +To wszystko — nie trzeba instalować dodatkowych czcionek do tego demo. + +--- + +## Krok 1: Utwórz LoadOptions i **Ustaw domyślne ustawienia czcionki** + +Pierwszą rzeczą, której potrzebujemy, jest czysty obiekt `LoadOptions`, który mówi Aspose, jak zachować się przy napotkaniu nieznanych krojów pisma. Wywołując `setFontSettings(new FontSettings())` **ustawiamy domyślne ustawienia czcionki**, które zaczynają się od pustej listy zastępczych. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Dlaczego to ważne:** +> Gdy nie skonfigurujesz czcionek explicite, Aspose odwołuje się do domyślnej kolekcji systemowej, co może ukrywać problemy z brakującymi czcionkami. Rozpoczynając od nowej instancji `FontSettings`, zyskujesz pełną kontrolę nad tym, które czcionki są uznawane za prawidłowe. + +--- + +## Krok 2: Dołącz nasłuchiwacz ostrzeżeń, aby **Wykrywać brakujące czcionki** + +Aspose generuje obiekt `WarningInfo` dla każdej wykonanej zamiany. Nasłuchując `WarningType.FONT_SUBSTITUTION`, możemy **wykrywać brakujące czcionki** natychmiast po przetworzeniu dokumentu. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro tip:** Nasłuchiwacz działa w tym samym wątku, w którym ładowany jest dokument, więc praktycznie nie wpływa na wydajność. Jeśli potrzebujesz zebrać ostrzeżenia do późniejszej analizy, umieść je w `List` zamiast drukować od razu. + +--- + +## Krok 3: Załaduj dokument przy użyciu skonfigurowanych opcji + +Teraz, gdy **ustawiliśmy ustawienia czcionki** i przygotowaliśmy nasłuchiwacz, po prostu ładujemy plik. Każda brakująca czcionka natychmiast wywołuje nasz callback. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Jeśli plik źródłowy odwołuje się do czcionki, której nie ma zainstalowanej, zobaczysz wyjście podobne do: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Ten wiersz dokładnie informuje, której czcionki brakowało i jaka zastępcza została użyta — idealne do logowania lub informacji zwrotnej dla użytkownika. + +--- + +## Krok 4: Kontynuuj normalne przetwarzanie (opcjonalnie) + +W tym momencie dokument jest w pełni załadowany i możesz przystąpić do dowolnej manipulacji — edycji, konwersji do PDF czy wyodrębniania tekstu. Nasłuchiwacz ostrzeżeń już wykonał swoją pracę, więc nie potrzebujesz dodatkowych sprawdzeń. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Co zrobić, jeśli potrzebujesz własnego zastępstwa?** +> Zamiast zostawiać `FontSettings` pusty, możesz dodać konkretne czcionki: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Teraz każda brakująca czcionka zostanie zastąpiona *Times New Roman* — niezawodnym wyborem dla większości zachodnich dokumentów. + +--- + +## Przegląd wizualny + +![Diagram przedstawiający, jak ustawić domyślne ustawienia czcionki w Aspose.Words dla Javy](image.png "Diagram przepływu ustawiania domyślnych ustawień czcionki") + +Diagram ilustruje przepływ od inicjalizacji `LoadOptions` (gdzie **ustawiamy domyślne ustawienia czcionki**) przez dołączenie nasłuchiwacza ostrzeżeń (aby **wykrywać brakujące czcionki**) aż po załadowanie dokumentu. + +--- + +## Typowe pułapki i jak ich uniknąć + +| Pułapka | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| **Zapomniano wywołać `setFontSettings`** | Aspose używa domyślnych czcionek systemowych, ukrywając brakujące czcionki. | Zawsze twórz nową instancję `FontSettings` i przypisuj ją do `LoadOptions`. | +| **Nasłuchiwacz nie uruchamia się** | Nasłuchiwacz został dodany po załadowaniu dokumentu. | Dodaj nasłuchiwacz ostrzeżeń *przed* wywołaniem `new Document(...)`. | +| **Błąd literówki w ścieżce prowadzi do `FileNotFoundException`** | Ścieżka zapisana na sztywno nie pasuje do wrażliwości systemu na wielkość liter. | Użyj `Paths.get("...").toAbsolutePath()` lub skonfiguruj ścieżkę względną od katalogu głównego projektu. | +| **Wiele brakujących czcionek przytłacza logi** | Duże dokumenty mogą generować dziesiątki ostrzeżeń. | Filtruj duplikaty lub agreguj komunikaty w `Set` przed wypisaniem. | + +--- + +## Rozszerzanie rozwiązania + +Jeśli potrzebujesz **ustawić ustawienia czcionki** dla całej aplikacji, rozważ stworzenie singletonu `FontSettings` i ponowne używanie go we wszystkich `LoadOptions`. Dzięki temu utrzymasz spójną strategię zastępczą i unikniesz wielokrotnego tworzenia obiektów. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Teraz dowolna część Twojego kodu może po prostu wywołać `FontConfig.getLoadOptions()` i natychmiast skorzystać z tej samej logiki **ustawiania domyślnych ustawień czcionki**. + +--- + +## Podsumowanie + +Właśnie omówiliśmy wszystko, co potrzebne, aby **ustawić domyślne ustawienia czcionki** w Aspose.Words dla Javy, **ustawić ustawienia czcionki** programowo oraz **wykrywać brakujące czcionki** zanim zepsują one Twój wynik. Pełny, działający przykład znajduje się w powyższych fragmentach kodu i możesz go wkleić bezpośrednio do swojego IDE, aby zobaczyć ostrzeżenia w akcji. + +Co dalej? Spróbuj zamienić czcionkę zastępczą, eksperymentuj z różnymi formatami dokumentów (DOC, RTF, HTML) lub zintegrować zbieracz ostrzeżeń z panelem monitoringu. Im więcej bawisz się `FontSettings`, tym większą pewność będziesz mieć, że generowane dokumenty wyglądają dokładnie tak, jak powinny — bez niespodzianek, bez zepsutych glifów. + +Masz pytania lub trudny scenariusz zamiany czcionek? zostaw komentarz poniżej i powodzenia w kodowaniu! + +## Powiązane samouczki + +- [Ustawienia zastępczych czcionek](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Ustawienia zastępczych czcionek](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Ustawienia zastępczych czcionek](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/java/images-shapes/_index.md b/words/polish/java/images-shapes/_index.md index e45c986bea..bbead205e7 100644 --- a/words/polish/java/images-shapes/_index.md +++ b/words/polish/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Dowiedz się, jak generować wysokiej jakości miniatury i mapy bitowe o niestan ### [Utwórz dokument Word w Javie – Dodaj prostokątny kształt z efektem cienia](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Dowiedz się, jak dodać prostokątny kształt z efektem cienia do dokumentu Word przy użyciu Aspose.Words dla Java. +### [Utwórz prostokątny kształt w dokumencie Word w Javie – Pełny przewodnik krok po kroku](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Dowiedz się, jak w pełni krok po kroku dodać prostokątny kształt do dokumentu Word przy użyciu Aspose.Words dla Java. + ## Dodatkowe zasoby - [Aspose.Words dla dokumentacji Java](https://reference.aspose.com/words/java/) diff --git a/words/polish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/polish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..6576668f78 --- /dev/null +++ b/words/polish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-26 +description: Utwórz prostokątny kształt w dokumencie Word w Javie i zastosuj efekt + cienia. Dowiedz się, jak dodać cień do kształtu, ustawić odległość cienia i zapisać + plik. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: pl +og_description: Utwórz prostokątny kształt w dokumencie Word w Javie, zastosuj efekt + cienia, dodaj cień do kształtu i ustaw odległość cienia przy użyciu Aspose.Words. +og_title: Tworzenie prostokątnego kształtu w dokumencie Word w Javie – kompletny przewodnik +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Tworzenie prostokątnego kształtu w dokumencie Word w Javie – pełny przewodnik + krok po kroku +url: /pl/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tworzenie prostokątnego kształtu w dokumencie Word w Javie – Pełny przewodnik krok po kroku + +Kiedykolwiek potrzebowałeś **create rectangle shape** w dokumencie Word w Javie, ale nie wiedziałeś, od czego zacząć? Nie jesteś sam — wielu programistów napotyka ten problem przy generowaniu raportów lub faktur w sposób programowy. W tym samouczku pokażemy dokładnie, jak **create rectangle shape**, dodać elegancki cień oraz precyzyjnie ustawić odległość cienia, aby rezultat wyglądał profesjonalnie. + +Użyjemy Aspose.Words for Java, solidnej biblioteki umożliwiającej manipulację plikami Word bez konieczności instalacji Microsoft Office. Po zakończeniu tego przewodnika będziesz w stanie tworzyć projekty **create word document java**, które **add shape shadow**, **apply shadow effect** i **set shadow distance** za pomocą kilku linijek kodu. + +--- + +## Co zbudujesz + +- Świeży plik `.docx` zawierający cyjanowy prostokąt. +- Realistyczny cień rzucany, rozmyty, nachylony i częściowo przezroczysty. +- Pełną kontrolę nad odległością cienia od kształtu. +- Gotową do uruchomienia klasę Java, którą możesz wkleić do dowolnego projektu Maven lub Gradle. + +Bez zewnętrznych narzędzi, bez ręcznych kroków w interfejsie — tylko czysty kod. + +--- + +## Wymagania wstępne + +- Java 8 lub nowsza (kod działa na Java 11, Java 17 itp.). +- Biblioteka Aspose.Words for Java (dostępna w Maven Central). +- Ulubione IDE lub edytor tekstu (IntelliJ IDEA, Eclipse, VS Code…). +- Podstawowa znajomość składni Javy. + +Jeśli nigdy wcześniej nie dodawałeś zależności Maven, oto szybki fragment: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Teraz zanurzmy się w temat. + +--- + +## Krok 1: Create Rectangle Shape in a Word Document + +Pierwszą rzeczą, której potrzebujemy, jest pusty dokument i `DocumentBuilder`. Myśl o builderze jak o piórze, które pisze do dokumentu. Gdy już go mamy, możemy **create rectangle shape** jednym wywołaniem metody. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Dlaczego to ważne:** Metoda `insertShape` nie tylko tworzy geometrię, ale także dodaje kształt do wewnętrznej kolekcji dokumentu, dzięki czemu możesz od razu rozpocząć jego stylizację. + +--- + +## Krok 2: Apply Shadow Effect to the Shape + +Teraz, gdy prostokąt znajduje się na stronie, **apply shadow effect**. Cienie dodają głębi, sprawiając, że kształt wydaje się unosić nad stroną — subtelna poprawa UI, która może zwiększyć czytelność raportów. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro tip:** Rozmycie `5.0` wygląda naturalnie w większości dokumentów wyświetlanych na ekranie. Jeśli drukujesz, możesz chcieć nieco niższą wartość, aby uniknąć rozmytego wyglądu. + +--- + +## Krok 3: Set Shadow Distance – Fine‑Tuning Placement + +Cienie to nie tylko rozmycie; potrzebny jest także odpowiedni offset. Tutaj **set shadow distance**. Odległość `7.0` punktów tworzy umiarkowany offset, który jest zauważalny, ale nie przytłaczający. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Co zrobić, gdy potrzebny jest większy offset?** Zwiększ wartość; zmniejsz ją, aby uzyskać bardziej zwarty wygląd. Pamiętaj, że odległość współpracuje z kątem, aby prawidłowo ustawić cień. + +--- + +## Krok 4: Save the Document – Persist Your Work + +Na koniec zapisujemy dokument na dysku. Zmień ścieżkę na miejsce, w którym chcesz przechowywać plik. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Uruchomienie klasy tworzy plik `shadow.docx`, który po otwarciu w Microsoft Word lub LibreOffice pokazuje cyjanowy prostokąt z miękkim szarym cieniem nachylonym pod kątem 45° i przesuniętym o 7 punktów. + +--- + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do skopiowania kod. Zawiera wszystkie importy, komentarze i końcowe wywołanie `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Oczekiwany wynik:** Otwórz `shadow.docx` → zobaczysz cyjanowy prostokąt wyśrodkowany na pierwszej stronie, rzucający subtelny szary cień lekko przesunięty w dół‑w prawo. Rozmycie i przezroczystość cienia sprawiają wrażenie naturalnego oświetlenia. + +--- + +## Często zadawane pytania i przypadki brzegowe + +### „Czy mogę użyć innego kształtu?” + +Oczywiście. Zamień `ShapeType.RECTANGLE` na `ShapeType.OVAL`, `ShapeType.LINE` lub dowolny inny obsługiwany enum. Reszta kodu cienia pozostaje bez zmian. + +### „Co jeśli potrzebuję wielu cieni?” + +Aspose.Words obsługuje tylko jeden cień na kształt. Aby zasymulować wiele cieni, zduplikuj kształt, przesuwaj każdą kopię i dostosuj przezroczystość. + +### „Czy cień jest widoczny w LibreOffice?” + +Tak — Aspose.Words zapisuje standardowy OOXML, który LibreOffice prawidłowo interpretuje. Cień może wyglądać nieco inaczej ze względu na silniki renderujące, ale efekt pozostaje. + +### „Jak zmienić kolor cienia, aby pasował do mojej marki?” + +Po prostu zamień `java.awt.Color.GRAY` na dowolny `java.awt.Color`, np. `new java.awt.Color(0, 120, 215)` dla korporacyjnego niebieskiego. + +--- + +## Ilustracja + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illustration showing a cyan rectangle with a gray drop shadow in a Word document. + +--- + +## Podsumowanie i kolejne kroki + +Omówiliśmy, jak **create rectangle shape**, **apply shadow effect**, **add shape shadow** i **set shadow distance** przy użyciu Aspose.Words for Java. Kod jest samodzielny, działa na dowolnym nowoczesnym JDK i generuje elegancki plik `.docx` gotowy do dystrybucji. + +Chcesz pójść dalej? Spróbuj: + +- Dodać tekst wewnątrz prostokąta przy pomocy `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Stworzyć tabelę kształtów, aby zbudować diagram. +- Eksportować dokument do PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Każde z tych zadań opiera się na fundamentach, które właśnie poznaliśmy, więc będziesz czuł się pewnie rozszerzając przykład. + +--- + +## Końcowe przemyślenia + +Opanowanie zadań **create word document java** takich jak kształtowanie i cieniowanie daje ogromną przewagę przy automatyzacji raportów, umów czy materiałów marketingowych. Pokazana metoda jest czysta, łatwa w utrzymaniu i — co najważniejsze — prosta do dostosowania do dowolnego stylu wizualnego. + +Wypróbuj kod, zmień rozmycie, kąt i odległość, i zobacz, jak Twoje dokumenty przechodzą od nudnych do eleganckich. Jeśli napotkasz problem, zostaw komentarz poniżej; chętnie pomogę. + +Miłego kodowania! + + +## Powiązane samouczki + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/portuguese/java/document-conversion-and-export/_index.md index ec306fc7b0..fcd86969f1 100644 --- a/words/portuguese/java/document-conversion-and-export/_index.md +++ b/words/portuguese/java/document-conversion-and-export/_index.md @@ -95,6 +95,9 @@ Aprenda a formatar tabelas e aplicar estilos de tabela no Aspose.Words para Java ### [Converter docx para markdown – Exportar Equações Matemáticas para LaTeX com Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Aprenda a converter documentos DOCX em Markdown e exportar equações matemáticas para LaTeX usando Aspose.Words. +### [Salvar Word como Markdown – Exportar Matemática para LaTeX com Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Aprenda a salvar documentos Word como arquivos Markdown e exportar equações matemáticas para LaTeX usando Aspose.Words for Java. + ### [Aspose.Words para PDF – Converter DOCX para PDF em Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Aprenda a converter arquivos DOCX para PDF rapidamente usando Aspose.Words for Java. @@ -104,6 +107,15 @@ Aprenda a inserir imagens ao converter documentos DOCX para Markdown usando Aspo ### [Criar PDF Acessível a partir de DOCX – Guia Completo](./create-accessible-pdf-from-docx-complete-guide/) Aprenda a gerar PDFs acessíveis a partir de documentos DOCX usando Aspose.Words for Java, garantindo conformidade com normas de acessibilidade. +### [Salvar Documento como PDF com Aspose.Words Java – Guia Completo de Acessibilidade](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Aprenda a salvar documentos como PDF totalmente acessíveis usando Aspose.Words for Java, garantindo conformidade com normas de acessibilidade. + +### [Criar PDF Acessível em Java – Guia Completo de Marcação](./create-accessible-pdf-in-java-full-tagging-guide/) +Aprenda a gerar PDFs totalmente acessíveis em Java usando Aspose.Words, com tags completas para conformidade de acessibilidade. + +### [Exportar docx para txt com Java – Guia de Programação Completo](./export-docx-to-txt-with-java-complete-programming-guide/) +Aprenda a exportar documentos DOCX para arquivos TXT usando Aspose.Words for Java neste guia completo, com exemplos de código passo a passo. + ## Perguntas Frequentes **Q: Como adiciono uma marca d'água a um PDF existente usando Aspose.Words?** diff --git a/words/portuguese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/portuguese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..bc7aa259a0 --- /dev/null +++ b/words/portuguese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-26 +description: Crie PDFs acessíveis em Java com código passo a passo. Aprenda a marcar + PDFs para acessibilidade e habilitar a marcação de PDF usando PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: pt +og_description: Crie PDF acessível em Java com código passo a passo. Aprenda como + marcar PDF para acessibilidade e habilitar a marcação de PDF usando PdfSaveOptions. +og_title: Criar PDF acessível em Java – Guia completo de marcação +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Criar PDF acessível em Java – Guia completo de marcação +url: /pt/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar PDF Acessível em Java – Guia Completo de Marcação + +Já se perguntou como **criar PDFs acessíveis** diretamente a partir de código Java? Você não está sozinho. Muitos desenvolvedores precisam atender usuários que dependem de leitores de tela, e a diferença entre um PDF simples e um acessível pode ser enorme. Neste tutorial vamos percorrer **como marcar PDF para acessibilidade**, mostrar **como criar PDF marcado** com Aspose PDF for Java, e revelar os passos exatos para **adicionar tags de acessibilidade ao PDF** para que todo leitor receba as mesmas informações. + +Também abordaremos as melhores práticas para **ativar a marcação de PDF**, armadilhas comuns e um exemplo completo e executável que você pode inserir em seu projeto hoje. Sem referências vagas — apenas código concreto, explicações e um arquivo final que você pode abrir no Adobe Acrobat para verificar as tags. + +## O que você aprenderá + +- O porquê da marcação de PDF e conformidade de acessibilidade. +- Pré-requisitos e configuração da biblioteca (Aspose PDF for Java 23.10 ou posterior). +- Como **criar PDF acessível** do zero, passo a passo. +- Maneiras de **adicionar tags de acessibilidade ao PDF** além da chamada básica `setTagDocumentStructure`. +- Dicas para testar o resultado e solucionar problemas comuns. + +Ao final deste guia, você será capaz de gerar PDFs que passam nas verificações WCAG 2.1 AA e ainda têm aparência profissional. + +--- + +## Pré-requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +| Requisito | Motivo | +|-------------|--------| +| **Java 8+** | Recursos modernos da linguagem e melhor manipulação de Unicode. | +| **Aspose PDF for Java** (v23.10 ou newer) | Fornece a classe `PdfSaveOptions` e suporte à marcação. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Para compilação e depuração facilitadas. | +| **Write permission** to a folder where the PDF will be saved | A chamada `doc.save` requer um caminho gravável. | + +Se ainda não adicionou o Aspose PDF ao seu projeto, insira a seguinte dependência Maven no seu `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Dica profissional:** Use a versão mais recente; lançamentos mais novos melhoram a precisão da marcação e adicionam recursos de acessibilidade específicos por idioma. + +--- + +## Etapa 1: Configurar a Estrutura do Documento + +Primeiro, criamos um novo objeto `Document`. Pense nele como uma tela em branco que mais tarde conterá as tags necessárias para acessibilidade. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Por que isso importa:** Sem conteúdo, não há nada para marcar. Adicionar até mesmo um simples `TextFragment` fornece ao mecanismo de marcação algo para trabalhar, e ele cria automaticamente uma tag `

` (parágrafo) quando ativamos a marcação de estrutura posteriormente. + +--- + +## Etapa 2: Criar Opções de Salvamento de PDF (o Núcleo da Marcação) + +Agora preparamos as opções que instruem o Aspose PDF a incorporar uma árvore de estrutura lógica dentro do arquivo. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +A chamada `setTagDocumentStructure(true)` é o interruptor para **ativar a marcação de PDF**. Quando true, a biblioteca constrói uma árvore de tags que espelha o layout visual, tornando o PDF legível por tecnologias assistivas. + +> **Observação:** Esta é a maneira mais simples de **como criar PDF marcado**. Para controle mais granular (por exemplo, definir idioma ou tags personalizadas), você pode explorar `pdfOptions.setTagLanguage("en-US")` e `pdfOptions.setTagStructureTreeRoot(...)`. + +--- + +## Etapa 3: Salvar o PDF Acessível + +Finalmente, gravamos o documento no disco usando as opções que acabamos de configurar. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Quando `doc.save` terminar, você encontrará `accessible.pdf` na pasta `output`. Abra‑o no Adobe Acrobat e veja **File → Properties → Description → Tags** – você deverá ver uma árvore de tags preenchida. + +--- + +## Como Marcar PDF para Acessibilidade – Além do Básico + +O trecho de três etapas acima já **adiciona tags de acessibilidade ao PDF**, mas documentos do mundo real frequentemente precisam de um pouco mais de refinamento. Aqui estão algumas melhorias que você pode aplicar: + +### 1. Definir o Idioma do Documento + +Screen readers usam o atributo de idioma para pronunciar o texto corretamente. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Fornecer um Título e Assunto + +Metadados ajudam ferramentas assistivas a fornecer contexto antes mesmo de o usuário abrir o arquivo. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Marcar Imagens com Texto Alternativo + +Se você incorporar imagens, elas precisam de descrições `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Marcar Cabeçalhos de Tabela + +Tabelas são notórias por confundir leitores, a menos que você sinalize as linhas de cabeçalho. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Essas etapas adicionais tornam seu PDF não apenas *tecnicamente* marcado, mas verdadeiramente **acessível** para um público diversificado. + +--- + +## Armadilhas Comuns ao Ativar a Marcação de PDF + +| Sintoma | Causa Provável | Correção | +|---------|----------------|----------| +| Tags ausentes no Acrobat | `setTagDocumentStructure` deixado como `false` | Certifique‑se de chamar `pdfOptions.setTagDocumentStructure(true)`. | +| Ordem de leitura incorreta | Layout complexo sem tags explícitas | Use `pdfOptions.setTagStructureTreeRoot(...)` para definir uma ordem personalizada. | +| Imagens lidas como “imagem” sem descrição | Nenhum texto alternativo definido | Chame `image.getAlternativeText().setValue("...")`. | +| Idioma não reconhecido | `setTagLanguage` omitido ou local incorreto | Forneça um código de idioma BCP‑47 (`en-US`, `fr-FR`). | + +Estar ciente desses problemas economiza horas de depuração posteriormente. + +--- + +## Verificar o Resultado – O que Esperar + +Depois de executar o programa, abra `output/accessible.pdf` no Adobe Acrobat Reader: + +1. **Painel de Tags** (`View → Show/Hide → Navigation Panes → Tags`) deve listar uma hierarquia como `/Document → /Part → /Sect → /Para`. +2. **Ordem de leitura** deve seguir o fluxo visual (texto primeiro, depois imagens). +3. **Leitor de tela** (NVDA, VoiceOver) lerá “Hello, accessible PDF!” em vez de apenas “Page 1”. + +Se algum desses itens estiver ausente, verifique novamente as etapas acima — especialmente a chamada `setTagDocumentStructure`. + +--- + +## Exemplo Completo Funcional (Pronto para Copiar‑Colar) + + + +## Tutoriais Relacionados + +- [Criar PDF Acessível a partir do Word – Converter para PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Criar PDF Acessível a partir de DOCX – Guia Completo](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Como salvar documento como PDF com Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/portuguese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/portuguese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..0cc8a79ccb --- /dev/null +++ b/words/portuguese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Incorpore imagens como base64 enquanto converte docx para markdown com + Aspose.Words for Java. Aprenda a converter Word para markdown, salvar Word como + markdown e lidar com imagens. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: pt +og_description: Incorpore imagens como base64 ao converter docx para markdown com + Aspose.Words para Java. Guia completo para converter Word para markdown e salvar + Word como markdown. +og_title: Incorporar imagens como Base64 ao converter DOCX para Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Incorporar imagens como Base64 ao converter DOCX para Markdown +url: /pt/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Incorporar Imagens como Base64 ao Converter DOCX para Markdown + +Já se perguntou como **incorporar imagens como base64** enquanto **converte docx para markdown**? Você não está sozinho — desenvolvedores perguntam constantemente como manter as imagens embutidas sem lidar com arquivos separados. A boa notícia é que o Aspose.Words for Java facilita tudo: você pode converter um documento Word para Markdown e incorporar automaticamente cada imagem como uma string Base64. + +Neste tutorial percorreremos todo o processo — desde carregar um `.docx` que contém imagens, até configurar um callback `MarkdownSaveOptions` que faz o trabalho pesado, e finalmente salvar o resultado como um arquivo `.md` limpo. Ao final você saberá exatamente como **convert word to markdown**, **convert images to base64**, e **save word as markdown** sem deixar pastas de imagens soltas. Sem ferramentas externas, sem pós‑processamento manual — apenas código Java puro que você pode inserir em qualquer projeto. + +## O que você precisará + +- **Java 17** (ou qualquer JDK recente) – o código usa sintaxe lambda, mas você pode adaptá-lo para versões mais antigas. +- Biblioteca **Aspose.Words for Java** (versão mais recente em 2026). Adicione a dependência Maven ou o JAR ao seu classpath. +- Um arquivo **DOCX** de exemplo que contenha ao menos uma imagem. +- Uma IDE ou um editor de texto simples — Visual Studio Code, IntelliJ IDEA, ou até mesmo `vim` serve. + +Se você já tem tudo isso, ótimo — vamos direto ao assunto. + +## Etapa 1: Carregar o Documento Word + +Primeiro criamos uma instância `Document` que aponta para o arquivo de origem. Esta é a mesma etapa, seja você **convert docx to markdown** ou apenas lendo o arquivo para outros fins. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Por que isso importa:** O objeto `Document` é o ponto de entrada para todas as operações do Aspose. Ele contém toda a estrutura do Word — incluindo imagens, tabelas e estilos — para que o callback posterior possa inspecionar cada recurso. + +## Etapa 2: Criar MarkdownSaveOptions e Registrar um Callback de Salvamento de Recurso + +A mágica está em `MarkdownSaveOptions`. Ao anexar um `IResourceSavingCallback` ganhamos controle sobre como cada recurso externo (como uma imagem) é gravado. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Por que usar `setSaveToMemory(true)`? + +Quando `saveToMemory` é true, o Aspose grava os bytes da imagem em um fluxo de memória ao invés de um arquivo. O exportador Markdown então converte esse fluxo em uma string Base64 e a insere diretamente na tag de imagem Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Esse é o núcleo de **embed images as base64**. + +## Etapa 3: Salvar o Documento como Markdown + +Agora que o callback está configurado, a etapa final é simplesmente chamar `save`. É aqui que realmente **convert word to markdown** e, graças ao callback, também **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Resultado:** `out.md` contém texto Markdown com cada imagem representada como um URI `data:`. Nenhum arquivo de imagem extra é criado no disco, então a pasta permanece organizada. + +## Etapa 4: Verificar a Saída e Problemas Comuns + +Abra o `out.md` gerado em qualquer visualizador de Markdown (VS Code, GitHub ou um gerador de site estático). Você deve ver algo como: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Lista de Verificação de Solução de Problemas + +| Problema | Causa Provável | Correção | +|----------|----------------|----------| +| A imagem aparece como link quebrado | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` is inside the callback | +| A string Base64 está truncada | Output file encoding mismatch | Save the Markdown using UTF‑8 (default for Aspose) | +| Nomes de arquivo inesperados | `setKeepResourceOriginalName(true)` | Keep it `false` to force the custom naming logic | + +## Etapa 5: Variações Avançadas (Opcional) + +### Converter Apenas Imagens Selecionadas + +Se você quiser incorporar apenas certas imagens (por exemplo, as maiores que 100 KB), adicione uma verificação de tamanho: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Usar um Formato de Imagem Diferente + +O `ResourceSavingArgs` fornece os bytes brutos, então você pode re‑codificar JPEGs como PNGs antes de incorporá‑los — útil quando o consumidor de Markdown prefere PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Essas ajustes ilustram quão flexível a abordagem **embed images as base64** é quando você **convert docx to markdown**. + +## Conclusão + +Você acabou de aprender como **embed images as base64** enquanto **convert docx to markdown** usando Aspose.Words for Java. Ao conectar um simples `IResourceSavingCallback`, a biblioteca faz todo o trabalho pesado: ela **convert word to markdown**, **convert images to base64**, e finalmente **save word as markdown** com uma única chamada `save`. + +Sinta-se à vontade para experimentar — tente diferentes regras de filtragem de imagens, mude para saída HTML, ou encadeie esta etapa com um gerador de site estático. O mesmo padrão funciona para outros formatos (HTML, EPUB) também, então você pode reutilizar o callback onde precisar de recursos embutidos. + +**Próximos passos:** +- Explore `HtmlSaveOptions` para imagens HTML‑com‑Base64. +- Combine isso com um pipeline CI para automatizar a geração de documentação. +- Aprofunde-se no `DocumentVisitor` da Aspose se precisar de controle ainda mais fino sobre o processo de conversão. + +Feliz codificação, e aproveite seus arquivos Markdown limpos e autossuficientes! + +## Tutoriais Relacionados + +- [Como Incorporar Imagens em Markdown ao Converter DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Converter docx para markdown – Exportar Equações Matemáticas para LaTeX com Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Salvar Imagens do Word – Guia Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/portuguese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..8f3a8278ac --- /dev/null +++ b/words/portuguese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Exportar docx para txt usando Java e Aspose.Words. Aprenda como converter + docx para texto, preservar Unicode e exportar Word como txt em poucos passos. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: pt +og_description: Exportar docx para txt em Java. Este tutorial mostra como converter + docx para texto, manter texto simples em Unicode e exportar Word como txt de forma + eficiente. +og_title: Exportar docx para txt com Java – Guia Completo +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Exportar docx para txt com Java – Guia Completo de Programação +url: /pt/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exportar docx para txt com Java – Guia de Programação Completo + +Já precisou **exportar docx para txt** mas ficou preocupado em perder caracteres especiais? Você não está sozinho. Quando você converte documentos Word para arquivos plain‑text, símbolos Unicode, tabelas e até mesmo formatação simples podem desaparecer como mágica. + +Neste guia, vamos percorrer um método confiável para **exportar docx para txt** usando Aspose.Words for Java, preservando cada glifo Unicode e mantendo os layouts de tabelas legíveis. Ao final, você também saberá como **converter docx para texto**, **converter word para texto**, e até **exportar word como txt** sem problemas. + +## O que este tutorial cobre + +* Configurar o Aspose.Words em um projeto Java +* Carregar um arquivo DOCX e prepará-lo para saída plain‑text +* Configurar o suporte **plain text unicode** via `TxtSaveOptions` +* Truques opcionais para manter tabelas legíveis no arquivo `.txt` resultante +* Salvar o arquivo e verificar a saída + +Sem scripts externos, sem ferramentas de linha de comando misteriosas — apenas código Java puro que você pode inserir em qualquer projeto Maven ou Gradle. + +> **Por que se importar?** Arquivos plain‑text são leves, amigáveis ao controle de versão e perfeitos para indexação de busca ou pipelines de processamento downstream. Se você já tentou `cat` um arquivo Word e recebeu lixo, este tutorial resolve esse problema. + +--- + +## Exportar docx para txt – Visão geral + +Antes de mergulharmos no código, vamos esclarecer a terminologia. **Exportar docx para txt** significa pegar um pacote Microsoft Word `.docx` e escrever seu conteúdo textual em um simples arquivo `.txt`. Ao contrário de uma conversão para PDF, a exportação para texto remove a formatação, mas pode manter quebras de linha, marcadores de parágrafo e — se configurado corretamente — caracteres Unicode como emojis, letras acentuadas ou scripts asiáticos. + +Aspose.Words torna isso simples porque abstrai o formato de arquivo Word e oferece a classe `TxtSaveOptions` onde você pode definir a codificação, o tratamento de tabelas e mais. + +### Pré-requisitos + +* Java 11 ou superior (a API funciona com Java 8+, mas assumiremos um JDK recente) +* Aspose.Words for Java JAR (disponível no Maven Central) +* Um arquivo de exemplo `unicode.docx` contendo diversos caracteres Unicode — pense em “こんにちは”, “😊”, e uma tabela simples + +Se você tem isso, vamos começar. + +--- + +## Etapa 1: Carregar o arquivo DOCX (Converter docx para texto) + +A primeira coisa que você precisa fazer é ler o documento fonte na memória. É aqui que o processo de **converter docx para texto** começa oficialmente. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Por que isso importa:* `Document` é a representação do Aspose.Words de um arquivo Word. Ao carregá-lo, você tem acesso a todos os seus parágrafos, tabelas e até elementos ocultos. Se o arquivo não for encontrado, o Aspose lança um `FileNotFoundException` claro, então você saberá imediatamente o que deu errado. + +--- + +## Etapa 2: Configurar TxtSaveOptions para Unicode (Plain text unicode) + +Arquivos plain‑text são apenas fluxos de bytes, portanto você deve dizer ao Java qual conjunto de caracteres usar. UTF‑8 é o padrão de fato para **plain text unicode** porque pode codificar cada ponto de código Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Dica profissional:** Se você pular a chamada `setEncoding`, o Aspose usa a codificação padrão da plataforma, que em muitas máquinas Windows é Windows‑1252. Essa configuração padrão descartará silenciosamente caracteres como “ß” ou “—”. + +--- + +## Etapa 3: Preservar o Layout da Tabela (Opcional, mas útil para legibilidade) + +Quando você **exporta word como txt**, as tabelas geralmente se achatam em uma única linha de texto, tornando-as ilegíveis. Aspose.Words oferece uma bandeira simples para manter a estrutura visual. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Quando usar:* Se seu DOCX fonte contém faturas, cronogramas ou quaisquer dados em forma de grade, habilitar `PreserveTableLayout` inserirá tabulações e quebras de linha para que o arquivo resultante ainda se pareça com uma tabela. Se você não precisar disso, pode omitir a linha e obter uma saída mais compacta. + +--- + +## Etapa 4: Salvar o Documento como Plain‑Text (Exportar word como txt) + +Agora o trabalho pesado está feito — basta escrever os bytes no disco. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Executar o programa gera `plain.txt` na mesma pasta. Abra-o com qualquer editor de texto (Notepad++, VS Code, até `cat` no terminal) e você verá: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Observe como a saudação japonesa e o emoticon sobreviveram, e a tabela manteve suas colunas graças ao `PreserveTableLayout`. Essa é a essência de um **exportar docx para txt** limpo. + +--- + +## Etapa 5: Verificar a Saída (Verificação de sanidade ao converter word para texto) + +Uma verificação rápida de sanidade previne perda silenciosa de dados. Aqui estão algumas maneiras de confirmar que você realmente **converte word para texto** corretamente: + +1. **Comparação de checksum** – calcule um hash SHA‑256 do arquivo `.txt` antes e depois de uma conversão de ida e volta (txt → docx → txt) para garantir estabilidade. +2. **Buscar marcadores Unicode** – use `grep` ou a busca da IDE (find‑in‑file) para localizar caracteres como “😊”. +3. **Abrir em múltiplos editores** – algumas versões antigas do Notepad do Windows ainda interpretam mal UTF‑8 sem BOM; abrir o arquivo no VS Code confirma a codificação correta. + +Se alguma dessas verificações falhar, verifique novamente se `saveOptions.setEncoding(StandardCharsets.UTF_8)` está presente e se seu DOCX fonte realmente contém texto Unicode. + +--- + +## Armadilhas Comuns & Como Evitá‑las + +| Problema | Por que acontece | Solução | +|----------|------------------|---------| +| **Caracteres ausentes** | A codificação padrão do sistema (ex.: Windows‑1252) descarta glifos não‑ASCII. | Defina explicitamente UTF‑8 via `saveOptions.setEncoding`. | +| **Tabelas se tornam uma única linha** | `PreserveTableLayout` deixado como padrão `false`. | Chame `saveOptions.setPreserveTableLayout(true)`. | +| **Arquivo não encontrado** | Caminho errado ou permissões de leitura ausentes. | Use caminhos absolutos ou `Paths.get(...)` com tratamento de exceção adequado. | +| **Desempenho lento em documentos grandes** | Carregando o documento inteiro na memória. | Transmita o documento em blocos usando `DocumentBuilder` se você precisar apenas de seções específicas. | + +--- + +## Bônus: Exportando Vários Arquivos DOCX em Lote + +Se você precisar **converter docx para texto** de uma pasta inteira, envolva a lógica em um loop: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Este trecho **exporta docx para txt** para cada arquivo no diretório, economizando horas de trabalho manual. + +--- + +## Conclusão + +Você acabou de aprender como **exportar docx para txt** com Java, garantindo que cada caractere Unicode permaneça intacto, as tabelas fiquem legíveis e todo o processo seja repetível. Configurando `TxtSaveOptions` para UTF‑8 e, opcionalmente, preservando layouts de tabelas, você pode de forma confiável **converter docx para texto**, **converter word para texto**, e **exportar word como txt** para qualquer fluxo de trabalho downstream. + +Pronto para o próximo desafio? Tente exportar para outros formatos plain‑text como markdown (`.md`) ou CSV, ou explore as capacidades de conversão para PDF do Aspose.Words. Os mesmos princípios — codificação explícita, preservação de layout e verificação completa — se aplicam em todas as situações. + +Feliz codificação, e que seus arquivos de texto estejam sempre ricos em Unicode! + +--- + +![Diagrama mostrando o pipeline de exportar docx para txt](/images/export-docx-to-txt-pipeline.png){alt="diagrama do pipeline de exportar docx para txt"} + +## Tutoriais Relacionados + +- [Converter Docx para Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Converter DOCX para PDF em Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Converter docx para markdown – Exportar Equações Matemáticas para LaTeX com Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/portuguese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..91ec80e1b3 --- /dev/null +++ b/words/portuguese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: Salvar documento como PDF usando Aspose.Words Java e adicionar acessibilidade + ao PDF. Aprenda a converter docx para PDF, marcar regras horizontais e garantir + conformidade com PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: pt +og_description: Salve o documento como PDF com Aspose.Words Java enquanto adiciona + acessibilidade ao PDF. Guia passo a passo para converter docx em PDF e marcar regras + horizontais para conformidade com PDF/UA‑2. +og_title: Salvar documento como PDF com Aspose.Words Java – Acessibilidade facilitada +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Salvar documento como PDF com Aspose.Words Java – Guia completo de acessibilidade +url: /pt/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salvar documento como PDF com Aspose.Words Java – Guia completo de acessibilidade + +Já se perguntou como **salvar documento como PDF** mantendo-o acessível para leitores de tela? Você não está sozinho. Muitos desenvolvedores precisam *converter docx para pdf* e ainda atender aos padrões PDF/UA‑2, especialmente quando a origem contém linhas horizontais que devem ser marcadas corretamente. Neste tutorial, percorreremos os passos exatos para **salvar documento como PDF** usando Aspose.Words for Java, automaticamente **adicionar acessibilidade ao PDF**, e garantir que cada linha horizontal seja **marcada** como um artefato. + +Começaremos com um projeto Java limpo, carregaremos um DOCX que já contém linhas horizontais, configuraremos as opções de salvamento em PDF para conformidade PDF/UA‑2 e, finalmente, geraremos um PDF totalmente acessível. Ao final, você será capaz de **salvar documento como pdf** com a confiança de que ele passa nas verificações de acessibilidade. + +## Pré-requisitos + +- Java 8 ou superior instalado (o tutorial foi testado no JDK 17). +- Maven 3.6+ (ou Gradle, se preferir) para gerenciar dependências. +- Uma licença válida do Aspose.Words for Java (a versão de avaliação funciona, mas uma licença remove as marcas d'água de avaliação). +- Um arquivo DOCX (`input.docx`) que inclui ao menos uma linha horizontal — pense em um simples separador de linha que você adicionaria no Word. + +> **Dica profissional:** Se você não tem um DOCX à mão, basta criar um novo documento Word, digitar alguns parágrafos, inserir *Inserir → Linha Horizontal*, salvar como `input.docx` e colocá-lo em uma pasta de sua escolha. + +## Etapa 1: Configurar o Projeto Maven + +Primeiro, crie um novo projeto Maven (ou adicione a um existente). O `pom.xml` precisa da dependência Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Por que isso importa:** Adicionar o artefato `aspose-words` é o primeiro passo para *converter docx para pdf*. Sem ele, o compilador não reconhecerá `Document`, `PdfSaveOptions` e outras classes cruciais. + +## Etapa 2: Carregar o DOCX de origem contendo linhas horizontais + +Agora escreveremos uma pequena classe Java que carrega o DOCX. É aqui que a parte de **marcar linhas horizontais** começa — o Aspose.Words trata automaticamente uma linha horizontal como um parágrafo com borda, mas deixaremos o mecanismo PDF/UA lidar com a marcação. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Observe que ainda não salvamos nada — estamos apenas **carregando** o DOCX, que é a primeira metade de *converter docx para pdf*. O objeto `Document` agora contém todo o conteúdo do Word, incluindo quaisquer linhas horizontais que você inseriu. + +## Etapa 3: Configurar as opções de salvamento em PDF para conformidade PDF/UA‑2 + +A mágica de **adicionar acessibilidade ao PDF** está em `PdfSaveOptions`. Ao definir o nível de conformidade para `PDF_UA_2`, o Aspose.Words irá: + +1. Marcar elementos estruturais (títulos, tabelas, etc.). +2. Marcar elementos decorativos — como linhas horizontais como *artefatos*, para que leitores de tela os ignorem. +3. Inserir os metadados necessários do PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Por que definir conformidade?** Sem `PDF_UA_2`, o PDF resultante ainda pode ser legível, mas não passará nos validadores automáticos de acessibilidade. O requisito de **marcar linhas horizontais** é satisfeito automaticamente porque o PDF/UA as trata como *artefatos* quando a flag de conformidade está ativada. + +## Etapa 4: Salvar o documento como PDF + +Agora finalmente **salvamos o documento como pdf**. Esta única linha faz o trabalho pesado — convertendo o DOCX, aplicando as tags de acessibilidade e gravando o arquivo no disco. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Execute a classe (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) e você verá uma mensagem de confirmação. Abra o `ua_compliant.pdf` resultante no Adobe Acrobat e verifique **Arquivo → Propriedades → Descrição → PDF/A, PDF/UA** — você deverá ver “PDF/UA‑2” listado. + +### Saída esperada + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Abra o PDF e você notará: + +- O texto do documento é selecionável e pesquisável. +- A linha horizontal é invisível para leitores de tela (tratada como um artefato). +- O PDF passa nas ferramentas básicas de validação PDF/UA (por exemplo, PAC 3). + +## Etapa 5: Verificar a acessibilidade – Checklist rápido + +Embora o Aspose.Words faça a maior parte do trabalho, é uma boa prática verificar a saída. + +| Verificação | Como verificar | +|-------------|----------------| +| **Título do documento** | Abra o Acrobat → Arquivo → Propriedades → Campo Título (deve corresponder a `pdfOptions.setTitle`). | +| **Marcação de artefato** | Use a ferramenta “Ordem de Leitura” do Acrobat. Linhas horizontais devem aparecer como *Artefato* (cinza). | +| **Ordem de leitura lógica** | Execute o “Verificador de Acessibilidade” no Acrobat; assegure que não haja erros estruturais. | +| **PDF marcado** | No Acrobat, veja no painel “Tags” – você deve ver uma hierarquia (Documento → Seção → Parágrafo, etc.). | +| **Conformidade PDF/UA** | O Acrobat exibirá “PDF/UA‑2” na aba “Padrões”. | + +Se alguma dessas verificações falhar, verifique novamente se você usou a versão mais recente do Aspose.Words e se `setCompliance(PdfCompliance.PDF_UA_2)` está corretamente aplicado. + +## Armadilhas comuns e como evitá‑las + +1. **Licença ausente** – A versão de avaliação adiciona uma marca d'água que pode quebrar a validação PDF/UA. Aplique sua licença logo no início do `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Caminho de entrada incorreto** – Uma `FileNotFoundException` interromperá a conversão. Use caminhos absolutos ou coloque o DOCX na raiz do projeto e faça referência a ele com `new File("input.docx").getAbsolutePath()`. +3. **Uso de versão antiga do Aspose** – O suporte a PDF/UA foi adicionado na versão 22.9. Atualize para a versão mais recente para evitar recursos ausentes. +4. **Linha horizontal como imagem** – Se você inseriu a linha como imagem em vez de uma linha horizontal nativa do Word, o Aspose a trata como uma imagem comum, não como artefato. Substitua a imagem pela *Linha Horizontal* incorporada do Word para marcação correta. + +## Expandindo a solução – E se você precisar de mais? + +- **Tags personalizados**: Se você tem outros elementos decorativos (por exemplo, ícones decorativos), pode marcá‑los manualmente como artefatos usando `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Múltiplos documentos**: Percorra uma pasta de arquivos DOCX e converta‑os em lote, reutilizando a mesma instância de `PdfSaveOptions` para desempenho. +- **Adicionar uma tag de idioma**: Para PDFs multilíngues, defina `pdfOptions.setLanguage("en-US")` para ajudar as tecnologias assistivas a escolher a voz correta. + +## Exemplo completo em funcionamento (Todo o código junto) + +Abaixo está o programa Java completo e executável. Copie‑e cole no seu IDE, ajuste os caminhos e execute. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Execute-o, abra o PDF gerado, e você terá um arquivo limpo e acessível pronto para distribuição. + +## Conclusão + +Acabamos de demonstrar como **salvar documento como pdf** com Aspose.Words for Java enquanto automaticamente **adicionamos acessibilidade ao pdf** e **marcamos linhas horizontais** como artefatos. Os principais pontos: + +- Use `PdfSaveOptions` com conformidade `PDF_UA_2` para atender aos padrões de acessibilidade. +- Carregar um DOCX e chamar `doc.save(..., pdfOptions)` é tudo que você precisa para **converter docx para pdf**. +- Linhas horizontais são tratadas para você — nenhum código extra necessário, atendendo ao requisito de **marcar linhas horizontais**. +- A abordagem está totalmente em conformidade com **aspose convert docx pdf**, funciona com a versão mais recente da biblioteca e produz um PDF pronto para validação. + +Pronto para o próximo desafio? Tente adicionar metadados personalizados, incorporar fontes ou processar em lote uma pasta inteira de arquivos DOCX. Cada uma dessas extensões se baseia na mesma fundação que apresentamos aqui. + +Tem dúvidas sobre conformidade PDF/UA, licenciamento ou manipulação de outros elementos do Word? Deixe um comentário ou consulte a documentação oficial da Aspose — há uma abundância de exemplos para explorar. Feliz codificação e aproveite a criação de PDFs acessíveis! + +![salvar documento como pdf usando Aspose.Words Java – exemplo de PDF acessível](placeholder-image.png "salvar documento como pdf usando Aspose.Words Java – exemplo de PDF acessível") + +## Tutoriais relacionados + +- [Como salvar documento como pdf com Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Como converter Word para PDF usando Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Converter DOCX para PDF em Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/portuguese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..63096ceed1 --- /dev/null +++ b/words/portuguese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Salve o Word como markdown e descubra como exportar equações matemáticas + para LaTeX usando Aspose.Words para Java. Converta equações do Word para LaTeX em + apenas algumas linhas. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: pt +og_description: Salve documentos Word como markdown e aprenda a exportar equações + matemáticas para LaTeX usando Aspose.Words for Java. Um guia completo e executável. +og_title: Salvar Word como markdown – Exportar matemática para LaTeX com Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Salvar Word como markdown – Exportar matemática para LaTeX com Java +url: /pt/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Salvar Word como markdown – Exportar Matemática para LaTeX com Java + +Já precisou **salvar Word como markdown** mas temia que suas equações se transformassem em uma bagunça incompreensível? Você não está sozinho. Neste guia vamos percorrer **como exportar matemática** de um arquivo `.docx` direto para LaTeX enquanto o restante do documento se torna um Markdown limpo. + +Cobriremos tudo, desde a configuração da biblioteca Aspose.Words até a verificação do arquivo final `out.md`. Ao final, você será capaz de **converter equações Word para LaTeX** com uma única chamada de método e entenderá as pequenas nuances que tornam a conversão confiável. + +--- + +## O que você precisará + +- **Java 8+** – o código roda em qualquer JDK recente. +- **Aspose.Words for Java** – a dependência Maven/Gradle ou o JAR, caso prefira configuração manual. +- Um documento Word (`math.docx`) que contenha ao menos uma equação Office Math. +- Uma IDE ou linha de comando `javac`/`java` – o que for mais confortável para você. + +Se já tem tudo isso, ótimo. Caso contrário, a próxima seção mostra exatamente como trazer a biblioteca para o seu projeto. + +--- + +## Salvar Word como markdown – Etapa 1: Adicionar Aspose.Words ao seu Projeto + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Dica profissional:** A Aspose oferece uma licença temporária gratuita para testes. Coloque o arquivo `license.xml` na sua pasta de recursos e chame `License license = new License(); license.setLicense("license.xml");` antes de carregar qualquer documento. + +Uma vez que a dependência esteja resolvida, você está pronto para escrever o código de conversão. + +--- + +## Como exportar equações matemáticas para LaTeX + +O trabalho pesado é feito por `MarkdownSaveOptions`. Ao mudar seu `OfficeMathExportMode` para `LATEX`, cada objeto Office Math é renderizado como um fragmento LaTeX dentro da saída Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Por que isso funciona + +- **`Document`** é o ponto de entrada da Aspose; ele abstrai o arquivo `.docx` e dá acesso a cada nó, incluindo equações. +- **`MarkdownSaveOptions`** informa à biblioteca *como* você deseja a saída. O comportamento padrão é renderizar equações como imagens, o que anula o propósito de um formato baseado em texto. +- **`OfficeMathExportMode.LATEX`** força o motor a traduzir cada nó `OfficeMath` para seu equivalente LaTeX, que parsers Markdown (como GitHub ou Jekyll) podem renderizar quando combinados com um plugin MathJax. + +--- + +## Converter equações Word para LaTeX – Etapa 2: Verificar a saída Markdown + +Depois de executar o programa, abra `out.md`. Você deverá ver algo parecido com isto: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Observação:** Os fragmentos LaTeX são envoltos em `$…$` para matemática inline e `$$…$$` para matemática em bloco. Essa é a sintaxe padrão que a maioria dos geradores de sites estáticos entende quando o MathJax está habilitado. + +Se preferir que as equações permaneçam apenas inline, você pode ajustar ainda mais o `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx para markdown latex – Etapa 3: Casos Limite e Armadilhas Comuns + +| Situação | O que observar | Solução | +|-----------|-------------------|-----| +| **Equações aninhadas complexas** | Aspose pode gerar chaves extras `{}` que alguns parsers tratam literalmente. | Pós‑processar o Markdown com uma regex simples para colapsar `{{` → `{`. | +| **MathJax ausente no site de destino** | As equações aparecem como código LaTeX bruto. | Adicionar `` ao seu template HTML. | +| **Documentos grandes** | O consumo de memória dispara porque o documento inteiro é carregado de uma vez. | Usar `LoadOptions.setLoadFormat(LoadFormat.DOCX)` e considerar processar páginas em lotes se ocorrer `OutOfMemoryError`. | +| **Licença não configurada** | Você receberá um aviso e a saída pode ficar com marca d'água. | Carregar a licença logo no início do `main`, como mostrado na dica Maven acima. | + +--- + +## Salvar Word como markdown – Exemplo Completo Funcional + +Abaixo está uma classe autônoma que você pode copiar‑colar em qualquer projeto Java. Basta substituir `YOUR_DIRECTORY` pelo caminho dos seus arquivos. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Execute o programa (`java MathToLatexMarkdown`) e verá a mensagem no console confirmando o sucesso. Abra `out.md` em qualquer editor – as equações deverão ser trechos LaTeX limpos prontos para renderização. + +--- + +## Captura de Saída Esperada + +![salvar word como markdown output com equações LaTeX](https://example.com/images/markdown-latex-output.png "salvar word como markdown output com equações LaTeX") + +*A imagem mostra um trecho do Markdown gerado onde a equação `\int_{a}^{b} f(x)\,dx` está envolta em `$$`.* + +--- + +## Conclusão + +Acabamos de demonstrar como **salvar Word como markdown** preservando cada equação Office Math como LaTeX nativo. O passo chave foi configurar `MarkdownSaveOptions` com `OfficeMathExportMode.LATEX`, que transforma um pipeline típico de Word‑para‑Markdown em uma ferramenta totalmente consciente de matemática. + +Agora você pode: + +1. **Como exportar matemática** de qualquer `.docx` sem perder fidelidade. +2. **Converter equações Word para LaTeX** para geradores de sites estáticos, documentação ou blogs acadêmicos. +3. Expandir a abordagem para processar lotes de arquivos, integrar em pipelines CI ou até criar um pequeno serviço web. + +Se estiver curioso sobre a próxima fronteira, experimente combinar isso com **docx to markdown latex** para documentos ricos em imagens, ou explore `HtmlSaveOptions` da Aspose para uma versão HTML pronta para a web. As possibilidades são infinitas—experimente, quebre coisas e depois compartilhe suas descobertas com a comunidade. + +Tem perguntas ou uma equação complicada que não foi renderizada como esperado? Deixe um comentário abaixo e feliz codificação! + +## Tutoriais Relacionados + +- [Como Exportar LaTeX do Word: Converter DOCX para Markdown & Salvar como PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Converter docx para markdown – Exportar Equações Matemáticas para LaTeX com Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Como Converter Word para PDF Usando Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/portuguese/java/document-loading-and-saving/_index.md index 7440c174ea..966abfdef3 100644 --- a/words/portuguese/java/document-loading-and-saving/_index.md +++ b/words/portuguese/java/document-loading-and-saving/_index.md @@ -99,6 +99,7 @@ As configurações de documentos são a chave para entregar documentos adaptados ### [Salvando Documentos como Arquivos de Texto no Aspose.Words for Java](./saving-documents-as-text-files/) ### [Determinando o Formato de Documento no Aspose.Words for Java](./determining-document-format/) ### [Recuperar docx corrompido – Guia completo para corrigir e processar documentos](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [Abrir Documento Word Corrompido – Definir Modo de Recuperação em Java](./open-corrupted-word-document-set-recovery-mode-in-java/) ### [Capturar avisos de substituição de fontes em Java com Aspose.Words – Guia completo](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## Perguntas Frequentes diff --git a/words/portuguese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/portuguese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..ba2ac230b5 --- /dev/null +++ b/words/portuguese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Abra documento Word corrompido em Java com Aspose.Words. Aprenda como + definir o modo de recuperação e recuperar arquivos Word corrompidos de forma confiável. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: pt +og_description: Abra documento Word corrompido em Java usando Aspose.Words. Este guia + mostra como definir o modo de recuperação e recuperar arquivos Word corrompidos + de forma eficiente. +og_title: Abrir documento Word corrompido – Definir modo de recuperação em Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Abrir Documento Word Corrompido – Definir Modo de Recuperação em Java +url: /pt/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Abrir Documento Word Corrompido – Definir Modo de Recuperação em Java + +Já tentou abrir um documento Word corrompido e viu o programa travar com uma exceção? Você não está sozinho—esses arquivos .docx quebrados podem ser uma verdadeira dor de cabeça. A boa notícia é que o Aspose.Words for Java oferece controle granular para que você possa **open corrupted word document** sem que o aplicativo falhe, e ainda decidir se deseja avisos, recuperação silenciosa ou uma rejeição rígida. + +Neste tutorial, percorreremos todo o processo: desde a criação do `LoadOptions` correto, até a escolha do valor apropriado de **set recovery mode**, e finalmente confirmar que o documento foi realmente carregado. Ao final, você saberá **how to recover corrupted word file** programaticamente, sem necessidade de copiar‑colar manualmente. + +> **O que você precisará** +> * Java 8 ou mais recente (a API funciona também com Java 11) +> * Aspose.Words for Java 23.9 (ou a versão mais recente) +> * Um arquivo .docx corrompido de exemplo—basta renomear qualquer arquivo válido para simular corrupção se você não tiver um à mão + +Vamos mergulhar. + +## Abrir Documento Word Corrompido – Visão Geral Passo a Passo + +Abaixo está o fluxo de alto nível que implementaremos: + +1. **Create `LoadOptions`** – este objeto informa ao Aspose.Words como se comportar quando encontra problemas. +2. **Set recovery mode** – escolha `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` ou `REJECT_CORRUPTED`. +3. **Load the document** usando as opções configuradas. +4. **Verify** se o carregamento foi bem‑sucedido (por exemplo, imprima a contagem de páginas). + +Cada passo é explicado em detalhe, com trechos de código que você pode copiar‑colar diretamente no seu IDE. + +## Definir Modo de Recuperação para Diferentes Cenários + +Aspose.Words define três estratégias de recuperação dentro de `LoadOptions.RecoveryMode`: + +| Mode | Behaviour | When to use | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | Tenta carregar o documento, mas exibe quaisquer problemas como avisos no console. | Você quer ver *o que* deu errado sem abortar. | +| `RECOVER_WITHOUT_WARNINGS` | Corrige silenciosamente o que for possível e suprime avisos. | Ambientes de produção onde os logs devem permanecer limpos. | +| `REJECT_CORRUPTED` | Lança uma exceção no momento em que a corrupção é detectada. | Pipelines de validação estritos que precisam falhar rapidamente. | + +Escolher o modo correto é a essência de **set recovery mode** adequadamente. Na maioria das sessões de depuração, `RECOVER_WITH_WARNINGS` é a escolha ideal porque informa exatamente quais partes foram reparadas. + +## Como Recuperar Arquivo Word Corrompido Usando Aspose.Words + +Abaixo está um **programa Java completo e executável** que demonstra todo o processo. Sinta‑se à vontade para colocá‑lo em um arquivo `RecoveryModeDemo.java`, ajustar o caminho e executar. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Por que cada linha importa + +* **`LoadOptions loadOptions = new LoadOptions();`** – sem este objeto, o Aspose.Words usa a recuperação padrão, que *rejeita* arquivos corrompidos. Criá‑lo fornece o ponto de extensão para mudar esse comportamento. +* **`setRecoveryMode(...)`** – esta é a chamada **set recovery mode** que decide se avisos aparecem, permanecem ocultos ou causam uma exceção. +* **`new Document(path, loadOptions);`** – o construtor aceita o `LoadOptions` que acabamos de configurar, portanto a biblioteca sabe como tratar o arquivo quebrado desde o início. +* **`doc.getPageCount()`** – uma verificação rápida de sanidade. Se o documento carregar e retornar a contagem de páginas, você conseguiu **how to recover corrupted word file** com sucesso. +* **`doc.save(...)`** – opcional, mas útil; você pode gravar a versão reparada de volta ao disco para uso posterior. + +## Tratando Casos Limítrofes Comuns + +### 1. Arquivo Não Encontrado + +Se o caminho estiver errado, `Document` lança uma `FileNotFoundException`. Envolva o carregamento em um bloco try‑catch e registre uma mensagem amigável: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Corrupção Irrecuperável + +Mesmo com `RECOVER_WITH_WARNINGS`, algumas estruturas estão além do reparo. Nesse caso, o Aspose.Words ainda carrega o que puder, mas você verá avisos como “Cannot read paragraph properties”. Preste atenção à saída do console; esses avisos frequentemente apontam para seções ausentes que você pode precisar reconstruir manualmente. + +### 3. Arquivos Grandes e Desempenho + +A recuperação adiciona uma pequena sobrecarga porque a biblioteca analisa o arquivo duas vezes—uma vez para detectar problemas, outra para reconstruir. Para documentos de vários gigabytes, considere fazer streaming do arquivo ou aumentar o heap da JVM (`-Xmx2g`) para evitar `OutOfMemoryError`. + +## Dicas Profissionais – Tornando a Recuperação Robusta + +* **Log warnings to a file** – redirecione `System.err` para um logger para que você tenha um registro de auditoria do que foi corrigido. +* **Validate after recovery** – execute `doc.updatePageLayout();` e então verifique novamente a contagem de páginas; às vezes o layout muda após corrigir seções quebradas. +* **Automate batch recovery** – envolva a demonstração em um loop que processa uma pasta de arquivos corrompidos, usando o mesmo `LoadOptions` a cada vez. + +## Conclusão + +Agora você sabe exatamente **how to recover corrupted word file** usando Aspose.Words for Java. Ao criar uma instância de `LoadOptions`, **set recovery mode** para a estratégia que se adapta ao seu cenário, e carregar o documento com essas opções, você pode abrir **open corrupted word document** com segurança sem que sua aplicação falhe. O código de exemplo acima é uma solução completa, pronta‑para‑executar, que imprime a contagem de páginas e ainda salva uma cópia limpa. + +Qual é o próximo passo? Experimente trocar o modo de recuperação para `RECOVER_WITHOUT_WARNINGS` e compare a saída do console, ou experimente carregar documentos criptografados (você precisará fornecer uma senha via + +## Tutoriais Relacionados + +- [Aspose.Words Java: Guia Abrangente para Processamento de Documentos Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Como Converter Word para PDF Usando Aspose.Words para Java](/words/english/java/document-converting/using-document-converting/) +- [Como Comparar Dois Arquivos Word com Aspose.Words para Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/portuguese/java/document-styling/_index.md index c5cf69c6d6..60abb6c194 100644 --- a/words/portuguese/java/document-styling/_index.md +++ b/words/portuguese/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aprenda a personalizar temas de documentos usando o Aspose.Words para Java. Este Aprenda a aplicar marcas d'água e definir configurações de página com o Aspose.Words para Java. Um guia completo com código-fonte. ### [Estilo de cabeçalho e rodapé de documento](./document-header-footer-styling/) Aprenda a estilizar cabeçalhos e rodapés de documentos usando o Aspose.Words para Java neste guia detalhado. Instruções passo a passo e código-fonte incluídos. +### [Definir configurações de fonte padrão no Aspose.Words para Java – Guia completo](./set-default-font-settings-in-aspose-words-for-java-complete/) +Aprenda a definir fontes padrão programaticamente no Aspose.Words para Java. Guia completo com exemplos de código-fonte. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/portuguese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..7c1f3ef31a --- /dev/null +++ b/words/portuguese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: Defina as configurações de fonte padrão no Aspose.Words para Java e aprenda + como definir configurações de fonte e detectar fontes ausentes em apenas algumas + linhas de código. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: pt +og_description: Defina as configurações de fonte padrão no Aspose.Words para Java, + aprenda a definir as configurações de fonte e detectar fontes ausentes de forma + rápida e confiável. +og_title: Definir configurações de fonte padrão no Aspose.Words para Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Definir Configurações de Fonte Padrão no Aspose.Words para Java – Guia Completo +url: /pt/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Definir Configurações de Fonte Padrão no Aspose.Words para Java – Guia Completo + +Já se perguntou como **definir configurações de fonte padrão** ao carregar um documento Word com Aspose.Words for Java? Você não está sozinho. Glifos ausentes podem transformar um relatório bem elaborado em uma bagunça ilegível, e detectar esses avisos de substituição de fonte cedo economiza horas de depuração. + +Neste tutorial, percorreremos um exemplo conciso e completo que **define configurações de fonte padrão**, mostra como **definir configurações de fonte** programaticamente e demonstra uma maneira confiável de **detectar fontes ausentes** antes que elas quebrem o layout. + +--- + +## O que você aprenderá + +- Como criar um objeto `LoadOptions` com uma nova instância de `FontSettings`. +- Como anexar um listener de avisos que **detectará fontes ausentes** durante o carregamento do documento. +- Como carregar um arquivo DOCX enquanto o listener relata silenciosamente quaisquer substituições. +- Dicas para personalizar fontes de fallback e lidar com casos extremos em produção. + +Sem bibliotecas extras, sem arquivos de configuração obscuros — apenas Java puro e Aspose.Words. + +--- + +## Pré-requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +1. **Aspose.Words for Java** (versão 23.10 ou mais recente) no seu classpath. +2. Um kit de desenvolvimento Java 17 (ou superior) – qualquer JDK moderno funciona. +3. Um arquivo DOCX que intencionalmente usa uma fonte que você não tem instalada (por exemplo, *“MissingFont.ttf”*). + +Se você não tem o JAR da Aspose, obtenha‑o no repositório oficial Maven: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +É isso — não é necessário instalar fontes adicionais para esta demonstração. + +--- + +## Etapa 1: Criar LoadOptions e **Definir Configurações de Fonte Padrão** + +A primeira coisa que precisamos é um objeto `LoadOptions` limpo que indica ao Aspose como se comportar ao encontrar tipos de letra desconhecidos. Ao chamar `setFontSettings(new FontSettings())` nós **definimos configurações de fonte padrão** que começam com uma lista de fallback vazia. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Por que isso importa:** +> Quando você não configura explicitamente as fontes, o Aspose recorre à coleção padrão do sistema, o que pode mascarar problemas de fontes ausentes. Ao iniciar a partir de uma nova instância de `FontSettings`, você tem controle total sobre quais fontes são consideradas válidas. + +--- + +## Etapa 2: Anexar um Listener de Avisos para **Detectar Fontes Ausentes** + +Aspose gera um objeto `WarningInfo` para cada substituição que realiza. Ao escutar `WarningType.FONT_SUBSTITUTION` podemos **detectar fontes ausentes** assim que o documento é analisado. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Dica profissional:** O listener roda na mesma thread que carrega o documento, portanto não há praticamente nenhum impacto de desempenho. Se precisar coletar avisos para análise posterior, envie‑os para um `List` em vez de imprimir diretamente. + +--- + +## Etapa 3: Carregar o Documento Usando as Opções Configuradas + +Agora que **definimos as configurações de fonte** e preparamos um listener, basta carregar o arquivo. Qualquer fonte ausente dispara nosso callback instantaneamente. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Se o arquivo de origem referenciar uma fonte que não está instalada, você verá uma saída semelhante a: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Essa linha informa exatamente qual fonte estava ausente e qual fallback foi usado — perfeito para registro ou feedback ao usuário. + +--- + +## Etapa 4: Continuar o Processamento Normal (Opcional) + +Neste ponto o documento está totalmente carregado, e você pode prosseguir com qualquer manipulação que desejar — edição, conversão para PDF ou extração de texto. O listener de avisos já fez seu trabalho, portanto não são necessárias verificações adicionais. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **E se você quiser um fallback personalizado?** +> Em vez de deixar o `FontSettings` vazio, você pode adicionar fontes específicas: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Agora qualquer tipo de letra ausente será substituído por *Times New Roman* — uma escolha confiável para a maioria dos documentos ocidentais. + +--- + +## Visão Geral Visual + +![Diagrama mostrando como definir configurações de fonte padrão no Aspose.Words for Java](image.png "Diagrama do fluxo de definição de configurações de fonte padrão") + +*Texto alternativo: fluxo de definição de configurações de fonte padrão no Aspose.Words for Java.* + +O diagrama ilustra o fluxo desde a inicialização de `LoadOptions` (onde **definimos configurações de fonte padrão**) até a anexação do listener de avisos (para **detectar fontes ausentes**) e, finalmente, o carregamento do documento. + +--- + +## Armadilhas Comuns & Como Evitá‑las + +| Armadilha | Por que acontece | Correção | +|-----------|------------------|----------| +| **Esqueceu de chamar `setFontSettings`** | Aspose usa os padrões do sistema, ocultando fontes ausentes. | Sempre crie uma nova instância de `FontSettings` e atribua‑a ao `LoadOptions`. | +| **Listener não disparado** | Listener adicionado após o carregamento do documento. | Adicione o listener de avisos *antes* de chamar `new Document(...)`. | +| **Erro de digitação no caminho gera `FileNotFoundException`** | Caminho codificado rígido não corresponde à sensibilidade a maiúsculas/minúsculas do SO. | Use `Paths.get("...").toAbsolutePath()` ou configure um caminho relativo a partir da raiz do projeto. | +| **Múltiplas fontes ausentes sobrecarregam os logs** | Documentos grandes podem gerar dezenas de avisos. | Filtre duplicatas ou agregue mensagens em um `Set` antes de imprimir. | + +--- + +## Expandindo a Solução + +Se você precisar **definir configurações de fonte** para toda a aplicação, considere criar um `FontSettings` singleton e reutilizá‑lo em todos os `LoadOptions`. Dessa forma, você mantém uma estratégia de fallback consistente e evita a criação repetida de objetos. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Agora qualquer parte da sua base de código pode simplesmente chamar `FontConfig.getLoadOptions()` e se beneficiar instantaneamente da mesma lógica de **definir configurações de fonte padrão**. + +--- + +## Conclusão + +Acabamos de cobrir tudo o que você precisa para **definir configurações de fonte padrão** no Aspose.Words for Java, **definir configurações de fonte** programaticamente e **detectar fontes ausentes** antes que elas corrompam sua saída. O exemplo completo e executável está nos trechos de código acima, e você pode colá‑lo diretamente no seu IDE para ver os avisos em ação. + +Próximos passos? Experimente trocar a fonte de fallback, teste diferentes formatos de documento (DOC, RTF, HTML) ou integre o coletor de avisos a um painel de monitoramento. Quanto mais você brincar com `FontSettings`, mais confiança terá de que seus documentos gerados aparecerão exatamente como esperado — sem surpresas, sem glifos quebrados. + +Tem perguntas ou um cenário complicado de substituição de fonte? Deixe um comentário abaixo, e feliz codificação! + +## Tutoriais Relacionados + +- [Definir Configurações de Fallback de Fonte](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Definir Configurações de Fallback de Fonte](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Definir Configurações de Fallback de Fonte](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/java/images-shapes/_index.md b/words/portuguese/java/images-shapes/_index.md index 8e253922b6..0d9678debf 100644 --- a/words/portuguese/java/images-shapes/_index.md +++ b/words/portuguese/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aprenda a gerar miniaturas de alta qualidade e bitmaps de tamanho personalizado ### [Criar documento Word Java – Adicionar forma retangular com efeito de sombra](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Aprenda a inserir uma forma retangular com sombra em documentos Word usando Aspose.Words para Java. +### [Criar forma retangular em documento Word Java – Guia completo passo a passo](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Um guia detalhado que mostra como inserir e formatar uma forma retangular em documentos Word usando Aspose.Words para Java. + ## Recursos adicionais - [Aspose.Words para documentação Java](https://reference.aspose.com/words/java/) diff --git a/words/portuguese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/portuguese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..79f63c8a8f --- /dev/null +++ b/words/portuguese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Crie uma forma retangular em um documento Word em Java e aplique o efeito + de sombra. Aprenda como adicionar sombra à forma, definir a distância da sombra + e salvar o arquivo. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: pt +og_description: Crie uma forma retangular em um documento Word Java, aplique o efeito + de sombra, adicione sombra à forma e defina a distância da sombra com Aspose.Words. +og_title: Criar Forma Retangular em Documento Word Java – Guia Completo +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Criar Forma Retangular em Documento Word Java – Guia Completo Passo a Passo +url: /pt/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Criar Forma Retangular em Documento Word Java – Guia Completo Passo a Passo + +Já precisou **criar forma retangular** em um documento Word Java, mas não sabia por onde começar? Você não está sozinho—muitos desenvolvedores encontram esse obstáculo ao gerar relatórios ou faturas programaticamente. Neste tutorial vamos percorrer exatamente como **criar forma retangular**, aplicar uma sombra refinada e ajustar a distância da sombra para que o resultado pareça profissional. + +Usaremos o Aspose.Words for Java, uma biblioteca robusta que permite manipular arquivos Word sem precisar do Microsoft Office instalado. Ao final deste guia você será capaz de criar projetos **word document java** que **add shape shadow**, **apply shadow effect** e **set shadow distance** com apenas algumas linhas de código. + +--- + +## O Que Você Vai Construir + +- Um novo arquivo `.docx` contendo um retângulo ciano. +- Uma sombra realista que é desfocada, inclinada e parcialmente transparente. +- Controle total sobre a distância da sombra em relação à forma. +- Uma classe Java pronta‑para‑executar que pode ser inserida em qualquer projeto Maven ou Gradle. + +Sem ferramentas externas, sem etapas manuais de UI—apenas código puro. + +--- + +## Pré‑requisitos + +- Java 8 ou superior (o código funciona em Java 11, Java 17, etc.). +- Biblioteca Aspose.Words for Java (disponível via Maven Central). +- Uma IDE ou editor de texto de sua preferência (IntelliJ IDEA, Eclipse, VS Code…). +- Familiaridade básica com a sintaxe Java. + +Se você nunca adicionou uma dependência Maven antes, aqui está o snippet rápido: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Agora, vamos mergulhar. + +--- + +## Etapa 1: Criar Forma Retangular em um Documento Word + +A primeira coisa que precisamos é de um documento em branco e de um `DocumentBuilder`. Pense no builder como uma caneta que escreve no documento. Depois de tê‑lo, podemos **create rectangle shape** com uma única chamada de método. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Por que isso importa:** O método `insertShape` não só cria a geometria, como também adiciona a forma à coleção interna do documento, permitindo que você comece a estilizar imediatamente. + +--- + +## Etapa 2: Aplicar Efeito de Sombra à Forma + +Agora que o retângulo está na página, vamos **apply shadow effect**. Sombras dão profundidade, fazendo a forma parecer levantada da página—uma melhoria sutil de UI que pode aumentar a legibilidade em relatórios. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Dica de especialista:** Um desfoque de `5.0` parece natural na maioria dos documentos exibidos em tela. Se você for imprimir, talvez queira um valor ligeiramente menor para evitar uma aparência borrada. + +--- + +## Etapa 3: Definir Distância da Sombra – Ajuste Fino da Posicionamento + +Sombras não são apenas sobre desfoque; elas também precisam do deslocamento correto. É aqui que **set shadow distance** entra. Uma distância de `7.0` pontos cria um deslocamento modesto que é perceptível, mas não excessivo. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **E se você precisar de um deslocamento maior?** Aumente o valor; diminua para um visual mais compacto. Lembre‑se de que a distância trabalha em conjunto com o ângulo para posicionar a sombra corretamente. + +--- + +## Etapa 4: Salvar o Documento – Persistir Seu Trabalho + +Por fim, gravamos o documento no disco. Altere o caminho para onde você quiser que o arquivo seja salvo. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Executar a classe cria um arquivo `shadow.docx` que, ao ser aberto no Microsoft Word ou LibreOffice, mostra um retângulo ciano com uma sombra cinza suave inclinada a 45° e deslocada em 7 pontos. + +--- + +## Exemplo Completo Funcionando + +Abaixo está o código completo, pronto para copiar e colar. Inclui todas as importações, comentários e a chamada final de `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Saída esperada:** Abra `shadow.docx` → você verá um retângulo ciano centralizado na primeira página, projetando uma sombra cinza sutil ligeiramente deslocada para a parte inferior‑direita. O desfoque e a transparência da sombra dão a impressão de iluminação natural. + +--- + +## Perguntas Frequentes & Casos de Borda + +### “Posso usar uma forma diferente?” + +Com certeza. Substitua `ShapeType.RECTANGLE` por `ShapeType.OVAL`, `ShapeType.LINE` ou qualquer outro enum suportado. O restante do código de sombra permanece igual. + +### “E se eu precisar de várias sombras?” + +O Aspose.Words suporta apenas uma sombra por forma. Para simular múltiplas sombras, duplique a forma, desloque cada cópia e ajuste a transparência. + +### “A sombra é visível no LibreOffice?” + +Sim—o Aspose.Words grava OOXML padrão, que o LibreOffice interpreta corretamente. A sombra pode parecer ligeiramente diferente devido aos motores de renderização, mas o efeito persiste. + +### “Como mudar a cor da sombra para combinar com a minha marca?” + +Basta trocar `java.awt.Color.GRAY` por qualquer `java.awt.Color` que preferir, como `new java.awt.Color(0, 120, 215)` para um azul corporativo. + +--- + +## Ilustração da Imagem + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illustration showing a cyan rectangle with a gray drop shadow in a Word document. + +--- + +## Recapitulação & Próximos Passos + +Cobrimos como **create rectangle shape**, **apply shadow effect**, **add shape shadow** e **set shadow distance** usando Aspose.Words for Java. O código é autocontido, roda em qualquer JDK moderno e produz um arquivo `.docx` polido pronto para distribuição. + +Quer ir além? Experimente: + +- Adicionar texto dentro do retângulo com `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Criar uma tabela de formas para montar um diagrama. +- Exportar o documento para PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Cada um desses itens se baseia nos mesmos fundamentos que acabamos de explorar, então você se sentirá confortável em estender o exemplo. + +--- + +## Considerações Finais + +Dominar tarefas **create word document java** como modelagem e sombreamento dá a você uma grande vantagem ao automatizar relatórios, contratos ou materiais de marketing. A abordagem mostrada aqui é limpa, mantível e—o mais importante—fácil de ajustar para qualquer estilo visual que você precise. + +Teste o código, ajuste o desfoque, ângulo e distância, e veja seus documentos se transformarem de simples a sofisticados. Se encontrar algum obstáculo, deixe um comentário abaixo; ficarei feliz em ajudar. + +Happy coding! + +## Tutoriais Relacionados + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/russian/java/document-conversion-and-export/_index.md index 7147f29a77..9efee256dd 100644 --- a/words/russian/java/document-conversion-and-export/_index.md +++ b/words/russian/java/document-conversion-and-export/_index.md @@ -85,35 +85,50 @@ weight: 22 Откройте для себя мощь форм документов в Aspose.Words для Java. Научитесь создавать визуально привлекательные документы с помощью пошаговых примеров. ### [Использование водяных знаков в документах в Aspose.Words для Java](./using-watermarks-to-documents/) -Узнайте, как добавлять водяные знаки в документы в Aspose.Words для Java. Настройте текстовые и графические водяные знаки для профессионально выглядящих документов. +Узнайте, как добавлять водяные знаки в документы в Aspose.Words for Java. Настройте текстовые и графические водяные знаки для профессионально выглядящих документов. ### [Форматирование таблиц и стилей таблиц в Aspose.Words для Java](./formatting-tables-and-table-styles/) -Узнайте, как форматировать таблицы и применять стили таблиц в Aspose.Words для Java. Изучите пошаговые руководства с исходным кодом для эффективного форматирования таблиц. Улучшите макет документа с помощью Aspose.Words. +Узнайте, как форматировать таблицы и применять стили таблиц в Aspose.Words for Java. Изучите пошаговые руководства с исходным кодом для эффективного форматирования таблиц. Улучшите макет документа с помощью Aspose.Words. -### [Использование фигур в документах в Aspose.Words for Java](./using-document-shapes/) +### [Использование фигур в документах в Aspose.Words для Java](./using-document-shapes/) Откройте мощь фигур в документах с Aspose.Words for Java. Научитесь создавать визуально привлекательные документы с пошаговыми примерами. -### [Использование водяных знаков в документах в Aspose.Words for Java](./using-watermarks-to-documents/) +### [Использование водяных знаков в документах в Aspose.Words для Java](./using-watermarks-to-documents/) Узнайте, как добавить водяные знаки в документы с помощью Aspose.Words for Java. Настройте текстовые и графические водяные знаки для профессионального вида документов. -### [Форматирование таблиц и стилей таблиц в Aspose.Words for Java](./formatting-tables-and-table-styles/) +### [Форматирование таблиц и стилей таблиц в Aspose.Words для Java](./formatting-tables-and-table-styles/) Узнайте, как форматировать таблицы и применять стили таблиц в Aspose.Words for Java. Исследуйте пошаговые руководства с исходным кодом для эффективного форматирования таблиц. Улучшите макет ваших документов с Aspose.Words. ### [Конвертировать docx в markdown – экспортировать математические уравнения в LaTeX с помощью Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Преобразуйте DOCX в markdown и экспортируйте уравнения Math в LaTeX с помощью Aspose.Words. +### [Сохранить Word как markdown – экспортировать Math в LaTeX с Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Сохраните документ Word в формате markdown и экспортируйте математические уравнения в LaTeX с помощью Java. + ### [Как встраивать изображения в Markdown при конвертации DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Узнайте, как сохранять изображения из DOCX при экспорте в Markdown с помощью Aspose.Words for Java. +### [Встраивание изображений в формате Base64 при конвертации DOCX в Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Узнайте, как встраивать изображения в виде Base64 при конвертации DOCX в Markdown с помощью Aspose.Words for Java. + ### [Сохранить документ как TXT – Быстрое руководство по экспорту математических формул Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Узнайте, как экспортировать математические уравнения из Word в формат TXT с помощью Aspose.Words for Java. +### [Экспорт docx в txt с Java – Полное руководство по программированию](./export-docx-to-txt-with-java-complete-programming-guide/) +Подробное руководство по экспорту документов DOCX в текстовый формат TXT с использованием Aspose.Words for Java. + ### [Aspose.Words в PDF – Конвертировать DOCX в PDF в Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Пошаговое руководство по конвертации DOCX в PDF с помощью Aspose.Words for Java, включая настройку параметров сохранения. ### [Создание доступного PDF из DOCX – Полное руководство](./create-accessible-pdf-from-docx-complete-guide/) Узнайте, как преобразовать DOCX в PDF, соответствующий требованиям доступности, используя Aspose.Words for Java. +### [Сохранить документ как PDF с Aspose.Words для Java – Полное руководство по доступности](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Пошаговое руководство по сохранению документов в PDF с полной поддержкой доступности согласно стандартам WCAG. + +### [Создание доступного PDF в Java – Полное руководство по тегированию](./create-accessible-pdf-in-java-full-tagging-guide/) +Полное руководство по созданию доступных PDF с полным тегированием в Aspose.Words для Java. + ## Часто задаваемые вопросы **Q: Как добавить водяной знак в существующий PDF с помощью Aspose.Words?** diff --git a/words/russian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/russian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..1734e9340f --- /dev/null +++ b/words/russian/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-05-26 +description: Создайте доступный PDF на Java с пошаговым кодом. Узнайте, как добавить + теги в PDF для обеспечения доступности и включить тегирование PDF с помощью PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: ru +og_description: Создайте доступный PDF в Java с пошаговым кодом. Узнайте, как помечать + PDF для доступности и включать тегирование PDF с помощью PdfSaveOptions. +og_title: Создание доступного PDF в Java – Полное руководство по тегированию +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Создание доступного PDF в Java — Полное руководство по тегированию +url: /ru/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание доступного PDF в Java – Полное руководство по тегированию + +Вы когда‑нибудь задумывались, как **создать доступный PDF** напрямую из кода Java? Вы не одиноки. Многие разработчики должны обслуживать пользователей, использующих программы чтения с экрана, и разница между обычным PDF и доступным может быть огромной. В этом руководстве мы пройдёмся по **тегированию PDF для доступности**, покажем, как **создать тегированный PDF** с помощью Aspose PDF for Java, и раскроем точные шаги по **добавлению тегов доступности в PDF**, чтобы каждый читатель получал одинаковую информацию. + +Мы также рассмотрим лучшие практики **включения PDF‑тегирования**, распространённые подводные камни и полностью готовый пример, который вы можете сразу добавить в свой проект. Никаких расплывчатых ссылок — только конкретный код, объяснения и готовый файл, который можно открыть в Adobe Acrobat для проверки тегов. + +## Что вы узнаете + +- Почему важны PDF‑теги и соответствие требованиям доступности. +- Требования и настройка библиотеки (Aspose PDF for Java 23.10 или новее). +- Как **создать доступный PDF** с нуля, шаг за шагом. +- Способы **добавления тегов доступности в PDF** помимо базового вызова `setTagDocumentStructure`. +- Советы по тестированию результата и устранению распространённых проблем. + +К концу этого руководства вы сможете генерировать PDF, которые проходят проверку WCAG 2.1 AA и выглядят профессионально. + +--- + +## Предварительные требования + +Прежде чем погрузиться в детали, убедитесь, что у вас есть: + +| Требование | Причина | +|------------|---------| +| **Java 8+** | Современные возможности языка и лучшая работа с Unicode. | +| **Aspose PDF for Java** (v23.10 or newer) | Предоставляет класс `PdfSaveOptions` и поддержку тегирования. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Для удобной компиляции и отладки. | +| **Write permission** to a folder where the PDF will be saved | Вызов `doc.save` требует путь с правом записи. | + +Если вы ещё не добавили Aspose PDF в свой проект, вставьте следующую зависимость Maven в ваш `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Подсказка:** Используйте последнюю версию; более новые релизы повышают точность тегирования и добавляют функции доступности, специфичные для языка. + +## Шаг 1: Настройка скелета документа + +Сначала мы создаём новый объект `Document`. Представьте его как чистый холст, который позже будет содержать теги, необходимые для доступности. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Почему это важно:** Без содержимого нечего тегировать. Добавление даже простого `TextFragment` даёт движку тегирования материал для работы, и он автоматически создаёт тег `

` (paragraph), когда мы позже включим структурное тегирование. + +## Шаг 2: Создание параметров сохранения PDF (ядро тегирования) + +Теперь мы подготавливаем параметры, которые указывают Aspose PDF встроить логическое дерево структуры в файл. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Вызов `setTagDocumentStructure(true)` является переключателем **включения PDF‑тегирования**. Когда он установлен в true, библиотека строит дерево тегов, отражающее визуальное расположение, делая PDF читаемым вспомогательными технологиями. + +> **Примечание:** Это самый простой способ **как создать тегированный pdf**. Для более тонкого управления (например, установки языка или пользовательских тегов) вы можете изучить `pdfOptions.setTagLanguage("en-US")` и `pdfOptions.setTagStructureTreeRoot(...)`. + +## Шаг 3: Сохранение доступного PDF + +Наконец, мы сохраняем документ на диск, используя только что настроенные параметры. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Когда `doc.save` завершится, вы найдёте `accessible.pdf` в папке `output`. Откройте его в Adobe Acrobat и посмотрите в **File → Properties → Description → Tags** — вы должны увидеть заполненное дерево тегов. + +## Как тегировать PDF для доступности – выход за рамки базового + +Приведённый выше трёхшаговый фрагмент уже **добавляет теги доступности в PDF**, но в реальных документах часто требуется дополнительная доработка. Ниже представлены несколько улучшений, которые можно добавить: + +### 1. Установка языка документа + +Программы чтения используют атрибут языка для правильного произношения текста. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Указание заголовка и темы + +Метаданные помогают вспомогательным средствам предоставить контекст ещё до того, как пользователь откроет файл. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Тегирование изображений альтернативным текстом + +Если вы вставляете изображения, им нужны описания `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Пометка заголовков таблиц + +Таблицы часто сбивают с толку читателей, если не пометить строки‑заголовки. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Эти дополнительные шаги делают ваш PDF не только *технически* тегированным, но и действительно **доступным** для широкой аудитории. + +## Распространённые подводные камни при включении PDF‑тегирования + +| Симптом | Вероятная причина | Решение | +|---------|-------------------|---------| +| Теги отсутствуют в Acrobat | `setTagDocumentStructure` left as `false` | Убедитесь, что вызываете `pdfOptions.setTagDocumentStructure(true)`. | +| Неправильный порядок чтения | Complex layout without explicit tags | Используйте `pdfOptions.setTagStructureTreeRoot(...)` для определения пользовательского порядка. | +| Изображения читаются как «image» без описания | No alternative text set | Вызовите `image.getAlternativeText().setValue("...")`. | +| Язык не распознан | `setTagLanguage` omitted or wrong locale | Укажите код языка BCP‑47 (`en-US`, `fr-FR`). | + +Осведомлённость об этих проблемах экономит часы отладки в дальнейшем. + +## Проверка результата – чего ожидать + +После запуска программы откройте `output/accessible.pdf` в Adobe Acrobat Reader: + +1. **Панель тегов** (`View → Show/Hide → Navigation Panes → Tags`) должна отображать иерархию типа `/Document → /Part → /Sect → /Para`. +2. **Порядок чтения** должен соответствовать визуальному потоку (сначала текст, затем изображения). +3. **Средство чтения** (NVDA, VoiceOver) будет произносить «Hello, accessible PDF!», а не просто «Page 1». + +Если какой‑либо из пунктов отсутствует, перепроверьте вышеуказанные шаги — особенно вызов `setTagDocumentStructure`. + +## Полный рабочий пример (готов к копированию и вставке) + + + +## Связанные руководства + +- [Создать доступный PDF из Word – Конвертация в PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Создать доступный PDF из DOCX – Полное руководство](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Как сохранить документ как PDF с помощью Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/russian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..ed31df82f8 --- /dev/null +++ b/words/russian/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Встраивайте изображения в формате base64 при преобразовании docx в markdown + с помощью Aspose.Words for Java. Узнайте, как конвертировать Word в markdown, сохранять + Word как markdown и обрабатывать изображения. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: ru +og_description: Встраивание изображений в формате base64 при конвертации docx в markdown + с помощью Aspose.Words для Java. Полное руководство по преобразованию Word в markdown + и сохранению Word в markdown. +og_title: Встраивание изображений в формате Base64 при преобразовании DOCX в Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Встраивание изображений в формате Base64 при конвертации DOCX в Markdown +url: /ru/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Встраивание изображений в формате Base64 при конвертации DOCX в Markdown + +Вы когда‑нибудь задумывались, как **встраивать изображения в формате base64** при **конвертации docx в markdown**? Вы не одиноки — разработчики постоянно спрашивают, как сохранить изображения внутри текста без необходимости управлять отдельными файлами. Хорошая новость в том, что Aspose.Words for Java делает это проще простого: вы можете конвертировать документ Word в Markdown и автоматически встраивать каждое изображение как строку Base64. + +В этом руководстве мы пройдем весь процесс — от загрузки `.docx`, содержащего изображения, до настройки обратного вызова `MarkdownSaveOptions`, который делает всю тяжелую работу, и, наконец, сохранения результата в чистый файл `.md`. К концу вы точно будете знать, как **convert word to markdown**, **convert images to base64** и **save word as markdown** без оставления лишних папок с изображениями. Без внешних инструментов, без ручной пост‑обработки — только чистый Java‑код, который можно добавить в любой проект. + +## Что понадобится + +- **Java 17** (или любой современный JDK) — код использует синтаксис лямбда, но вы можете адаптировать его под более старые версии. +- **Aspose.Words for Java** library (latest version as of 2026). Add the Maven dependency or the JAR to your classpath. +- Пример файла **DOCX**, содержащего хотя бы одно изображение. +- IDE или простой текстовый редактор — Visual Studio Code, IntelliJ IDEA или даже `vim` подойдут. + +Если у вас уже есть всё это, отлично — сразу приступаем. + +## Шаг 1: Загрузка документа Word + +Сначала мы создаём экземпляр `Document`, указывающий на исходный файл. Это тот же шаг, независимо от того, **convert docx to markdown** вы делаете или просто читаете файл для других целей. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Почему это важно:** Объект `Document` является точкой входа для любой операции Aspose. Он хранит всю структуру Word — включая изображения, таблицы и стили — поэтому последующий обратный вызов может инспектировать каждый ресурс. + +## Шаг 2: Создание MarkdownSaveOptions и регистрация обратного вызова сохранения ресурсов + +Вся магия происходит в `MarkdownSaveOptions`. Подключив `IResourceSavingCallback`, мы получаем контроль над тем, как каждый внешний ресурс (например, изображение) записывается. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Зачем использовать `setSaveToMemory(true)`? + +Когда `saveToMemory` установлен в `true`, Aspose записывает байты изображения в поток памяти вместо файла. Экспортер Markdown затем преобразует этот поток в строку Base64 и вставляет её напрямую в тег изображения Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Это и есть суть **встраивания изображений в формате base64**. + +## Шаг 3: Сохранение документа в формате Markdown + +Теперь, когда обратный вызов настроен, последний шаг — просто вызвать `save`. Здесь мы действительно **convert word to markdown**, а благодаря обратному вызову также **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Результат:** `out.md` содержит текст Markdown, где каждое изображение представлено как URI `data:`. Дополнительные файлы изображений на диск не создаются, поэтому папка остаётся чистой. + +## Шаг 4: Проверка результата и распространённые подводные камни + +Откройте сгенерированный `out.md` в любом просмотрщике Markdown (VS Code, GitHub или статический генератор сайтов). Вы должны увидеть что‑то вроде: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Список проверок при устранении неполадок + +| Проблема | Вероятная причина | Решение | +|----------|-------------------|---------| +| Изображение отображается как битая ссылка | `setSaveToMemory` был опущен | Убедитесь, что `args.setSaveToMemory(true);` находится внутри обратного вызова | +| Base64‑строка обрезана | Несоответствие кодировки выходного файла | Сохраните Markdown в кодировке UTF‑8 (по умолчанию для Aspose) | +| Неожиданные имена файлов | `setKeepResourceOriginalName(true)` | Оставьте `false`, чтобы принудительно использовать пользовательскую логику именования | + +## Шаг 5: Расширенные варианты (необязательно) + +### Конвертировать только выбранные изображения + +Если вы хотите встраивать только определённые изображения (например, те, что больше 100 KB), добавьте проверку размера: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Использовать другой формат изображения + +`ResourceSavingArgs` предоставляет вам необработанные байты, поэтому вы можете перекодировать JPEG в PNG перед встраиванием — это полезно, когда потребитель Markdown предпочитает PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Эти настройки показывают, насколько гибок подход **встраивания изображений в формате base64**, когда вы **convert docx to markdown**. + +## Заключение + +Вы только что узнали, как **встраивать изображения в формате base64** при **конвертации docx в markdown** с помощью Aspose.Words for Java. Подключив простой `IResourceSavingCallback`, библиотека делает всю тяжелую работу: она **convert word to markdown**, **convert images to base64** и, наконец, **save word as markdown** одним вызовом `save`. + +Не стесняйтесь экспериментировать — пробуйте разные правила фильтрации изображений, переключайтесь на вывод HTML или соединяйте этот шаг с генератором статических сайтов. Тот же шаблон работает и для других форматов (HTML, EPUB), так что вы можете переиспользовать обратный вызов там, где нужны встроенные ресурсы. + +**Следующие шаги:** +- Исследуйте `HtmlSaveOptions` для HTML‑с изображениями в Base64. +- Объедините это с CI‑конвейером для автоматической генерации документации. +- Погрузитесь в `DocumentVisitor` от Aspose, если нужен ещё более тонкий контроль над процессом конвертации. + +Счастливого кодинга и наслаждайтесь чистыми, самодостаточными файлами Markdown! + +## Связанные руководства + +- [Как встраивать изображения в Markdown при конвертации DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Конвертация docx в markdown – экспорт математических уравнений в LaTeX с помощью Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Сохранение изображений из Word – руководство Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/russian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..3863a1bcc9 --- /dev/null +++ b/words/russian/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-26 +description: Экспортируйте docx в txt с помощью Java и Aspose.Words. Узнайте, как + конвертировать docx в текст, сохранить Unicode и экспортировать Word в txt за несколько + шагов. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: ru +og_description: Экспорт docx в txt на Java. Этот учебник показывает, как конвертировать + docx в текст, сохранять обычный текст Unicode и эффективно экспортировать Word в + txt. +og_title: Экспорт docx в txt с помощью Java – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Экспорт docx в txt с помощью Java – Полное руководство по программированию +url: /ru/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Экспорт docx в txt с Java – Полное руководство по программированию + +Когда‑нибудь вам нужно было **export docx to txt**, но вы боялись потерять специальные символы? Вы не одиноки. При конвертации документов Word в plain‑text файлы символы Unicode, таблицы и даже простое форматирование могут исчезнуть как по волшебству. + +В этом руководстве мы пройдём надёжный способ **export docx to txt** с использованием Aspose.Words for Java, сохраняющий каждый символ Unicode и поддерживающий читаемость таблиц. К концу вы также узнаете, как **convert docx to text**, **convert word to text**, и даже **export word as txt** без проблем. + +## Что охватывает данный учебник + +* Настройка Aspose.Words в Java‑проекте +* Загрузка DOCX‑файла и подготовка его к выводу в plain‑text +* Настройка поддержки **plain text unicode** через `TxtSaveOptions` +* Дополнительные приёмы для сохранения читаемости таблиц в получаемом файле `.txt` +* Сохранение файла и проверка результата + +Без внешних скриптов, без загадочных командных утилит — только чистый Java‑код, который можно вставить в любой проект Maven или Gradle. + +> **Why care?** Plain‑text файлы легковесны, удобны для систем контроля версий и идеальны для индексации поиска или последующих конвейеров обработки. Если вы когда‑либо пытались `cat` Word‑файл и получали бессмыслицу, это руководство решает эту проблему. + +## Export docx в txt – Обзор + +Прежде чем погрузиться в код, разберём терминологию. **Export docx to txt** означает взятие пакета Microsoft Word `.docx` и запись его текстового содержимого в простой файл `.txt`. В отличие от конвертации в PDF, экспорт в текст удаляет стили, но может сохранять разрывы строк, маркеры абзацев и — при правильной настройке — символы Unicode, такие как эмодзи, буквы с диакритическими знаками или азиатские скрипты. + +Aspose.Words упрощает задачу, поскольку абстрагирует формат файлов Word и предоставляет класс `TxtSaveOptions`, где можно задать кодировку, обработку таблиц и многое другое. + +### Требования + +* Java 11 или новее (API работает с Java 8+, но будем считать, что используется современный JDK) +* Aspose.Words for Java JAR (доступен в Maven Central) +* Пример файла `unicode.docx`, содержащего разнообразные символы Unicode — например “こんにちは”, “😊” и простую таблицу + +Если всё готово, приступим. + +## Шаг 1: Загрузка DOCX‑файла (Convert docx to text) + +Первое, что нужно сделать, — прочитать исходный документ в память. Здесь официально начинается процесс **convert docx to text**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Почему это важно:* `Document` — представление Aspose.Words для файла Word. При загрузке вы получаете доступ ко всем абзацам, таблицам и даже скрытым элементам. Если файл не найден, Aspose бросает понятный `FileNotFoundException`, так что вы сразу узнаете, в чём проблема. + +## Шаг 2: Настройка TxtSaveOptions для Unicode (Plain text unicode) + +Plain‑text файлы — это просто поток байтов, поэтому необходимо указать Java, какой набор символов использовать. UTF‑8 является де‑факто стандартом для **plain text unicode**, поскольку может кодировать любую точку Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro tip:** Если пропустить вызов `setEncoding`, Aspose использует кодировку по умолчанию платформы, которая на многих Windows‑машинах — Windows‑1252. Эта кодировка будет тихо отбрасывать такие символы, как “ß” или “—”. + +## Шаг 3: Сохранение макета таблицы (Опционально, но удобно для читаемости) + +При **export word as txt** таблицы обычно сплющиваются в одну строку текста, делая их нечитаемыми. Aspose.Words предоставляет простой флаг для сохранения визуальной структуры. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Когда использовать:* Если ваш исходный DOCX содержит счета, расписания или любые табличные данные, включение `PreserveTableLayout` вставит табуляции и разрывы строк, чтобы полученный файл всё ещё напоминал таблицу. Если это не требуется, можно опустить эту строку и получить более компактный вывод. + +## Шаг 4: Сохранение документа в plain‑text (Export word as txt) + +Теперь основная работа выполнена — просто запишите байты на диск. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Запуск программы создаёт `plain.txt` в той же папке. Откройте его в любом текстовом редакторе (Notepad++, VS Code, даже `cat` в терминале) и вы увидите: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Обратите внимание, как японское приветствие и смайлик сохранились, а таблица удержала свои столбцы благодаря `PreserveTableLayout`. Это суть чистого **export docx to txt**. + +## Шаг 5: Проверка вывода (Convert word to text sanity check) + +Быстрая проверка помогает избежать потери данных. Ниже несколько способов убедиться, что вы действительно **convert word to text** правильно: + +1. **Checksum comparison** – вычислите SHA‑256 хеш файла `.txt` до и после конвертации туда‑обратно (txt → docx → txt), чтобы убедиться в стабильности. +2. **Search for Unicode markers** – используйте `grep` или поиск в файлах IDE, чтобы найти такие символы, как “😊”. +3. **Open in multiple editors** – некоторые старые версии Windows Notepad всё ещё неправильно интерпретируют UTF‑8 без BOM; открытие файла в VS Code подтверждает правильную кодировку. + +Если любой из этих тестов не прошёл, проверьте, что `saveOptions.setEncoding(StandardCharsets.UTF_8)` присутствует, и что ваш исходный DOCX действительно содержит Unicode‑текст. + +## Распространённые подводные камни и как их избежать + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Отсутствующие символы** | Системная кодировка по умолчанию (например, Windows‑1252) отбрасывает не‑ASCII символы. | Явно задайте UTF‑8 через `saveOptions.setEncoding`. | +| **Таблицы превращаются в одну строку** | `PreserveTableLayout` оставлен со значением по умолчанию `false`. | Вызовите `saveOptions.setPreserveTableLayout(true)`. | +| **Файл не найден** | Неправильный путь или отсутствие прав чтения. | Используйте абсолютные пути или `Paths.get(...)` с корректной обработкой исключений. | +| **Снижение производительности на больших документах** | Загрузка всего документа в память. | Потоково обрабатывайте документ частями с помощью `DocumentBuilder`, если нужны только определённые секции. | + +## Бонус: Экспорт нескольких DOCX‑файлов пакетно + +Если вам нужно **convert docx to text** для всей папки, оберните логику в цикл: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Этот фрагмент **export docx to txt** для каждого файла в каталоге, экономя вам часы ручной работы. + +## Заключение + +Вы только что узнали, как **export docx to txt** с помощью Java, гарантируя, что каждый символ Unicode остаётся неизменным, таблицы остаются читаемыми, а весь процесс повторяемый. Настроив `TxtSaveOptions` на UTF‑8 и при необходимости сохраняя макет таблиц, вы можете надёжно **convert docx to text**, **convert word to text** и **export word as txt** для любого последующего рабочего процесса. + +Готовы к следующему вызову? Попробуйте экспортировать в другие plain‑text форматы, такие как markdown (`.md`) или CSV, или изучите возможности конвертации PDF в Aspose.Words. Те же принципы — явная кодировка, сохранение макета и тщательная проверка — применимы везде. + +Счастливого кодинга, и пусть ваши текстовые файлы всегда остаются богатыми Unicode! + +--- + +![Схема, показывающая процесс экспорта docx в txt](/images/export-docx-to-txt-pipeline.png){alt="схема процесса экспорта docx в txt"} + +## Связанные руководства + +- [Конвертировать Docx в Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Конвертировать DOCX в PDF на Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Конвертировать docx в markdown – Экспорт математических уравнений в LaTeX с Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/russian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..b3e112a2bd --- /dev/null +++ b/words/russian/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-05-26 +description: Сохраните документ в PDF с помощью Aspose.Words Java и добавьте доступность + в PDF. Узнайте, как преобразовать DOCX в PDF, пометить горизонтальные линии и обеспечить + соответствие PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: ru +og_description: Сохраните документ в PDF с помощью Aspose.Words Java, добавив доступность + в PDF. Пошаговое руководство по конвертации docx в PDF и маркировке горизонтальных + линий для соответствия PDF/UA‑2. +og_title: Сохранить документ в PDF с Aspose.Words Java — Доступность без усилий +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Сохранение документа в PDF с помощью Aspose.Words Java – Полное руководство + по доступности +url: /ru/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Сохранить документ как PDF с помощью Aspose.Words Java – Полное руководство по доступности + +Задумывались ли вы когда‑нибудь, как **save document as PDF** при этом сохранить его доступным для программ чтения с экрана? Вы не одиноки. Многие разработчики нуждаются в *convert docx to pdf* и при этом должны соответствовать стандартам PDF/UA‑2, особенно когда источник содержит горизонтальные линии, которые необходимо правильно пометить. В этом руководстве мы пошагово рассмотрим, как **save document as PDF** с помощью Aspose.Words for Java, автоматически **add accessibility to PDF**, и обеспечить, чтобы каждая горизонтальная линия была **tagged** как артефакт. + +Мы начнём с чистого проекта Java, загрузим DOCX, в котором уже есть горизонтальные линии, настроим параметры сохранения PDF для соответствия PDF/UA‑2 и, наконец, запишем полностью доступный PDF. К концу вы сможете **save document as pdf** с уверенностью, что он проходит проверки доступности. + +## Требования + +- Java 8 или новее установленный (в руководстве использовался JDK 17). +- Maven 3.6+ (или Gradle, если предпочитаете) для управления зависимостями. +- Действительная лицензия Aspose.Words for Java (бесплатная пробная версия работает, но лицензия удаляет водяные знаки оценки). +- Файл DOCX (`input.docx`), содержащий как минимум одну горизонтальную линию — представьте простой разделитель, который вы добавляете в Word. + +> **Pro tip:** Если у вас нет готового DOCX, просто создайте новый документ Word, введите несколько абзацев, вставьте *Insert → Horizontal Line*, сохраните как `input.docx` и поместите его в папку по вашему выбору. + +## Шаг 1: Настройка проекта Maven + +Сначала создайте новый проект Maven (или добавьте в существующий). В `pom.xml` необходимо указать зависимость Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Почему это важно:** Добавление артефакта `aspose-words` — первый шаг к *convert docx to pdf*. Без него компилятор не распознает `Document`, `PdfSaveOptions` и другие важные классы. + +## Шаг 2: Загрузка исходного DOCX, содержащего горизонтальные линии + +Теперь мы напишем небольшой класс Java, который загружает DOCX. Здесь начинается часть **tag horizontal rules** — Aspose.Words автоматически рассматривает горизонтальную линию как абзац с границей, но мы позволим движку PDF/UA выполнить маркировку. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Обратите внимание, что мы пока ничего не сохраняем — мы просто **loading** DOCX, что является первой частью *convert docx to pdf*. Объект `Document` теперь содержит весь контент Word, включая любые вставленные вами горизонтальные линии. + +## Шаг 3: Настройка параметров сохранения PDF для соответствия PDF/UA‑2 + +Магия **adding accessibility to PDF** реализуется в `PdfSaveOptions`. Установив уровень соответствия `PDF_UA_2`, Aspose.Words выполнит: + +1. Пометить структурные элементы (заголовки, таблицы и т.д.). +2. Отметить декоративные элементы — такие как горизонтальные линии — как *artifacts*, чтобы программы чтения с экрана их игнорировали. +3. Вставить необходимые метаданные PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Почему устанавливать соответствие?** Без `PDF_UA_2` полученный PDF может быть читаемым, но не пройдет автоматические валидаторы доступности. Требование **tag horizontal rules** удовлетворяется автоматически, поскольку PDF/UA рассматривает их как *artifacts*, когда включён флаг соответствия. + +## Шаг 4: Сохранение документа как PDF + +Теперь мы наконец **save document as pdf**. Эта единственная строка выполняет всю тяжелую работу — преобразование DOCX, применение тегов доступности и запись файла на диск. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Запустите класс (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) и вы увидите сообщение подтверждения. Откройте полученный `ua_compliant.pdf` в Adobe Acrobat и проверьте **File → Properties → Description → PDF/A, PDF/UA** — вы должны увидеть «PDF/UA‑2» в списке. + +### Ожидаемый вывод + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Откройте PDF, и вы заметите: + +- Текст документа можно выделять и искать. +- Горизонтальная линия невидима для программ чтения с экрана (рассматривается как артефакт). +- PDF проходит базовые инструменты проверки PDF/UA (например, PAC 3). + +## Шаг 5: Проверка доступности — быстрый чек‑лист + +Хотя Aspose.Words делает большую часть работы, рекомендуется проверить полученный результат. + +| Проверка | Как проверить | +|----------|----------------| +| **Заголовок документа** | Откройте Acrobat → File → Properties → поле Title (должно соответствовать `pdfOptions.setTitle`). | +| **Маркировка артефактов** | Используйте инструмент “Reading Order” в Acrobat. Горизонтальные линии должны отображаться как *Artifact* (серый). | +| **Логический порядок чтения** | Запустите “Accessibility Checker” в Acrobat; убедитесь, что нет структурных ошибок. | +| **Тегированный PDF** | В Acrobat откройте панель “Tags” — вы должны увидеть иерархию (Document → Section → Paragraph и т.д.). | +| **Соответствие PDF/UA** | Acrobat отобразит «PDF/UA‑2» во вкладке “Standards”. | + +Если любой из этих пунктов не проходит, проверьте, что вы используете последнюю версию Aspose.Words и что `setCompliance(PdfCompliance.PDF_UA_2)` применён корректно. + +## Распространённые ошибки и как их избежать + +1. **Отсутствующая лицензия** – Пробная версия добавляет водяной знак, который может нарушить проверку PDF/UA. Примените лицензию в начале `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Неправильный путь к входному файлу** – Исключение `FileNotFoundException` остановит конвертацию. Используйте абсолютные пути или разместите DOCX в корне проекта и укажите его как `new File("input.docx").getAbsolutePath()`. +3. **Использование старой версии Aspose** – Поддержка PDF/UA была добавлена в версии 22.9. Обновитесь до последней версии, чтобы избежать отсутствия функций. +4. **Горизонтальная линия как изображение** – Если вы вставили линию как изображение вместо встроенной горизонтальной линии Word, Aspose рассматривает её как обычное изображение, а не как артефакт. Замените изображение на встроенную в Word *Horizontal Line* для корректной маркировки. + +## Расширение решения — что если нужно больше? + +- **Custom Tags**: Если у вас есть другие декоративные элементы (например, декоративные иконки), вы можете вручную пометить их как артефакты, используя `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Пройдитесь по папке с файлами DOCX и выполните пакетное преобразование, повторно используя один экземпляр `PdfSaveOptions` для повышения производительности. +- **Adding a Language Tag**: Для многоязычных PDF установите `pdfOptions.setLanguage("en-US")`, чтобы помочь вспомогательным технологиям выбрать правильный голос. + +## Полный рабочий пример (весь код вместе) + +Ниже представлен полный, исполняемый Java‑программ. Скопируйте‑вставьте его в свою IDE, скорректируйте пути и запустите. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +## Заключение + +Мы только что продемонстрировали, как **save document as pdf** с помощью Aspose.Words for Java, автоматически **add accessibility to pdf** и **tag horizontal rules** как артефакты. Основные выводы: + +- Используйте `PdfSaveOptions` с уровнем соответствия `PDF_UA_2`, чтобы соответствовать стандартам доступности. +- Загрузка DOCX и вызов `doc.save(..., pdfOptions)` — всё, что нужно для **convert docx to pdf**. +- Горизонтальные линии обрабатываются автоматически — дополнительный код не требуется, что удовлетворяет требованию **tag horizontal rules**. +- Подход полностью **aspose convert docx pdf** совместим, работает с последней версией библиотеки и создаёт PDF, готовый к проверке. + +Готовы к следующему вызову? Попробуйте добавить пользовательские метаданные, внедрить шрифты или выполнить пакетную обработку целой папки файлов DOCX. Каждое из этих расширений опирается на ту же основу, которую мы здесь изложили. + +Есть вопросы о соответствии PDF/UA, лицензировании или работе с другими элементами Word? Оставьте комментарий или ознакомьтесь с официальной документацией Aspose — там множество примеров для изучения. Приятного кодинга и удачной работы над доступными PDF! + +![сохранить документ как pdf с помощью Aspose.Words Java – пример доступного PDF](placeholder-image.png "сохранить документ как pdf с помощью Aspose.Words Java – пример доступного PDF") + +## Связанные руководства + +- [Как сохранить документ как pdf с помощью Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Как конвертировать Word в PDF с помощью Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Конвертация DOCX в PDF на Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/russian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..6458d5a194 --- /dev/null +++ b/words/russian/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-05-26 +description: Сохраните документ Word в формате markdown и узнайте, как экспортировать + математические уравнения в LaTeX с помощью Aspose.Words для Java. Преобразуйте уравнения + Word в LaTeX всего за несколько строк кода. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: ru +og_description: Сохраните документ Word в формате markdown и узнайте, как экспортировать + математические уравнения в LaTeX с помощью Aspose.Words для Java. Полное, готовое + к запуску руководство. +og_title: Сохранить Word в markdown – экспортировать математику в LaTeX с Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Сохранить Word как markdown – экспортировать математику в LaTeX с помощью Java +url: /ru/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Сохранить Word как markdown – экспортировать математические формулы в LaTeX с помощью Java + +Когда‑нибудь вам нужно было **save word as markdown**, но вы боялись, что уравнения превратятся в нечитаемый беспорядок? Вы не одиноки. В этом руководстве мы пройдемся по **how to export math** из файла `.docx` напрямую в LaTeX, а остальная часть документа будет преобразована в чистый Markdown. + +Мы рассмотрим всё: от настройки библиотеки Aspose.Words до проверки конечного файла `out.md`. К концу вы сможете **convert word equations latex** одним вызовом метода и поймете небольшие нюансы, которые делают преобразование надёжным. + +--- + +## Что вам понадобится + +- **Java 8+** – код работает на любой современной JDK. +- **Aspose.Words for Java** – либо зависимость Maven/Gradle, либо JAR, если вы предпочитаете ручную настройку. +- Документ Word (`math.docx`), содержащий хотя бы одно уравнение Office Math. +- IDE или обычная командная строка `javac`/`java` – что вам удобнее. + +Если у вас уже есть всё это, отлично. Если нет, следующий раздел покажет, как именно добавить библиотеку в ваш проект. + +--- + +## Сохранить Word как markdown – Шаг 1: Добавить Aspose.Words в ваш проект + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose предлагает бесплатную временную лицензию для тестирования. Поместите файл `license.xml` в папку resources и вызовите `License license = new License(); license.setLicense("license.xml");` перед загрузкой любого документа. + +После того как зависимость будет разрешена, вы готовы писать код преобразования. + +--- + +## Как экспортировать математические уравнения в LaTeX + +Основная работа выполняется классом `MarkdownSaveOptions`. При переключении его `OfficeMathExportMode` на `LATEX` каждый объект Office Math будет отображён как фрагмент LaTeX внутри вывода Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Почему это работает + +- **`Document`** — точка входа Aspose; она абстрагирует файл `.docx` и предоставляет доступ ко всем узлам, включая уравнения. +- **`MarkdownSaveOptions`** указывает библиотеке *как* вы хотите получить вывод. Поведение по умолчанию — рендерить уравнения как изображения, что противоречит цели текстового формата. +- **`OfficeMathExportMode.LATEX`** заставляет движок переводить каждый узел `OfficeMath` в его эквивалент LaTeX, который могут отобразить парсеры Markdown (например, GitHub или Jekyll) в сочетании с плагином MathJax. + +## Преобразовать уравнения Word в LaTeX – Шаг 2: Проверить вывод Markdown + +После запуска программы откройте `out.md`. Вы должны увидеть что‑то вроде этого: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** Фрагменты LaTeX обёрнуты в `$…$` для встроенной математики и `$$…$$` для блочной. Это стандартный синтаксис, который понимают большинство генераторов статических сайтов при включённом MathJax. + +Если вы предпочитаете, чтобы уравнения оставались только встроенными, вы можете дополнительно настроить `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx в markdown latex – Шаг 3: Пограничные случаи и распространённые подводные камни + +| Ситуация | На что обратить внимание | Решение | +|-----------|-------------------|-----| +| **Complex nested equations** | Aspose может выводить лишние фигурные скобки `{}`, которые некоторые парсеры воспринимают буквально. | Пост‑обработать Markdown простым регулярным выражением, чтобы свернуть `{{` → `{`. | +| **Missing MathJax on the target site** | Уравнения отображаются как сырой код LaTeX. | Добавить `` в ваш HTML‑шаблон. | +| **Large documents** | Потребление памяти резко возрастает, так как весь документ загружается сразу. | Использовать `LoadOptions.setLoadFormat(LoadFormat.DOCX)` и рассмотреть обработку страниц пакетами, если возникнет `OutOfMemoryError`. | +| **License not set** | Вы получите предупреждение, и вывод может быть с водяным знаком. | Загрузить лицензию в начале `main`, как показано в совете по Maven выше. | + +## Сохранить Word как markdown – Полный рабочий пример + +Ниже представлен автономный класс, который вы можете скопировать и вставить в любой Java‑проект. Просто замените `YOUR_DIRECTORY` на путь к вашим файлам. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Запустите программу (`java MathToLatexMarkdown`), и вы увидите сообщение в консоли, подтверждающее успех. Откройте `out.md` в любом редакторе — уравнения должны быть чистыми фрагментами LaTeX, готовыми к отображению. + +## Ожидаемый снимок вывода + +![сохранить word как markdown вывод с уравнениями LaTeX](https://example.com/images/markdown-latex-output.png "сохранить word как markdown вывод с уравнениями LaTeX") + +*На изображении показан фрагмент сгенерированного Markdown, где уравнение `\int_{a}^{b} f(x)\,dx` обёрнуто в `$$`.* + +## Заключение + +Мы только что продемонстрировали, как **save word as markdown**, сохраняя каждое уравнение Office Math в виде нативного LaTeX. Ключевой шаг — настройка `MarkdownSaveOptions` с `OfficeMathExportMode.LATEX`, что превращает типичный конвейер Word‑в‑Markdown в полностью поддерживающий математику инструмент преобразования. + +Теперь вы можете: + +1. **How to export math** из любого `.docx` без потери точности. +2. **Convert word equations latex** для статических генераторов сайтов, документации или академических блогов. +3. Расширить подход для пакетной обработки множества файлов, интеграции с CI‑конвейерами или даже создания небольшого веб‑сервиса. + +Если вам интересна следующая граница, попробуйте сочетать это с **docx to markdown latex** для документов с большим количеством изображений, или изучите `HtmlSaveOptions` от Aspose для веб‑готовой HTML‑версии. Возможности безграничны — экспериментируйте, ломайте вещи и делитесь своими находками с сообществом. + +Есть вопросы или сложное уравнение, которое не отобразилось как ожидалось? Оставьте комментарий ниже, и счастливого кодинга! + +## Похожие руководства + +- [Как экспортировать LaTeX из Word: преобразовать DOCX в Markdown и сохранить как PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Преобразовать docx в markdown – экспортировать математические уравнения в LaTeX с помощью Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Как конвертировать Word в PDF с помощью Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/russian/java/document-loading-and-saving/_index.md index dff5de4d1d..f6f8ec8cdd 100644 --- a/words/russian/java/document-loading-and-saving/_index.md +++ b/words/russian/java/document-loading-and-saving/_index.md @@ -133,6 +133,9 @@ Aspose.Words for Java упрощает **save images from Word** докумен ### [Восстановление повреждённого docx – Полное руководство по исправлению и обработке документов](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) Узнайте, как восстановить повреждённые файлы docx, исправить ошибки и продолжить обработку документов с помощью Aspose.Words for Java. +### [Открытие повреждённого Word‑документа – установка режима восстановления в Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Узнайте, как открыть повреждённый документ Word, установить режим восстановления и обработать его с помощью Aspose.Words for Java. + ### [Захват предупреждений о замене шрифтов в Java с Aspose.Words – Полное руководство](./capture-font-substitution-warnings-in-java-with-aspose-words/) Узнайте, как перехватывать и обрабатывать предупреждения о замене шрифтов при работе с документами в Java с помощью Aspose.Words. diff --git a/words/russian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/russian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..4f406aa1bb --- /dev/null +++ b/words/russian/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Откройте повреждённый документ Word в Java с помощью Aspose.Words. Узнайте, + как установить режим восстановления и надёжно восстанавливать повреждённые файлы + Word. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: ru +og_description: Откройте повреждённый документ Word в Java с помощью Aspose.Words. + Это руководство показывает, как включить режим восстановления и эффективно восстанавливать + повреждённые файлы Word. +og_title: Открыть повреждённый документ Word – установить режим восстановления в Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Открыть повреждённый документ Word – установить режим восстановления в Java +url: /ru/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Открытие повреждённого документа Word – Установка режима восстановления в Java + +Когда‑либо пытались открыть повреждённый документ Word и видели, как программа падает с исключением? Вы не одиноки — такие сломанные .docx файлы могут стать настоящей головной болью. Хорошая новость в том, что Aspose.Words for Java предоставляет детальный контроль, позволяя **открыть повреждённый документ Word** без краха приложения, а также решать, хотите ли вы предупреждения, тихое восстановление или жёсткое отклонение. + +В этом руководстве мы пройдём полный процесс: от создания правильного `LoadOptions`, до выбора соответствующего значения **set recovery mode**, и, наконец, подтверждения, что документ действительно загружен. К концу вы узнаете **как восстановить повреждённый файл Word** программно, без необходимости ручного копирования‑вставки. + +> **Что понадобится** +> * Java 8 или новее (API работает и с Java 11) +> * Aspose.Words for Java 23.9 (или последняя версия) +> * Пример повреждённого .docx файла — просто переименуйте любой корректный файл, чтобы имитировать повреждение, если у вас нет готового образца + +Давайте начнём. + +## Открытие повреждённого документа Word – пошаговый обзор + +Ниже представлена общая схема, которую мы реализуем: + +1. **Create `LoadOptions`** – этот объект сообщает Aspose.Words, как себя вести при возникновении проблем. +2. **Set recovery mode** – выберите `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` или `REJECT_CORRUPTED`. +3. **Load the document** используя настроенные параметры. +4. **Verify** успешность загрузки (например, вывести количество страниц). + +Каждый шаг подробно объяснён ниже, с фрагментами кода, которые можно сразу скопировать в свою IDE. + +## Установка режима восстановления для разных сценариев + +Aspose.Words определяет три стратегии восстановления внутри `LoadOptions.RecoveryMode`: + +| Mode | Поведение | Когда использовать | +|------|-----------|---------------------| +| `RECOVER_WITH_WARNINGS` | Пытается загрузить документ, но выводит любые проблемы в виде предупреждений в консоль. | Нужно увидеть *что* пошло не так, не прерывая процесс. | +| `RECOVER_WITHOUT_WARNINGS` | Тихо исправляет то, что возможно, и подавляет предупреждения. | Производственная среда, где логи должны оставаться чистыми. | +| `REJECT_CORRUPTED` | Выбрасывает исключение сразу при обнаружении повреждения. | Жёсткие конвейеры валидации, требующие мгновенного отказа. | + +Выбор правильного режима — суть корректного **set recovery mode**. В большинстве отладочных сеансов `RECOVER_WITH_WARNINGS` является оптимальным, так как точно указывает, какие части были исправлены. + +## Как восстановить повреждённый файл Word с помощью Aspose.Words + +Ниже представлен **полный, исполняемый Java‑программный пример**, демонстрирующий весь процесс. Сохраните его в файл `RecoveryModeDemo.java`, при необходимости измените путь к файлу и запустите. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Почему каждая строка важна + +* **`LoadOptions loadOptions = new LoadOptions();`** – без этого объекта Aspose.Words использует режим восстановления по умолчанию, который *отклоняет* повреждённые файлы. Создав его, вы получаете возможность изменить поведение. +* **`setRecoveryMode(...)`** – это вызов **set recovery mode**, определяющий, будут ли выводиться предупреждения, скрываться или приводить к исключению. +* **`new Document(path, loadOptions);`** – конструктор принимает только что настроенный `LoadOptions`, поэтому библиотека сразу знает, как обращаться с повреждённым файлом. +* **`doc.getPageCount()`** – быстрая проверка. Если документ загружается и возвращает количество страниц, вы успешно **как восстановить повреждённый файл Word**. +* **`doc.save(...)`** – опционально, но удобно; можно записать исправленную версию обратно на диск для последующего использования. + +## Обработка распространённых граничных случаев + +### 1. Файл не найден + +Если путь указан неверно, `Document` бросает `FileNotFoundException`. Оберните загрузку в блок try‑catch и выведите дружелюбное сообщение: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Невосстановимая порча + +Даже с `RECOVER_WITH_WARNINGS` некоторые структуры могут быть безнадёжно повреждены. В этом случае Aspose.Words всё равно загрузит то, что возможно, но вы увидите предупреждения вроде «Cannot read paragraph properties». Обращайте внимание на вывод консоли; такие предупреждения часто указывают на отсутствующие секции, которые придётся восстанавливать вручную. + +### 3. Большие файлы и производительность + +Восстановление добавляет небольшие накладные расходы, поскольку библиотека парсит файл дважды — сначала для обнаружения проблем, затем для их исправления. Для многогигабайтных документов рассмотрите возможность потоковой обработки файла или увеличьте размер кучи JVM (`-Xmx2g`), чтобы избежать `OutOfMemoryError`. + +## Профессиональные советы — как сделать восстановление надёжным + +* **Log warnings to a file** – перенаправьте `System.err` в логгер, чтобы иметь аудиторский след того, что было исправлено. +* **Validate after recovery** – выполните `doc.updatePageLayout();` и затем повторно проверьте количество страниц; иногда макет меняется после исправления сломанных секций. +* **Automate batch recovery** – оберните демонстрацию в цикл, обрабатывающий папку с повреждёнными файлами, используя один и тот же `LoadOptions` каждый раз. + +## Заключение + +Теперь вы точно знаете **как восстановить повреждённый файл Word** с помощью Aspose.Words for Java. Создав экземпляр `LoadOptions`, **set recovery mode** в стратегию, соответствующую вашему сценарию, и загрузив документ с этими параметрами, вы сможете безопасно **открыть повреждённый документ Word** без сбоев приложения. Приведённый выше пример кода — полностью готовое решение, которое выводит количество страниц и даже сохраняет очищенную копию. + +Что дальше? Попробуйте переключить режим восстановления на `RECOVER_WITHOUT_WARNINGS` и сравните вывод консоли, либо поэкспериментируйте с загрузкой зашифрованных документов (вам понадобится передать пароль через + +## Связанные руководства + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/russian/java/document-styling/_index.md index cc2ad0d2eb..623040f6c1 100644 --- a/words/russian/java/document-styling/_index.md +++ b/words/russian/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aspose.Words for Java предоставляет мощные инструмен Узнайте, как применять водяные знаки и настраивать конфигурации страниц с помощью Aspose.Words для Java. Подробное руководство с исходным кодом. ### [Оформление верхнего и нижнего колонтитула документа](./document-header-footer-styling/) Узнайте, как стилизовать верхние и нижние колонтитулы документов с помощью Aspose.Words для Java в этом подробном руководстве. Пошаговые инструкции и исходный код включены. +### [Установка настроек шрифта по умолчанию в Aspose.Words для Java – Полное руководство](./set-default-font-settings-in-aspose-words-for-java-complete/) +Узнайте, как установить настройки шрифта по умолчанию в Aspose.Words для Java. Пошаговое руководство с примерами кода. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/russian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..edca373716 --- /dev/null +++ b/words/russian/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: Установите настройки шрифта по умолчанию в Aspose.Words для Java и узнайте, + как задать параметры шрифта и обнаружить отсутствующие шрифты всего в несколько + строк кода. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: ru +og_description: Установите настройки шрифта по умолчанию в Aspose.Words для Java, + научитесь задавать параметры шрифта и быстро и надёжно обнаруживать отсутствующие + шрифты. +og_title: Установить настройки шрифта по умолчанию в Aspose.Words для Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Установите настройки шрифта по умолчанию в Aspose.Words для Java – полное руководство +url: /ru/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Установить настройки шрифта по умолчанию в Aspose.Words for Java – Полное руководство + +Когда‑нибудь задумывались, как **установить настройки шрифта по умолчанию** при загрузке Word‑документа с помощью Aspose.Words for Java? Вы не одиноки. Отсутствующие глифы могут превратить аккуратный отчёт в набор нечитаемых символов, а раннее обнаружение предупреждений о замене шрифтов экономит часы отладки. + +В этом руководстве мы пройдём через лаконичный, сквозной пример, который **устанавливает настройки шрифта по умолчанию**, показывает, как **программно задать настройки шрифта**, и демонстрирует надёжный способ **обнаружения отсутствующих шрифтов** до того, как они испортят макет. + +--- + +## Что вы узнаете + +- Как создать объект `LoadOptions` с новым экземпляром `FontSettings`. +- Как прикрепить слушатель предупреждений, который **обнаружит отсутствующие шрифты** во время загрузки документа. +- Как загрузить файл DOCX, при этом слушатель тихо сообщает о любых заменах. +- Советы по настройке резервных шрифтов и обработке граничных случаев в продакшене. + +Никаких дополнительных библиотек, никаких скрытых конфигурационных файлов — только чистый Java и Aspose.Words. + +--- + +## Требования + +Прежде чем приступить, убедитесь, что у вас есть: + +1. **Aspose.Words for Java** (версия 23.10 или новее) в classpath. +2. JDK 17 (или новее) — любой современный JDK подойдёт. +3. Файл DOCX, в котором намеренно используется шрифт, которого у вас нет (например, *“MissingFont.ttf”*). + +Если у вас нет JAR‑файла Aspose, скачайте его из официального Maven‑репозитория: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Вот и всё — для этой демонстрации не требуется устанавливать дополнительные шрифты. + +--- + +## Шаг 1: Создать LoadOptions и **установить настройки шрифта по умолчанию** + +Первое, что нам нужно, — чистый объект `LoadOptions`, который указывает Aspose, как вести себя при встрече с неизвестными гарнитурами. Вызвав `setFontSettings(new FontSettings())`, мы **устанавливаем настройки шрифта по умолчанию**, начинающиеся с пустого списка резервных шрифтов. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Почему это важно:** +> Если явно не задавать шрифты, Aspose использует системную коллекцию по умолчанию, что может скрыть проблемы с отсутствующими шрифтами. Начав с нового экземпляра `FontSettings`, вы получаете полный контроль над тем, какие шрифты считаются допустимыми. + +--- + +## Шаг 2: Прикрепить слушатель предупреждений для **обнаружения отсутствующих шрифтов** + +Aspose генерирует объект `WarningInfo` для каждой выполненной замены. Слушая `WarningType.FONT_SUBSTITUTION`, мы можем **обнаружить отсутствующие шрифты** сразу после парсинга документа. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Совет:** Слушатель работает в том же потоке, что и загрузка документа, поэтому практически нет потерь в производительности. Если нужно собрать предупреждения для последующего анализа, сохраняйте их в `List` вместо прямого вывода. + +--- + +## Шаг 3: Загрузить документ с использованием настроенных параметров + +Теперь, когда мы **установили настройки шрифта** и подготовили слушатель, просто загружаем файл. Любой отсутствующий шрифт мгновенно вызывает наш колбэк. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Если исходный файл ссылается на шрифт, которого нет в системе, вы увидите вывод, похожий на: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Эта строка точно указывает, какой шрифт отсутствовал и какой резервный был использован — идеально для логирования или обратной связи пользователю. + +--- + +## Шаг 4: Продолжить обычную обработку (по желанию) + +На данном этапе документ полностью загружен, и вы можете выполнять любые операции — редактировать, конвертировать в PDF или извлекать текст. Слушатель предупреждений уже выполнил свою работу, так что дополнительные проверки не нужны. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Что если нужен собственный резервный шрифт?** +> Вместо пустого `FontSettings` можно добавить конкретные шрифты: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Теперь любой отсутствующий шрифт будет заменён на *Times New Roman* — надёжный выбор для большинства западных документов. + +--- + +## Визуальный обзор + +![Диаграмма, показывающая, как установить настройки шрифта по умолчанию в Aspose.Words for Java](image.png "Диаграмма потока установки настроек шрифта по умолчанию") + +*Alt text: flowchart установки настроек шрифта по умолчанию в Aspose.Words for Java.* + +Диаграмма иллюстрирует процесс от инициализации `LoadOptions` (где мы **устанавливаем настройки шрифта по умолчанию**) до прикрепления слушателя предупреждений (для **обнаружения отсутствующих шрифтов**) и, наконец, загрузки документа. + +--- + +## Распространённые ошибки и как их избежать + +| Ошибка | Почему происходит | Как исправить | +|--------|-------------------|---------------| +| **Не вызван `setFontSettings`** | Aspose использует системные настройки, скрывая отсутствующие шрифты. | Всегда создавайте новый экземпляр `FontSettings` и присваивайте его `LoadOptions`. | +| **Слушатель не срабатывает** | Слушатель добавлен после загрузки документа. | Добавляйте слушатель **до** вызова `new Document(...)`. | +| **Опечатка в пути → `FileNotFoundException`** | Жёстко заданный путь не совпадает с регистром файловой системы. | Используйте `Paths.get("...").toAbsolutePath()` или задавайте относительный путь от корня проекта. | +| **Множественные отсутствующие шрифты заполняют логи** | Большие документы могут генерировать десятки предупреждений. | Фильтруйте дубликаты или агрегируйте сообщения в `Set` перед выводом. | + +--- + +## Расширение решения + +Если нужно **установить настройки шрифта** для всего приложения, рассмотрите создание синглтона `FontSettings` и его повторное использование во всех `LoadOptions`. Так вы сохраняете единый подход к резервным шрифтам и избегаете лишних созданий объектов. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Теперь любой участок кода может просто вызвать `FontConfig.getLoadOptions()` и сразу получить ту же логику **установки настроек шрифта по умолчанию**. + +--- + +## Заключение + +Мы рассмотрели всё, что необходимо для **установки настроек шрифта по умолчанию** в Aspose.Words for Java, **программного задания настроек шрифта** и **обнаружения отсутствующих шрифтов** до того, как они испортят вывод. Полный, готовый к запуску пример находится в приведённых выше фрагментах кода, и вы можете вставить его в свою IDE, чтобы увидеть предупреждения в действии. + +Что дальше? Попробуйте заменить резервный шрифт, поэкспериментируйте с различными форматами документов (DOC, RTF, HTML) или интегрируйте сборщик предупреждений в панель мониторинга. Чем больше вы играете с `FontSettings`, тем увереннее будете в том, что генерируемые документы выглядят точно так, как задумано — без сюрпризов и сломанных глифов. + +Есть вопросы или сложный сценарий замены шрифтов? Оставляйте комментарий ниже, и удачной разработки! + +## Связанные руководства + +- [Set Font Fallback Settings](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/java/images-shapes/_index.md b/words/russian/java/images-shapes/_index.md index 7867e5dfa2..3750f52013 100644 --- a/words/russian/java/images-shapes/_index.md +++ b/words/russian/java/images-shapes/_index.md @@ -37,6 +37,9 @@ ### [Создание документа Word в Java – Добавление прямоугольной фигуры с эффектом тени](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Узнайте, как добавить прямоугольную форму с теневым эффектом в документ Word с помощью Aspose.Words для Java. +### [Создание прямоугольной фигуры в документе Word на Java – Полное пошаговое руководство](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Узнайте, как создать прямоугольную фигуру в документе Word с помощью Aspose.Words для Java, следуя полному пошаговому руководству. + ## Дополнительные ресурсы - [Документация Aspose.Words для Java](https://reference.aspose.com/words/java/) diff --git a/words/russian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/russian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..15216d5d8d --- /dev/null +++ b/words/russian/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-05-26 +description: Создайте прямоугольную форму в документе Word на Java и примените эффект + тени. Узнайте, как добавить тень к форме, установить расстояние тени и сохранить + файл. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: ru +og_description: Создайте прямоугольную форму в документе Word на Java, примените эффект + тени, добавьте тень к форме и задайте расстояние тени с помощью Aspose.Words. +og_title: Создание прямоугольной формы в документе Word на Java – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Создание прямоугольной фигуры в документе Word на Java – полное пошаговое руководство +url: /ru/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание прямоугольной формы в Java Word Document – Полное пошаговое руководство + +Когда‑нибудь вам нужно было **create rectangle shape** в Java Word документе, но вы не знали, с чего начать? Вы не одиноки — многие разработчики сталкиваются с этой проблемой при программной генерации отчетов или счетов. В этом руководстве мы подробно покажем, как **create rectangle shape**, применить аккуратную тень и точно настроить расстояние тени, чтобы результат выглядел профессионально. + +Мы будем использовать Aspose.Words for Java, мощную библиотеку, позволяющую манипулировать Word‑файлами без установки Microsoft Office. К концу этого руководства вы сможете создавать проекты **create word document java**, которые **add shape shadow**, **apply shadow effect** и **set shadow distance** всего несколькими строками кода. + +--- + +## Что вы создадите + +- Новый файл `.docx`, содержащий циановый прямоугольник. +- Реалистичная падающая тень, размытая, под углом и частично прозрачная. +- Полный контроль над расстоянием тени от формы. +- Готовый к запуску Java‑класс, который можно добавить в любой проект Maven или Gradle. + +Никаких внешних инструментов, никаких ручных действий в UI — только чистый код. + +--- + +## Предварительные требования + +- Java 8 или новее (код работает на Java 11, Java 17 и т.д.). +- Библиотека Aspose.Words for Java (доступна через Maven Central). +- IDE или текстовый редактор по вашему выбору (IntelliJ IDEA, Eclipse, VS Code…). +- Базовое знакомство с синтаксисом Java. + +Если вы никогда не добавляли зависимость Maven, вот быстрый фрагмент: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Теперь давайте погрузимся. + +--- + +## Шаг 1: Создание прямоугольной формы в документе Word + +Первое, что нам нужно, — пустой документ и `DocumentBuilder`. Думайте о билдере как о перье, которое пишет в документ. Как только он у нас есть, мы можем **create rectangle shape** одним вызовом метода. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Почему это важно:** Метод `insertShape` не только создает геометрию, но и добавляет форму во внутреннюю коллекцию документа, так что вы можете сразу приступить к её стилизации. + +--- + +## Шаг 2: Применение эффекта тени к форме + +Теперь, когда прямоугольник находится на странице, мы **apply shadow effect**. Тени придают глубину, заставляя форму выглядеть так, будто она поднялась над страницей — тонкое улучшение UI, которое может повысить читаемость в отчетах. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro tip:** Размытие `5.0` выглядит естественно для большинства документов, отображаемых на экране. Если вы печатаете, возможно, захотите немного уменьшить значение, чтобы избежать размытого вида. + +--- + +## Шаг 3: Установка расстояния тени – точная настройка положения + +Тени — это не только размытие; им также нужен правильный сдвиг. Здесь мы **set shadow distance**. Расстояние `7.0` пунктов создает умеренный сдвиг, заметный, но не навязчивый. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Что если мне нужен больший сдвиг?** Увеличьте значение; уменьшите его для более плотного вида. Помните, расстояние работает вместе с углом, чтобы правильно позиционировать тень. + +--- + +## Шаг 4: Сохранение документа – сохранение вашей работы + +Наконец, мы записываем документ на диск. Измените путь на тот, где вы хотите хранить файл. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Запуск класса создаёт файл `shadow.docx`, который при открытии в Microsoft Word или LibreOffice показывает циановый прямоугольник с мягкой серой тенью, наклонённой под 45° и сдвинутой на 7 пунктов. + +--- + +## Полный рабочий пример + +Ниже приведён полностью готовый к копированию код. Он включает все импорты, комментарии и финальный вызов `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Ожидаемый результат:** Откройте `shadow.docx` → вы увидите циановый прямоугольник, центрированный на первой странице, отбрасывающий лёгкую серую тень, слегка смещённую вниз‑вправо. Размытие и прозрачность тени делают её похожей на естественное освещение. + +--- + +## Часто задаваемые вопросы и особые случаи + +### «Могу ли я использовать другую форму?» + +Абсолютно. Замените `ShapeType.RECTANGLE` на `ShapeType.OVAL`, `ShapeType.LINE` или любой другой поддерживаемый enum. Остальной код тени остаётся без изменений. + +### «Что если мне нужны несколько теней?» + +Aspose.Words поддерживает только одну тень на форму. Чтобы имитировать несколько теней, продублируйте форму, сдвиньте каждую копию и отрегулируйте прозрачность. + +### «Видна ли тень в LibreOffice?» + +Да — Aspose.Words записывает стандартный OOXML, который LibreOffice корректно интерпретирует. Тень может выглядеть немного иначе из‑за разных движков рендеринга, но эффект сохраняется. + +### «Как изменить цвет тени, чтобы он соответствовал моему бренду?» + +Просто замените `java.awt.Color.GRAY` на любой `java.awt.Color`, который вам нужен, например `new java.awt.Color(0, 120, 215)` для корпоративного синего. + +--- + +## Иллюстрация + +![create rectangle shape in Java Word document](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** иллюстрация, показывающая циановый прямоугольник с серой падающей тенью в документе Word. + +--- + +## Итоги и дальнейшие шаги + +Мы рассмотрели, как **create rectangle shape**, **apply shadow effect**, **add shape shadow** и **set shadow distance** с помощью Aspose.Words for Java. Код автономный, работает на любой современной JDK и создаёт полированный файл `.docx`, готовый к распространению. + +Хотите пойти дальше? Попробуйте: + +- Добавить текст внутри прямоугольника с помощью `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Создать таблицу форм для построения диаграммы. +- Экспортировать документ в PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Каждое из этих действий опирается на те же основы, которые мы только что изучили, так что вы будете чувствовать себя уверенно, расширяя пример. + +--- + +## Заключительные мысли + +Освоив задачи **create word document java**, такие как формирование и затенение, вы получаете огромное преимущество при автоматизации отчетов, контрактов или маркетинговых материалов. Подход, показанный здесь, чистый, поддерживаемый и — что самое важное — легко настраиваемый под любой визуальный стиль, который вам нужен. + +Запустите код, поиграйте с размытием, углом и расстоянием, и наблюдайте, как ваши документы превращаются из скучных в полированные. Если столкнётесь с проблемой, оставьте комментарий ниже; я с радостью помогу. + +Удачной разработки! + +## Похожие руководства + +- [Создать документ Word на Java – Добавить прямоугольную форму с эффектом тени](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Как создать поля формы и добавить содержимое с помощью DocumentBuilder в Aspose.Words для Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Создать PDF из Word с генерацией штрихкода – Aspose.Words для Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/spanish/java/document-conversion-and-export/_index.md index 18209156cf..8c8f638ca8 100644 --- a/words/spanish/java/document-conversion-and-export/_index.md +++ b/words/spanish/java/document-conversion-and-export/_index.md @@ -92,15 +92,24 @@ Aprende a formatear tablas y aplicar estilos de tabla en Aspose.Words for Java. ### [Convertir docx a markdown – Exportar ecuaciones matemáticas a LaTeX con Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Aprenda a convertir documentos DOCX a Markdown y exportar ecuaciones matemáticas a LaTeX usando Aspose.Words. +### [Guardar Word como markdown – Exportar ecuaciones a LaTeX con Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Aprende a guardar documentos Word en formato markdown y exportar ecuaciones matemáticas a LaTeX usando Aspose.Words for Java. + ### [Guardar documento como TXT – Guía rápida para exportar ecuaciones de Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Aprenda a guardar documentos Word como archivos TXT y exportar ecuaciones matemáticas manteniendo el formato. +### [Exportar docx a txt con Java – Guía completa de programación](./export-docx-to-txt-with-java-complete-programming-guide/) +Aprenda a exportar documentos DOCX a archivos TXT usando Aspose.Words for Java con esta guía paso a paso. + ### [Aspose.Words a PDF – Convertir DOCX a PDF en Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Aprenda a convertir archivos DOCX a PDF usando Aspose.Words for Java en unos simples pasos. ### [Cómo incrustar imágenes en Markdown al convertir DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Aprenda a insertar imágenes en archivos markdown durante la conversión de documentos DOCX con Aspose.Words. +### [Incrustar imágenes como Base64 al convertir DOCX a Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Aprende a incrustar imágenes en formato Base64 durante la conversión de DOCX a Markdown usando Aspose.Words for Java. + ### [Cómo exportar LaTeX desde Word: convertir DOCX a Markdown y guardar como PDF](./how-to-export-latex-from-word-convert-docx-to-markdown-save/) Aprenda a convertir documentos Word a LaTeX mediante Markdown y generar un PDF final. @@ -119,6 +128,12 @@ Aprenda a generar PDFs accesibles conforme a PDF/UA a partir de documentos Word ### [Crear PDF accesible desde DOCX – Guía completa](./create-accessible-pdf-from-docx-complete-guide/) Aprenda a generar PDFs accesibles a partir de documentos DOCX cumpliendo con los estándares PDF/UA. +### [Guardar documento como PDF con Aspose.Words Java – Guía completa de accesibilidad](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Aprenda a guardar documentos como PDF accesibles cumpliendo con PDF/UA usando Aspose.Words for Java. + +### [Crear PDF accesible en Java – Guía completa de etiquetado](./create-accessible-pdf-in-java-full-tagging-guide/) +Aprende a generar PDFs accesibles con etiquetado completo en Java usando Aspose.Words, cumpliendo con los estándares PDF/UA. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} diff --git a/words/spanish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/spanish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..435e30f9f9 --- /dev/null +++ b/words/spanish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-05-26 +description: Crea PDF accesible en Java con código paso a paso. Aprende cómo etiquetar + PDF para accesibilidad y habilitar el etiquetado de PDF usando PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: es +og_description: Crea PDF accesible en Java con código paso a paso. Aprende cómo etiquetar + PDF para accesibilidad y habilitar el etiquetado de PDF usando PdfSaveOptions. +og_title: Crear PDF accesible en Java – Guía completa de etiquetado +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Crear PDF accesible en Java – Guía completa de etiquetado +url: /es/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear PDF accesible en Java – Guía completa de etiquetado + +¿Alguna vez te has preguntado cómo **crear PDF accesibles** directamente desde código Java? No estás solo. Muchos desarrolladores necesitan atender a usuarios que dependen de lectores de pantalla, y la diferencia entre un PDF simple y uno accesible puede ser enorme. En este tutorial recorreremos **cómo etiquetar PDF para accesibilidad**, te mostraremos **cómo crear PDF etiquetados** con Aspose PDF for Java, y revelaremos los pasos exactos para **añadir etiquetas de accesibilidad a PDF** para que cada lector pueda obtener la misma información. + +También cubriremos las mejores prácticas para **habilitar el etiquetado de PDF**, errores comunes y un ejemplo completo y ejecutable que puedes incorporar a tu proyecto hoy. Sin referencias vagas—solo código concreto, explicaciones y un archivo final que puedes abrir en Adobe Acrobat para verificar las etiquetas. + +## Qué aprenderás + +- El porqué del etiquetado de PDF y el cumplimiento de accesibilidad. +- Requisitos previos y configuración de la biblioteca (Aspose PDF for Java 23.10 o posterior). +- Cómo **crear PDF accesibles** desde cero, paso a paso. +- Formas de **añadir etiquetas de accesibilidad a PDF** más allá de la llamada básica `setTagDocumentStructure`. +- Consejos para probar el resultado y solucionar problemas comunes. + +Al final de esta guía podrás generar PDFs que superen las verificaciones WCAG 2.1 AA y que además tengan un aspecto profesional. + +--- + +## Requisitos previos + +Antes de profundizar, asegúrate de tener: + +| Requisito | Razón | +|-------------|--------| +| **Java 8+** | Funciones modernas del lenguaje y mejor manejo de Unicode. | +| **Aspose PDF for Java** (v23.10 o newer) | Proporciona la clase `PdfSaveOptions` y soporte de etiquetado. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | Para una compilación y depuración fáciles. | +| **Write permission** to a folder where the PDF will be saved | La llamada `doc.save` necesita una ruta con permisos de escritura. | + +Si aún no has añadido Aspose PDF a tu proyecto, inserta la siguiente dependencia Maven en tu `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Consejo profesional:** Usa la última versión; las versiones más recientes mejoran la precisión del etiquetado y añaden funciones de accesibilidad específicas por idioma. + +--- + +## Paso 1: Configurar el esqueleto del documento + +Primero, creamos un nuevo objeto `Document`. Piensa en él como un lienzo en blanco que más adelante contendrá las etiquetas que necesitamos para la accesibilidad. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Por qué es importante:** Sin contenido, no hay nada que etiquetar. Añadir incluso un simple `TextFragment` le da al motor de etiquetado algo con lo que trabajar, y crea automáticamente una etiqueta `

` (párrafo) cuando más adelante habilitamos el etiquetado de estructura. + +--- + +## Paso 2: Crear opciones de guardado de PDF (el núcleo del etiquetado) + +Ahora preparamos las opciones que indican a Aspose PDF que incruste un árbol de estructura lógica dentro del archivo. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +La llamada a `setTagDocumentStructure(true)` es el interruptor para **habilitar el etiquetado de PDF**. Cuando es true, la biblioteca construye un árbol de etiquetas que refleja el diseño visual, haciendo que el PDF sea legible por tecnologías de asistencia. + +> **Nota:** Esta es la forma más sencilla de **cómo crear PDF etiquetado**. Para un control más granular (p. ej., establecer el idioma o etiquetas personalizadas), puedes explorar `pdfOptions.setTagLanguage("en-US")` y `pdfOptions.setTagStructureTreeRoot(...)`. + +--- + +## Paso 3: Guardar el PDF accesible + +Finalmente, escribimos el documento en disco usando las opciones que acabamos de configurar. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Cuando `doc.save` finaliza, encontrarás `accessible.pdf` en la carpeta `output`. Ábrelo en Adobe Acrobat y revisa **Archivo → Propiedades → Descripción → Etiquetas** – deberías ver un árbol de etiquetas poblado. + +--- + +## Cómo etiquetar PDF para accesibilidad – Más allá de lo básico + +El fragmento de tres pasos anterior ya **añade etiquetas de accesibilidad a PDF**, pero los documentos del mundo real a menudo necesitan un poco más de pulido. Aquí tienes algunas mejoras que puedes aplicar: + +### 1. Establecer el idioma del documento + +Los lectores de pantalla usan el atributo de idioma para pronunciar el texto correctamente. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Proporcionar un título y asunto + +Los metadatos ayudan a las herramientas de asistencia a ofrecer contexto antes de que el usuario abra el archivo. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Etiquetar imágenes con texto alternativo + +Si incrustas imágenes, necesitan descripciones `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Marcar encabezados de tabla + +Las tablas son notorias por confundir a los lectores a menos que marques las filas de encabezado. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Estos pasos adicionales hacen que tu PDF no solo esté *técnicamente* etiquetado, sino verdaderamente **accesible** para una audiencia diversa. + +--- + +## Problemas comunes al habilitar el etiquetado de PDF + +| Síntoma | Causa probable | Solución | +|---------|----------------|----------| +| Etiquetas ausentes en Acrobat | `setTagDocumentStructure` dejado como `false` | Asegúrate de llamar a `pdfOptions.setTagDocumentStructure(true)`. | +| Orden de lectura incorrecto | Diseño complejo sin etiquetas explícitas | Usa `pdfOptions.setTagStructureTreeRoot(...)` para definir un orden personalizado. | +| Imágenes leídas como “imagen” sin descripción | No se ha establecido texto alternativo | Llama a `image.getAlternativeText().setValue("...")`. | +| Idioma no reconocido | `setTagLanguage` omitido o locale incorrecto | Proporciona un código de idioma BCP‑47 (`en-US`, `fr-FR`). | + +Ser consciente de estos problemas te ahorra horas de depuración más adelante. + +--- + +## Verificar el resultado – Qué esperar + +Después de ejecutar el programa, abre `output/accessible.pdf` en Adobe Acrobat Reader: + +1. **Panel de etiquetas** (`View → Show/Hide → Navigation Panes → Tags`) debería listar una jerarquía como `/Document → /Part → /Sect → /Para`. +2. **Orden de lectura** debería seguir el flujo visual (texto primero, luego imágenes). +3. **Lector de pantalla** (NVDA, VoiceOver) leerá “Hello, accessible PDF!” en lugar de solo “Page 1”. + +Si falta alguno de esos elementos, revisa nuevamente los pasos anteriores—especialmente la llamada `setTagDocumentStructure`. + +--- + +## Ejemplo completo funcional (listo para copiar y pegar) + + + +## Tutoriales relacionados + +- [Crear PDF accesible desde Word – Convertir a PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Crear PDF accesible desde DOCX – Guía completa](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Cómo guardar documento como PDF con Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/spanish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/spanish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..cea7011bc2 --- /dev/null +++ b/words/spanish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-26 +description: Incrusta imágenes como base64 mientras conviertes docx a markdown con + Aspose.Words para Java. Aprende a convertir Word a markdown, guardar Word como markdown + y manejar imágenes. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: es +og_description: Incrusta imágenes como base64 al convertir docx a markdown con Aspose.Words + para Java. Guía completa para convertir Word a markdown y guardar Word como markdown. +og_title: Incrustar imágenes como Base64 al convertir DOCX a Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Incrustar imágenes como Base64 al convertir DOCX a Markdown +url: /es/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Incrustar imágenes como Base64 al convertir DOCX a Markdown + +¿Alguna vez te has preguntado cómo **incrustar imágenes como base64** mientras **conviertes docx a markdown**? No eres el único: los desarrolladores preguntan constantemente cómo mantener las imágenes en línea sin manejar archivos separados. La buena noticia es que Aspose.Words for Java lo hace muy fácil: puedes convertir un documento Word a Markdown e incrustar automáticamente cada imagen como una cadena Base64. + +En este tutorial recorreremos todo el proceso—desde cargar un `.docx` que contiene imágenes, hasta configurar una devolución de llamada `MarkdownSaveOptions` que hace el trabajo pesado, y finalmente guardar el resultado como un archivo `.md` limpio. Al final sabrás exactamente cómo **convertir word a markdown**, **convertir imágenes a base64**, y **guardar word como markdown** sin dejar carpetas de imágenes sueltas. Sin herramientas externas, sin procesamiento manual posterior—solo código Java puro que puedes incorporar en cualquier proyecto. + +## Lo que necesitarás + +- **Java 17** (o cualquier JDK reciente) – el código usa sintaxis lambda, pero puedes adaptarlo a versiones anteriores. +- Biblioteca **Aspose.Words for Java** (última versión a partir de 2026). Añade la dependencia Maven o el JAR a tu classpath. +- Un archivo **DOCX** de ejemplo que contenga al menos una imagen. +- Un IDE o un editor de texto sencillo—Visual Studio Code, IntelliJ IDEA, o incluso `vim` servirán. + +Si ya tienes todo esto, genial—vamos directo al grano. + +## Paso 1: Cargar el documento Word + +Primero creamos una instancia de `Document` que apunta al archivo fuente. Este paso es el mismo tanto si **conviertes docx a markdown** como si solo lees el archivo para otros propósitos. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Por qué es importante:** El objeto `Document` es el punto de entrada para cada operación de Aspose. Contiene toda la estructura de Word—incluidas imágenes, tablas y estilos—para que la devolución de llamada posterior pueda inspeccionar cada recurso. + +## Paso 2: Crear MarkdownSaveOptions y registrar una devolución de llamada de guardado de recursos + +La magia está en `MarkdownSaveOptions`. Al adjuntar un `IResourceSavingCallback` obtenemos control sobre cómo se escribe cada recurso externo (como una imagen). + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: ¿Por qué usar `setSaveToMemory(true)`? + +Cuando `saveToMemory` es true, Aspose escribe los bytes de la imagen en un flujo de memoria en lugar de un archivo. El exportador de Markdown luego convierte ese flujo a una cadena Base64 y la inserta directamente en la etiqueta de imagen Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Eso es el núcleo de **incrustar imágenes como base64**. + +## Paso 3: Guardar el documento como Markdown + +Ahora que la devolución de llamada está configurada, el paso final es simplemente llamar a `save`. Aquí es donde realmente **convertimos word a markdown** y, gracias a la devolución de llamada, también **convertimos imágenes a base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Resultado:** `out.md` contiene texto Markdown con cada imagen representada como un URI `data:`. No se crean archivos de imagen adicionales en disco, por lo que la carpeta permanece ordenada. + +## Paso 4: Verificar la salida y errores comunes + +Abre el `out.md` generado en cualquier visor de Markdown (VS Code, GitHub o un generador de sitios estáticos). Deberías ver algo como: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Lista de verificación para solución de problemas + +| Problema | Causa probable | Solución | +|----------|----------------|----------| +| La imagen aparece como enlace roto | No se incluyó `setSaveToMemory` | Asegúrate de que `args.setSaveToMemory(true);` esté dentro de la devolución de llamada | +| La cadena Base64 está truncada | Incompatibilidad de codificación del archivo de salida | Guarda el Markdown usando UTF‑8 (predeterminado en Aspose) | +| Nombres de archivo inesperados | `setKeepResourceOriginalName(true)` | Déjalo en `false` para forzar la lógica de nombrado personalizada | + +## Paso 5: Variaciones avanzadas (Opcional) + +### Convertir solo imágenes seleccionadas + +Si solo deseas incrustar ciertas imágenes (por ejemplo, las que superen los 100 KB), añade una comprobación de tamaño: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Usar un formato de imagen diferente + +`ResourceSavingArgs` te proporciona los bytes sin procesar, por lo que puedes volver a codificar JPEGs como PNGs antes de incrustarlos—útil cuando el consumidor de Markdown prefiere PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Estas adaptaciones demuestran cuán flexible es el enfoque de **incrustar imágenes como base64** cuando **conviertes docx a markdown**. + +## Conclusión + +Acabas de aprender cómo **incrustar imágenes como base64** mientras **conviertes docx a markdown** usando Aspose.Words for Java. Al conectar una sencilla `IResourceSavingCallback`, la biblioteca realiza todo el trabajo pesado: **convertir word a markdown**, **convertir imágenes a base64**, y finalmente **guardar word como markdown** con una única llamada a `save`. + +Siéntete libre de experimentar—prueba diferentes reglas de filtrado de imágenes, cambia a salida HTML, o encadena este paso con un generador de sitios estáticos. El mismo patrón funciona para otros formatos (HTML, EPUB) también, de modo que puedes reutilizar la devolución de llamada donde necesites recursos en línea. + +**Próximos pasos:** +- Explora `HtmlSaveOptions` para HTML con imágenes Base64. +- Combínalo con una canalización CI para automatizar la generación de documentación. +- Sumérgete en `DocumentVisitor` de Aspose si necesitas un control aún más fino del proceso de conversión. + +¡Feliz codificación y disfruta de tus archivos Markdown limpios y autocontenidos! + +## Tutoriales relacionados + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/spanish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..31604c5e32 --- /dev/null +++ b/words/spanish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-05-26 +description: Exportar docx a txt usando Java y Aspose.Words. Aprende cómo convertir + docx a texto, preservar Unicode y exportar Word como txt en unos pocos pasos. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: es +og_description: Exportar docx a txt en Java. Este tutorial muestra cómo convertir + docx a texto, mantener texto plano Unicode y exportar Word como txt de manera eficiente. +og_title: Exportar docx a txt con Java – Guía completa +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Exportar docx a txt con Java – Guía completa de programación +url: /es/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exportar docx a txt con Java – Guía completa de programación + +¿Alguna vez necesitaste **exportar docx a txt** pero temías perder caracteres especiales? No eres el único. Cuando conviertes documentos de Word a archivos de texto plano, los símbolos Unicode, las tablas e incluso el formato simple pueden desaparecer como por arte de magia. + +En esta guía recorreremos una forma fiable de **exportar docx a txt** usando Aspose.Words para Java, preservando cada glifo Unicode y manteniendo legibles los diseños de tabla. Al final también sabrás cómo **convertir docx a texto**, **convertir word a texto**, e incluso **exportar word como txt** sin problemas. + +## Qué cubre este tutorial + +* Configurar Aspose.Words en un proyecto Java +* Cargar un archivo DOCX y prepararlo para la salida de texto plano +* Configurar el soporte de **plain text unicode** mediante `TxtSaveOptions` +* Trucos opcionales para mantener legibles las tablas en el archivo `.txt` resultante +* Guardar el archivo y verificar la salida + +Sin scripts externos, sin herramientas misteriosas de línea de comandos—solo código Java puro que puedes insertar en cualquier proyecto Maven o Gradle. + +> **¿Por qué importa?** Los archivos de texto plano son ligeros, amigables con el control de versiones y perfectos para la indexación de búsqueda o canalizaciones de procesamiento posteriores. Si alguna vez intentaste `cat` un archivo Word y obtuviste un galimatías, este tutorial resuelve ese problema. + +--- + +## Exportar docx a txt – Visión general + +Antes de sumergirnos en el código, aclaremos la terminología. **Exportar docx a txt** significa tomar un paquete Microsoft Word `.docx` y escribir su contenido textual en un archivo simple `.txt`. A diferencia de una conversión a PDF, una exportación a texto elimina el estilo pero puede conservar saltos de línea, marcadores de párrafo y—si lo configuras correctamente—caracteres Unicode como emojis, letras acentuadas o escrituras asiáticas. + +Aspose.Words hace esto sin complicaciones porque abstrae el formato de archivo Word y ofrece una clase `TxtSaveOptions` donde puedes dictar la codificación, el manejo de tablas y más. + +### Requisitos previos + +* Java 11 o superior (la API funciona con Java 8+, pero asumiremos un JDK reciente) +* Aspose.Words para Java JAR (disponible en Maven Central) +* Un archivo de ejemplo `unicode.docx` que contenga diversos caracteres Unicode—piensa en “こんにちは”, “😊”, y una tabla simple + +Si ya los tienes, comencemos. + +--- + +## Paso 1: Cargar el archivo DOCX (Convertir docx a texto) + +Lo primero que debes hacer es leer el documento fuente en memoria. Aquí es donde oficialmente comienza el proceso de **convertir docx a texto**. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Por qué es importante:* `Document` es la representación de Aspose.Words de un archivo Word. Al cargarlo, obtienes acceso a todos sus párrafos, tablas e incluso elementos ocultos. Si el archivo no se encuentra, Aspose lanza una clara `FileNotFoundException`, por lo que sabrás inmediatamente qué salió mal. + +## Paso 2: Configurar TxtSaveOptions para Unicode (Texto plano Unicode) + +Los archivos de texto plano son solo flujos de bytes, por lo que debes indicar a Java qué conjunto de caracteres usar. UTF‑8 es el estándar de facto para **texto plano Unicode** porque puede codificar cada punto de código Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Consejo profesional:** Si omites la llamada a `setEncoding`, Aspose usa por defecto la codificación predeterminada de la plataforma, que en muchas máquinas Windows es Windows‑1252. Ese valor predeterminado eliminará silenciosamente caracteres como “ß” o “—”. + +## Paso 3: Preservar el diseño de tabla (Opcional, pero útil para la legibilidad) + +Cuando **exportas word como txt**, las tablas suelen aplanarse en una sola línea de texto, haciéndolas ilegibles. Aspose.Words ofrece una bandera simple para mantener la estructura visual. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Cuándo usarlo:* Si tu DOCX fuente contiene facturas, horarios o cualquier dato tipo cuadrícula, habilitar `PreserveTableLayout` insertará tabulaciones y saltos de línea para que el archivo resultante aún se asemeje a una tabla. Si no lo necesitas, puedes omitir la línea y obtener una salida más compacta. + +## Paso 4: Guardar el documento como texto plano (Exportar word como txt) + +Ahora el trabajo pesado está hecho—solo escribe los bytes en disco. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Ejecutar el programa genera `plain.txt` en la misma carpeta. Ábrelo con cualquier editor de texto (Notepad++, VS Code, incluso `cat` en una terminal) y verás: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Observa cómo el saludo japonés y el emoticón sobrevivieron, y la tabla mantuvo sus columnas gracias a `PreserveTableLayout`. Esa es la esencia de una **exportación docx a txt** limpia. + +## Paso 5: Verificar la salida (Comprobación de sanidad al convertir word a texto) + +Una rápida comprobación de sanidad previene la pérdida silenciosa de datos. Aquí hay algunas formas de confirmar que realmente **conviertes word a texto** correctamente: + +1. **Comparación de checksum** – calcula un hash SHA‑256 del archivo `.txt` antes y después de una conversión de ida y vuelta (txt → docx → txt) para asegurar la estabilidad. +2. **Buscar marcadores Unicode** – usa `grep` o la búsqueda en archivos del IDE para localizar caracteres como “😊”. +3. **Abrir en varios editores** – algunas versiones antiguas de Notepad de Windows aún interpretan mal UTF‑8 sin BOM; abrir el archivo en VS Code confirma la codificación correcta. + +Si alguna de estas comprobaciones falla, verifica nuevamente que `saveOptions.setEncoding(StandardCharsets.UTF_8)` esté presente y que tu DOCX fuente realmente contenga texto Unicode. + +## Problemas comunes y cómo evitarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **Caracteres faltantes** | La codificación predeterminada del sistema (p. ej., Windows‑1252) elimina glifos no ASCII. | Establece explícitamente UTF‑8 mediante `saveOptions.setEncoding`. | +| **Las tablas se convierten en una sola línea** | `PreserveTableLayout` quedó en su valor predeterminado `false`. | Llama a `saveOptions.setPreserveTableLayout(true)`. | +| **Archivo no encontrado** | Ruta incorrecta o permisos de lectura faltantes. | Usa rutas absolutas o `Paths.get(...)` con manejo de excepciones adecuado. | +| **Ralentización del rendimiento en documentos enormes** | Cargar todo el documento en memoria. | Transmite el documento en fragmentos usando `DocumentBuilder` si solo necesitas secciones específicas. | + +## Bonus: Exportar varios archivos DOCX en lote + +Si necesitas **convertir docx a texto** para una carpeta completa, envuelve la lógica en un bucle: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Este fragmento **exporta docx a txt** para cada archivo en el directorio, ahorrándote horas de trabajo manual. + +## Conclusión + +Acabas de aprender cómo **exportar docx a txt** con Java, garantizando que cada carácter Unicode permanezca intacto, que las tablas sean legibles y que todo el proceso sea reproducible. Configurando `TxtSaveOptions` para UTF‑8 y, opcionalmente, preservando los diseños de tabla, puedes convertir de forma fiable **docx a texto**, **convertir word a texto**, y **exportar word como txt** para cualquier flujo de trabajo posterior. + +¿Listo para el próximo desafío? Intenta exportar a otros formatos de texto plano como markdown (`.md`) o CSV, o explora las capacidades de conversión a PDF de Aspose.Words. Los mismos principios—codificación explícita, preservación del diseño y verificación exhaustiva—se aplican en todos los casos. + +¡Feliz codificación, y que tus archivos de texto siempre permanezcan ricos en Unicode! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="diagrama del pipeline de exportar docx a txt"} + +## Tutoriales relacionados + +- [Convertir Docx a Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convertir DOCX a PDF en Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convertir docx a markdown – Exportar ecuaciones matemáticas a LaTeX con Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/spanish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..7b449a29db --- /dev/null +++ b/words/spanish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Guardar documento como PDF usando Aspose.Words Java y añadir accesibilidad + al PDF. Aprende a convertir docx a PDF, etiquetar reglas horizontales y garantizar + el cumplimiento de PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: es +og_description: Guarde el documento como PDF con Aspose.Words Java mientras agrega + accesibilidad al PDF. Guía paso a paso para convertir docx a PDF y etiquetar reglas + horizontales para el cumplimiento de PDF/UA‑2. +og_title: Guardar documento como PDF con Aspose.Words Java – Accesibilidad facilitada +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Guardar documento como PDF con Aspose.Words Java – Guía completa de accesibilidad +url: /es/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guardar documento como PDF con Aspose.Words Java – Guía completa de accesibilidad + +¿Alguna vez te has preguntado cómo **guardar documento como PDF** manteniéndolo accesible para lectores de pantalla? No estás solo. Muchos desarrolladores necesitan *convertir docx a pdf* y seguir cumpliendo con los estándares PDF/UA‑2, especialmente cuando la fuente contiene reglas horizontales que deben etiquetarse correctamente. En este tutorial recorreremos paso a paso cómo **guardar documento como PDF** usando Aspose.Words para Java, **añadir accesibilidad al PDF** de forma automática y garantizar que cada regla horizontal esté **etiquetada** como un artefacto. + +Comenzaremos con un proyecto Java limpio, cargaremos un DOCX que ya contiene reglas horizontales, configuraremos las opciones de guardado PDF para el cumplimiento PDF/UA‑2 y, finalmente, generaremos un PDF totalmente accesible. Al final, podrás **guardar documento como pdf** con la confianza de que pasa las verificaciones de accesibilidad. + +## Requisitos previos + +Antes de sumergirnos, asegúrate de tener: + +- Java 8 o superior instalado (el tutorial se probó con JDK 17). +- Maven 3.6+ (o Gradle si lo prefieres) para gestionar dependencias. +- Una licencia válida de Aspose.Words para Java (la prueba gratuita funciona, pero una licencia elimina las marcas de agua de evaluación). +- Un archivo DOCX (`input.docx`) que incluya al menos una regla horizontal—piensa en una simple línea separadora que agregarías en Word. + +> **Consejo profesional:** Si no tienes un DOCX a mano, simplemente crea un nuevo documento de Word, escribe algunos párrafos, inserta *Insertar → Línea horizontal*, guárdalo como `input.docx` y colócalo en la carpeta que prefieras. + +## Paso 1: Configurar el proyecto Maven + +Primero, crea un nuevo proyecto Maven (o añádelo a uno existente). El `pom.xml` necesita la dependencia de Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Por qué es importante:** Añadir el artefacto `aspose-words` es el primer paso para *convertir docx a pdf*. Sin él, el compilador no reconocerá `Document`, `PdfSaveOptions` y otras clases cruciales. + +## Paso 2: Cargar el DOCX de origen que contiene reglas horizontales + +Ahora escribiremos una pequeña clase Java que cargue el DOCX. Aquí es donde comienza la parte de **etiquetar reglas horizontales**—Aspose.Words trata automáticamente una regla horizontal como un párrafo con borde, pero dejaremos que el motor PDF/UA gestione la etiquetación. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Observa que aún no hemos guardado nada; solo estamos **cargando** el DOCX, que es la primera mitad de *convertir docx a pdf*. El objeto `Document` ahora contiene todo el contenido de Word, incluidas las reglas horizontales que insertaste. + +## Paso 3: Configurar las opciones de guardado PDF para cumplimiento PDF/UA‑2 + +La magia de **añadir accesibilidad al PDF** reside en `PdfSaveOptions`. Al establecer el nivel de cumplimiento en `PDF_UA_2`, Aspose.Words: + +1. Etiquetará los elementos estructurales (títulos, tablas, etc.). +2. Marcará los elementos decorativos—como las reglas horizontales—como *artefactos*, de modo que los lectores de pantalla los ignoren. +3. Insertará los metadatos necesarios de PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **¿Por qué establecer el cumplimiento?** Sin `PDF_UA_2`, el PDF resultante puede seguir siendo legible pero no pasará los validadores automáticos de accesibilidad. El requisito de **etiquetar reglas horizontales** se satisface automáticamente porque PDF/UA las trata como *artefactos* cuando está activada la bandera de cumplimiento. + +## Paso 4: Guardar el documento como PDF + +Ahora finalmente **guardamos documento como pdf**. Esta única línea realiza el trabajo pesado—convierte el DOCX, aplica las etiquetas de accesibilidad y escribe el archivo en disco. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Ejecuta la clase (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) y verás un mensaje de confirmación. Abre el `ua_compliant.pdf` resultante en Adobe Acrobat y verifica **Archivo → Propiedades → Descripción → PDF/A, PDF/UA**—deberías ver “PDF/UA‑2” listado. + +### Resultado esperado + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Abre el PDF y notarás: + +- El texto del documento es seleccionable y buscable. +- La línea horizontal es invisible para los lectores de pantalla (tratada como artefacto). +- El PDF pasa las herramientas básicas de validación PDF/UA (por ejemplo, PAC 3). + +## Paso 5: Verificar la accesibilidad – Lista de verificación rápida + +Aunque Aspose.Words realiza la mayor parte del trabajo, es buena práctica verificar la salida. + +| Verificación | Cómo comprobar | +|--------------|----------------| +| **Título del documento** | Abre Acrobat → Archivo → Propiedades → Campo Title (debe coincidir con `pdfOptions.setTitle`). | +| **Etiquetado de artefactos** | Usa la herramienta “Orden de lectura” de Acrobat. Las reglas horizontales deben aparecer como *Artefacto* (gris). | +| **Orden lógico de lectura** | Ejecuta el “Comprobador de accesibilidad” en Acrobat; asegúrate de que no haya errores estructurales. | +| **PDF etiquetado** | En Acrobat, revisa el panel “Etiquetas” – deberías ver una jerarquía (Document → Section → Paragraph, etc.). | +| **Cumplimiento PDF/UA** | Acrobat mostrará “PDF/UA‑2” bajo la pestaña “Estándares”. | + +Si alguna de estas verificaciones falla, revisa que estés usando la última versión de Aspose.Words y que `setCompliance(PdfCompliance.PDF_UA_2)` esté aplicado correctamente. + +## Problemas comunes y cómo evitarlos + +1. **Licencia ausente** – La versión de prueba añade una marca de agua que puede romper la validación PDF/UA. Aplica tu licencia al inicio del `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Ruta de entrada incorrecta** – Una `FileNotFoundException` detendrá la conversión. Usa rutas absolutas o coloca el DOCX en la raíz del proyecto y haz referencia con `new File("input.docx").getAbsolutePath()`. +3. **Uso de una versión antigua de Aspose** – El soporte PDF/UA se añadió en la versión 22.9. Actualiza a la última versión para evitar funciones faltantes. +4. **Regla horizontal como imagen** – Si insertaste la línea como una imagen en lugar de una regla horizontal nativa de Word, Aspose la trata como una imagen normal, no como artefacto. Sustituye la imagen por la *Línea horizontal* incorporada de Word para un etiquetado correcto. + +## Extender la solución – ¿Qué pasa si necesitas más? + +- **Etiquetas personalizadas**: Si tienes otros elementos decorativos (p. ej., íconos decorativos), puedes marcarlos manualmente como artefactos usando `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Múltiples documentos**: Recorre una carpeta de archivos DOCX y conviértelos por lotes, reutilizando la misma instancia de `PdfSaveOptions` para mejorar el rendimiento. +- **Agregar una etiqueta de idioma**: Para PDFs multilingües, establece `pdfOptions.setLanguage("en-US")` para ayudar a las tecnologías de asistencia a elegir la voz adecuada. + +## Ejemplo completo (todo el código junto) + +A continuación tienes el programa Java completo y ejecutable. Copia‑pega en tu IDE, ajusta las rutas y ejecuta. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Ejecuta el programa, abre el PDF generado y tendrás un archivo limpio y accesible listo para distribuir. + +## Conclusión + +Acabamos de demostrar cómo **guardar documento como pdf** con Aspose.Words para Java mientras se **añade accesibilidad al pdf** de forma automática y se **etiquetan reglas horizontales** como artefactos. Los puntos clave: + +- Usa `PdfSaveOptions` con cumplimiento `PDF_UA_2` para cumplir con los estándares de accesibilidad. +- Cargar un DOCX y llamar a `doc.save(..., pdfOptions)` es todo lo que necesitas para **convertir docx a pdf**. +- Las reglas horizontales se gestionan por ti—no se requiere código adicional, cumpliendo el requisito de **etiquetar reglas horizontales**. +- El enfoque es totalmente **aspose convert docx pdf** compatible, funciona con la última versión de la biblioteca y produce un PDF listo para validación. + +¿Listo para el siguiente desafío? Prueba agregar metadatos personalizados, incrustar fuentes o procesar por lotes una carpeta completa de archivos DOCX. Cada una de esas extensiones se basa en la misma base que hemos establecido aquí. + +¿Tienes preguntas sobre el cumplimiento PDF/UA, licencias o el manejo de otros elementos de Word? Deja un comentario o consulta la documentación oficial de Aspose—hay una gran cantidad de ejemplos para explorar. ¡Feliz codificación y disfruta creando PDFs accesibles! + +![guardar documento como pdf usando Aspose.Words Java – ejemplo de PDF accesible](placeholder-image.png "guardar documento como pdf usando Aspose.Words Java – ejemplo de PDF accesible") + +## Tutoriales relacionados + +- [Cómo guardar documento como pdf con Aspose.Words para Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Cómo convertir Word a PDF usando Aspose.Words para Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convertir DOCX a PDF en Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/spanish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..d97fe73567 --- /dev/null +++ b/words/spanish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,233 @@ +--- +category: general +date: 2026-05-26 +description: Guarda Word como markdown y descubre cómo exportar ecuaciones matemáticas + a LaTeX usando Aspose.Words para Java. Convierte ecuaciones de Word a LaTeX en solo + unas pocas líneas. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: es +og_description: Guarda Word como Markdown y aprende a exportar ecuaciones matemáticas + a LaTeX usando Aspose.Words para Java. Una guía completa y ejecutable. +og_title: Guardar Word como markdown – Exportar matemáticas a LaTeX con Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Guardar Word como markdown – Exportar matemáticas a LaTeX con Java +url: /es/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guardar Word como markdown – Exportar matemáticas a LaTeX con Java + +¿Alguna vez necesitaste **guardar Word como markdown** pero temías que tus ecuaciones se convirtieran en un desastre? No estás solo. En esta guía recorreremos **cómo exportar matemáticas** desde un archivo `.docx` directamente a LaTeX mientras el resto del documento se convierte en Markdown limpio. + +Cubrirémos todo, desde la configuración de la biblioteca Aspose.Words hasta la verificación del archivo final `out.md`. Al final podrás **convertir ecuaciones de Word a LaTeX** en una única llamada de método, y comprenderás los pequeños matices que hacen que la conversión sea fiable. + +--- + +## Lo que necesitarás + +- **Java 8+** – el código se ejecuta en cualquier JDK reciente. +- **Aspose.Words for Java** – ya sea la dependencia Maven/Gradle o el JAR si prefieres una configuración manual. +- Un documento Word (`math.docx`) que contenga al menos una ecuación de Office Math. +- Un IDE o la línea de comandos simple `javac`/`java`, lo que prefieras. + +Si ya los tienes, genial. Si no, la siguiente sección muestra exactamente cómo obtener la biblioteca en tu proyecto. + +--- + +## Guardar Word como markdown – Paso 1: Añadir Aspose.Words a tu proyecto + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Consejo profesional:** Aspose ofrece una licencia temporal gratuita para pruebas. Coloca el archivo `license.xml` en tu carpeta de recursos y llama a `License license = new License(); license.setLicense("license.xml");` antes de cargar cualquier documento. + +Una vez resuelta la dependencia, estás listo para escribir el código de conversión. + +--- + +## Cómo exportar ecuaciones matemáticas a LaTeX + +El trabajo pesado lo realiza `MarkdownSaveOptions`. Al cambiar su `OfficeMathExportMode` a `LATEX`, cada objeto Office Math se renderiza como un fragmento LaTeX dentro del resultado Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Por qué funciona esto + +- **`Document`** es el punto de entrada de Aspose; abstrae el archivo `.docx` y te da acceso a cada nodo, incluidas las ecuaciones. +- **`MarkdownSaveOptions`** indica a la biblioteca *cómo* deseas la salida. El comportamiento predeterminado es renderizar las ecuaciones como imágenes, lo que contradice el propósito de un formato basado en texto. +- **`OfficeMathExportMode.LATEX`** obliga al motor a traducir cada nodo `OfficeMath` a su equivalente LaTeX, que los analizadores Markdown (como GitHub o Jekyll) pueden renderizar cuando se combina con un plugin MathJax. + +--- + +## Convertir ecuaciones de Word a LaTeX – Paso 2: Verificar la salida Markdown + +Después de ejecutar el programa, abre `out.md`. Deberías ver algo como esto: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Nota:** Los fragmentos LaTeX están envueltos en `$…$` para matemáticas en línea y `$$…$$` para matemáticas en bloque. Esta es la sintaxis estándar que la mayoría de los generadores de sitios estáticos entienden cuando MathJax está habilitado. + +Si prefieres que las ecuaciones permanezcan solo en línea, puedes ajustar aún más `MarkdownSaveOptions`: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx a markdown LaTeX – Paso 3: Casos límite y errores comunes + +| Situación | Qué observar | Solución | +|-----------|--------------|----------| +| **Ecuaciones anidadas complejas** | Aspose puede generar llaves extra `{}` que algunos analizadores tratan literalmente. | Post‑procesa el Markdown con una expresión regular simple para colapsar `{{` → `{`. | +| **Falta MathJax en el sitio objetivo** | Las ecuaciones aparecen como código LaTeX sin procesar. | Añade `` a tu plantilla HTML. | +| **Documentos grandes** | El consumo de memoria se dispara porque todo el documento se carga de una vez. | Usa `LoadOptions.setLoadFormat(LoadFormat.DOCX)` y considera procesar páginas en lotes si encuentras `OutOfMemoryError`. | +| **Licencia no establecida** | Recibirás una advertencia y la salida puede estar marcada con una marca de agua. | Carga la licencia temprano en `main` como se muestra en el consejo Maven anterior. | + +--- + +## Guardar Word como markdown – Ejemplo completo funcionando + +A continuación hay una clase autónoma que puedes copiar y pegar en cualquier proyecto Java. Simplemente reemplaza `YOUR_DIRECTORY` con la ruta a tus archivos. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Ejecuta el programa (`java MathToLatexMarkdown`) y verás el mensaje en la consola confirmando el éxito. Abre `out.md` en cualquier editor – las ecuaciones deberían ser fragmentos LaTeX limpios listos para renderizar. + +--- + +## Captura de salida esperada + +![salida de guardar Word como markdown con ecuaciones LaTeX](https://example.com/images/markdown-latex-output.png "salida de guardar Word como markdown con ecuaciones LaTeX") + +*La imagen muestra un fragmento del Markdown generado donde la ecuación `\int_{a}^{b} f(x)\,dx` está envuelta en `$$`.* + +--- + +## Conclusión + +Acabamos de demostrar cómo **guardar Word como markdown** mientras se preserva cada ecuación Office Math como LaTeX nativo. El paso clave fue configurar `MarkdownSaveOptions` con `OfficeMathExportMode.LATEX`, lo que convierte una canalización típica de Word a Markdown en una herramienta de conversión totalmente consciente de las matemáticas. + +Ahora puedes: + +1. **Cómo exportar matemáticas** desde cualquier `.docx` sin perder fidelidad. +2. **Convertir ecuaciones de Word a LaTeX** para generadores de sitios estáticos, documentación o blogs académicos. +3. Extender el enfoque para procesar en lotes muchos archivos, integrarlo con pipelines CI, o incluso crear un pequeño servicio web. + +Si tienes curiosidad por la siguiente frontera, intenta combinar esto con **docx a markdown LaTeX** para documentos con muchas imágenes, o explora `HtmlSaveOptions` de Aspose para una versión HTML lista para la web. Las posibilidades son infinitas—experimenta, rompe cosas y luego comparte tus hallazgos con la comunidad. + +¿Tienes preguntas o una ecuación complicada que no se renderizó como esperabas? Deja un comentario abajo, ¡y feliz codificación! + +## Tutoriales relacionados + +- [Cómo exportar LaTeX desde Word: Convertir DOCX a Markdown y guardar como PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Convertir docx a markdown – Exportar ecuaciones matemáticas a LaTeX con Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Cómo convertir Word a PDF usando Aspose.Words para Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/spanish/java/document-loading-and-saving/_index.md index 86dc2027a7..9066a4794f 100644 --- a/words/spanish/java/document-loading-and-saving/_index.md +++ b/words/spanish/java/document-loading-and-saving/_index.md @@ -116,6 +116,8 @@ Las configuraciones de documento son la clave para entregar documentos adaptados ### [Recuperar docx corrupto – Guía completa para reparar y procesar documentos](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [Abrir documento Word corrupto – Establecer modo de recuperación en Java](./open-corrupted-word-document-set-recovery-mode-in-java/) + ### [Capturar advertencias de sustitución de fuentes en Java con Aspose.Words – Guía completa](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## Preguntas frecuentes diff --git a/words/spanish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/spanish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..bf62b12448 --- /dev/null +++ b/words/spanish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-05-26 +description: Abrir documento de Word dañado en Java con Aspose.Words. Aprende cómo + establecer el modo de recuperación y recuperar archivos de Word dañados de forma + fiable. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: es +og_description: Abrir documento de Word dañado en Java usando Aspose.Words. Esta guía + muestra cómo establecer el modo de recuperación y recuperar archivos de Word dañados + de manera eficiente. +og_title: Abrir documento Word corrupto – establecer modo de recuperación en Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Abrir documento de Word corrupto – Configurar modo de recuperación en Java +url: /es/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Abrir documento Word corrupto – Establecer modo de recuperación en Java + +¿Alguna vez intentaste abrir un documento Word corrupto y viste cómo el programa se bloquea con una excepción? No eres el único; esos archivos .docx rotos pueden ser un verdadero dolor de cabeza. La buena noticia es que Aspose.Words for Java te brinda un control granular para que puedas **open corrupted word document** sin que la aplicación se caiga, e incluso decidir si deseas advertencias, recuperación silenciosa o un rechazo definitivo. + +En este tutorial recorreremos todo el proceso: desde crear el `LoadOptions` correcto, hasta elegir el valor adecuado de **set recovery mode**, y finalmente confirmar que el documento se haya cargado correctamente. Al final sabrás **how to recover corrupted word file** de forma programática, sin necesidad de copiar‑pegar manualmente. + +> **Qué necesitarás** +> * Java 8 o superior (la API también funciona con Java 11) +> * Aspose.Words for Java 23.9 (o la última versión) +> * Un archivo .docx corrupto de muestra—simplemente renombra cualquier archivo válido para simular corrupción si no tienes uno a mano + +Vamos a sumergirnos. + +## Abrir documento Word corrupto – Visión general paso a paso + +A continuación se muestra el flujo de alto nivel que implementaremos: + +1. **Crear `LoadOptions`** – este objeto indica a Aspose.Words cómo comportarse cuando encuentra problemas. +2. **Establecer modo de recuperación** – elige `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` o `REJECT_CORRUPTED`. +3. **Cargar el documento** usando las opciones configuradas. +4. **Verificar** que la carga haya tenido éxito (p. ej., imprimir el recuento de páginas). + +Cada paso se explica en detalle, con fragmentos de código que puedes copiar‑pegar directamente en tu IDE. + +## Establecer modo de recuperación para diferentes escenarios + +Aspose.Words define tres estrategias de recuperación dentro de `LoadOptions.RecoveryMode`: + +| Modo | Comportamiento | Cuándo usar | +|------|----------------|-------------| +| `RECOVER_WITH_WARNINGS` | Intenta cargar el documento, pero muestra cualquier problema como advertencias en la consola. | Quieres ver *qué* salió mal sin abortar. | +| `RECOVER_WITHOUT_WARNINGS` | Corrige silenciosamente lo que puede y suprime las advertencias. | Entornos de producción donde los registros deben permanecer limpios. | +| `REJECT_CORRUPTED` | Lanza una excepción en el momento en que se detecta la corrupción. | Pipelines de validación estricta que deben fallar rápidamente. | + +Elegir el modo correcto es la esencia de **set recovery mode** adecuadamente. En la mayoría de las sesiones de depuración `RECOVER_WITH_WARNINGS` es la opción ideal porque te indica exactamente qué partes fueron reparadas. + +## Cómo recuperar un archivo Word corrupto usando Aspose.Words + +A continuación tienes un **programa Java completo y ejecutable** que demuestra todo el proceso. Siéntete libre de colocarlo en un archivo `RecoveryModeDemo.java`, ajustar la ruta y ejecutarlo. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Por qué cada línea es importante + +* **`LoadOptions loadOptions = new LoadOptions();`** – sin este objeto Aspose.Words usa la recuperación predeterminada, que *rechaza* los archivos corruptos. Crearlo te permite cambiar ese comportamiento. +* **`setRecoveryMode(...)`** – esta es la llamada **set recovery mode** que decide si aparecen advertencias, se ocultan o provocan una excepción. +* **`new Document(path, loadOptions);`** – el constructor acepta el `LoadOptions` que acabamos de configurar, de modo que la biblioteca sepa cómo tratar el archivo dañado desde el principio. +* **`doc.getPageCount()`** – una rápida comprobación de sanidad. Si el documento se carga y devuelve un recuento de páginas, has logrado **how to recover corrupted word file**. +* **`doc.save(...)`** – opcional pero útil; puedes escribir la versión reparada de nuevo en disco para uso posterior. + +## Manejo de casos límite comunes + +### 1. Archivo no encontrado + +Si la ruta es incorrecta, `Document` lanza una `FileNotFoundException`. Envuelve la carga en un bloque try‑catch y registra un mensaje amigable: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Corrupción irrecuperable + +Incluso con `RECOVER_WITH_WARNINGS`, algunas estructuras están más allá de la reparación. En ese caso Aspose.Words aún carga lo que puede, pero verás advertencias como “Cannot read paragraph properties”. Presta atención a la salida de la consola; esas advertencias a menudo indican secciones faltantes que deberás reconstruir manualmente. + +### 3. Archivos grandes y rendimiento + +La recuperación añade una pequeña sobrecarga porque la biblioteca analiza el archivo dos veces: una para detectar problemas y otra para reconstruir. Para documentos de varios gigabytes, considera transmitir el archivo o aumentar el heap de la JVM (`-Xmx2g`) para evitar `OutOfMemoryError`. + +## Consejos profesionales – Hacer la recuperación robusta + +* **Registrar advertencias en un archivo** – redirige `System.err` a un logger para que tengas un registro de auditoría de lo que se corrigió. +* **Validar después de la recuperación** – ejecuta `doc.updatePageLayout();` y luego vuelve a comprobar el recuento de páginas; a veces el diseño cambia después de reparar secciones rotas. +* **Automatizar recuperación por lotes** – envuelve la demostración en un bucle que procese una carpeta de archivos corruptos, usando el mismo `LoadOptions` cada vez. + +## Conclusión + +Ahora sabes exactamente **how to recover corrupted word file** usando Aspose.Words for Java. Creando una instancia de `LoadOptions`, **set recovery mode** a la estrategia que se ajuste a tu escenario, y cargando el documento con esas opciones, puedes abrir de forma segura **open corrupted word document** sin que tu aplicación se caiga. El código de ejemplo anterior es una solución completa, lista para ejecutar, que imprime el recuento de páginas e incluso guarda una copia limpiada. + +¿Qué sigue? Prueba cambiar el modo de recuperación a `RECOVER_WITHOUT_WARNINGS` y compara la salida de la consola, o experimenta cargando documentos cifrados (necesitarás proporcionar una contraseña a través de + +## Tutoriales relacionados + +- [Aspose.Words Java: Guía completa para el procesamiento de documentos Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Cómo convertir Word a PDF usando Aspose.Words para Java](/words/english/java/document-converting/using-document-converting/) +- [Cómo comparar dos archivos Word con Aspose.Words para Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/spanish/java/document-styling/_index.md index 61f20dd816..884f2198ee 100644 --- a/words/spanish/java/document-styling/_index.md +++ b/words/spanish/java/document-styling/_index.md @@ -43,6 +43,8 @@ Aprenda a personalizar temas de documentos con Aspose.Words para Java. Esta guí Aprenda a aplicar marcas de agua y configurar páginas con Aspose.Words para Java. Una guía completa con código fuente. ### [Estilo de encabezado y pie de página del documento](./document-header-footer-styling/) Aprenda a aplicar estilo a encabezados y pies de página de documentos con Aspose.Words para Java en esta guía detallada. Incluye instrucciones paso a paso y código fuente. +### [Configuración predeterminada de fuentes en Aspose.Words para Java – Guía completa](./set-default-font-settings-in-aspose-words-for-java-complete/) +Aprenda a establecer la fuente predeterminada en documentos con Aspose.Words para Java. Guía completa con ejemplos de código. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/spanish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..633fe8d324 --- /dev/null +++ b/words/spanish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Configure la configuración de fuentes predeterminada en Aspose.Words + para Java y aprenda a establecer la configuración de fuentes y detectar fuentes + faltantes con solo unas pocas líneas de código. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: es +og_description: Establezca la configuración de fuentes predeterminada en Aspose.Words + para Java, aprenda a configurar la tipografía y a detectar fuentes faltantes de + forma rápida y fiable. +og_title: Establecer la configuración de fuente predeterminada en Aspose.Words para + Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Establecer la configuración de fuente predeterminada en Aspose.Words para Java + – Guía completa +url: /es/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Configurar la configuración de fuentes predeterminadas en Aspose.Words para Java – Guía completa + +¿Alguna vez te has preguntado cómo **establecer la configuración de fuentes predeterminadas** al cargar un documento Word con Aspose.Words para Java? No estás solo. Los glifos faltantes pueden convertir un informe pulido en un desastre confuso, y detectar esas advertencias de sustitución de fuentes temprano ahorra horas de depuración. + +En este tutorial recorreremos un ejemplo conciso y de extremo a extremo que **establece la configuración de fuentes predeterminadas**, te muestra cómo **establecer la configuración de fuentes** mediante código, y demuestra una forma fiable de **detectar fuentes faltantes** antes de que arruinen tu diseño. + +--- + +## Qué aprenderás + +- Cómo crear un objeto `LoadOptions` con una nueva instancia de `FontSettings`. +- Cómo adjuntar un listener de advertencias que **detecte fuentes faltantes** durante la carga del documento. +- Cómo cargar un archivo DOCX mientras el listener informa silenciosamente cualquier sustitución. +- Consejos para personalizar fuentes de respaldo y manejar casos límite en producción. + +Sin bibliotecas adicionales, sin archivos de configuración obscuros—solo Java puro y Aspose.Words. + +--- + +## Requisitos previos + +Antes de comenzar, asegúrate de tener: + +1. **Aspose.Words para Java** (versión 23.10 o posterior) en tu classpath. +2. Un kit de desarrollo Java 17 (o superior) — cualquier JDK moderno funciona. +3. Un archivo DOCX que intencionalmente use una fuente que no tengas instalada (p. ej., *“MissingFont.ttf”*). + +Si te falta el JAR de Aspose, descárgalo del repositorio oficial de Maven: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Eso es todo—no necesitas instalar fuentes adicionales para esta demostración. + +--- + +## Paso 1: Crear LoadOptions y **establecer la configuración de fuentes predeterminadas** + +Lo primero que necesitamos es un objeto `LoadOptions` limpio que indique a Aspose cómo comportarse cuando encuentre tipografías desconocidas. Llamando a `setFontSettings(new FontSettings())` **establecemos la configuración de fuentes predeterminadas** que comienza con una lista de respaldo vacía. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Por qué es importante:** +> Cuando no configuras explícitamente las fuentes, Aspose recurre a la colección predeterminada del sistema, lo que puede ocultar problemas de fuentes faltantes. Al iniciar con una instancia nueva de `FontSettings` obtienes control total sobre qué fuentes se consideran válidas. + +--- + +## Paso 2: Adjuntar un listener de advertencias para **detectar fuentes faltantes** + +Aspose genera un objeto `WarningInfo` por cada sustitución que realiza. Escuchando `WarningType.FONT_SUBSTITUTION` podemos **detectar fuentes faltantes** en el momento en que el documento se analiza. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Consejo profesional:** El listener se ejecuta en el mismo hilo que carga el documento, por lo que prácticamente no hay penalización de rendimiento. Si necesitas recopilar advertencias para análisis posterior, introdúcelas en una `List` en lugar de imprimirlas directamente. + +--- + +## Paso 3: Cargar el documento usando las opciones configuradas + +Ahora que hemos **establecido la configuración de fuentes** y preparado un listener, simplemente cargamos el archivo. Cualquier fuente faltante activa nuestra devolución de llamada al instante. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Si el archivo fuente hace referencia a una fuente que no está instalada, verás una salida similar a: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Esa línea te indica exactamente qué fuente faltó y qué respaldo se utilizó—perfecto para registro o retroalimentación al usuario. + +--- + +## Paso 4: Continuar con el procesamiento normal (opcional) + +En este punto el documento está completamente cargado, y puedes proceder con cualquier manipulación que desees—edición, conversión a PDF o extracción de texto. El listener de advertencias ya ha cumplido su función, por lo que no necesitas verificaciones adicionales. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **¿Qué pasa si deseas un respaldo personalizado?** +> En lugar de dejar `FontSettings` vacío, puedes añadir fuentes específicas: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Ahora cualquier tipografía faltante será reemplazada por *Times New Roman*—una opción fiable para la mayoría de los documentos occidentales. + +--- + +## Visión general visual + +![Diagrama que muestra cómo establecer la configuración de fuentes predeterminadas en Aspose.Words para Java](image.png "Diagrama del flujo de configuración de fuentes predeterminadas") + +*Texto alternativo: diagrama del flujo de configuración de fuentes predeterminadas en Aspose.Words para Java.* + +El diagrama ilustra el flujo desde la inicialización de `LoadOptions` (donde **establecemos la configuración de fuentes predeterminadas**) hasta la adjunción del listener de advertencias (para **detectar fuentes faltantes**) y, finalmente, la carga del documento. + +--- + +## Errores comunes y cómo evitarlos + +| Error | Por qué ocurre | Solución | +|-------|----------------|----------| +| **Olvidar llamar a `setFontSettings`** | Aspose usa los valores predeterminados del sistema, ocultando fuentes faltantes. | Siempre crea una nueva instancia de `FontSettings` y asígnala a `LoadOptions`. | +| **Listener no se dispara** | Listener añadido después de cargar el documento. | Añade el listener de advertencias *antes* de llamar a `new Document(...)`. | +| **Error de ruta que produce `FileNotFoundException`** | Ruta codificada manualmente no coincide con la sensibilidad a mayúsculas del SO. | Usa `Paths.get("...").toAbsolutePath()` o configura una ruta relativa desde la raíz del proyecto. | +| **Múltiples fuentes faltantes saturan los registros** | Documentos grandes pueden generar decenas de advertencias. | Filtra duplicados o agrega mensajes en un `Set` antes de imprimir. | + +--- + +## Extender la solución + +Si necesitas **establecer la configuración de fuentes** para toda una aplicación, considera crear un `FontSettings` singleton y reutilizarlo en todos los `LoadOptions`. Así mantienes una estrategia de respaldo coherente y evitas la creación repetida de objetos. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Ahora cualquier parte de tu código puede simplemente llamar a `FontConfig.getLoadOptions()` y beneficiarse instantáneamente de la misma lógica de **establecer la configuración de fuentes predeterminadas**. + +--- + +## Conclusión + +Acabamos de cubrir todo lo que necesitas para **establecer la configuración de fuentes predeterminadas** en Aspose.Words para Java, **establecer la configuración de fuentes** mediante código y **detectar fuentes faltantes** antes de que corrompan tu salida. El ejemplo completo y ejecutable está en los fragmentos de código anteriores, y puedes pegarlos directamente en tu IDE para ver las advertencias en acción. + +¿Próximos pasos? Prueba cambiando la fuente de respaldo, experimenta con diferentes formatos de documento (DOC, RTF, HTML) o integra el colector de advertencias en un panel de monitoreo. Cuanto más juegues con `FontSettings`, más confianza tendrás de que tus documentos generados se vean exactamente como esperas—sin sorpresas, sin glifos rotos. + +¿Tienes preguntas o un escenario complicado de sustitución de fuentes? Deja un comentario abajo, ¡y feliz codificación! + +## Tutoriales relacionados + +- [Set Font Fallback Settings](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/java/images-shapes/_index.md b/words/spanish/java/images-shapes/_index.md index 31e75162ef..076618bedd 100644 --- a/words/spanish/java/images-shapes/_index.md +++ b/words/spanish/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aprenda a generar miniaturas de alta calidad y mapas de bits de tamaño personal ### [Crear documento Word en Java – Añadir forma de rectángulo con efecto de sombra](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Aprenda a crear un documento Word en Java y agregar una forma rectangular con sombra usando Aspose.Words. +### [Crear forma de rectángulo en documento Word Java – Guía completa paso a paso](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Aprenda a crear y personalizar una forma rectangular en documentos Word usando Aspose.Words para Java, con instrucciones detalladas paso a paso. + ## Recursos adicionales - [Documentación de Aspose.Words para Java](https://reference.aspose.com/words/java/) diff --git a/words/spanish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/spanish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..5980f3c53e --- /dev/null +++ b/words/spanish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-26 +description: Crear una forma rectangular en un documento Word con Java y aplicar el + efecto de sombra. Aprende cómo agregar sombra a la forma, establecer la distancia + de la sombra y guardar el archivo. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: es +og_description: Crear una forma rectangular en un documento Word con Java, aplicar + efecto de sombra, añadir sombra a la forma y establecer la distancia de la sombra + con Aspose.Words. +og_title: Crear forma de rectángulo en documento Word con Java – Guía completa +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Crear forma de rectángulo en documento Word con Java – Guía completa paso a + paso +url: /es/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear forma de rectángulo en un documento Word con Java – Guía completa paso a paso + +¿Alguna vez necesitaste **crear una forma de rectángulo** en un documento Word con Java pero no sabías por dónde empezar? No estás solo: muchos desarrolladores se topan con este obstáculo al generar informes o facturas de forma programática. En este tutorial recorreremos paso a paso cómo **crear una forma de rectángulo**, aplicar una sombra pulida y afinar la distancia de la sombra para que el resultado luzca profesional. + +Usaremos Aspose.Words para Java, una biblioteca robusta que permite manipular archivos Word sin necesidad de tener Microsoft Office instalado. Al final de esta guía podrás **crear documentos Word con Java** que **añadan sombra a la forma**, **apliquen efecto de sombra** y **establezcan la distancia de la sombra** con solo unas pocas líneas de código. + +--- + +## Qué construirás + +- Un archivo `.docx` nuevo que contiene un rectángulo cian. +- Una sombra realista que está difuminada, inclinada y parcialmente transparente. +- Control total sobre la distancia de la sombra respecto a la forma. +- Una clase Java lista para ejecutar que puedes insertar en cualquier proyecto Maven o Gradle. + +Sin herramientas externas, sin pasos manuales en la UI: solo código puro. + +--- + +## Requisitos previos + +- Java 8 o superior (el código funciona en Java 11, Java 17, etc.). +- Biblioteca Aspose.Words para Java (disponible a través de Maven Central). +- Un IDE o editor de texto que prefieras (IntelliJ IDEA, Eclipse, VS Code…). +- Familiaridad básica con la sintaxis de Java. + +Si nunca has añadido una dependencia Maven antes, aquí tienes el fragmento rápido: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Ahora, vamos al grano. + +--- + +## Paso 1: Crear forma de rectángulo en un documento Word + +Lo primero que necesitamos es un documento en blanco y un `DocumentBuilder`. Piensa en el builder como una pluma que escribe dentro del documento. Una vez que lo tengamos, podemos **crear una forma de rectángulo** con una única llamada a método. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Por qué es importante:** El método `insertShape` no solo crea la geometría sino que también añade la forma a la colección interna del documento, de modo que puedes comenzar a estilizarla de inmediato. + +--- + +## Paso 2: Aplicar efecto de sombra a la forma + +Ahora que el rectángulo está en la página, **aplicaremos el efecto de sombra**. Las sombras dan profundidad, haciendo que la forma parezca levantada de la página: una mejora sutil de UI que puede aumentar la legibilidad en los informes. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Consejo profesional:** Un difuminado de `5.0` se ve natural en la mayoría de los documentos mostrados en pantalla. Si vas a imprimir, quizá quieras un valor ligeramente menor para evitar una apariencia borrosa. + +--- + +## Paso 3: Establecer distancia de sombra – Ajuste fino de la posición + +Las sombras no solo se tratan de difuminado; también necesitan el desplazamiento correcto. Aquí es donde **establecemos la distancia de la sombra**. Una distancia de `7.0` puntos crea un desplazamiento moderado que se nota pero no resulta abrumador. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **¿Qué pasa si necesitas un desplazamiento mayor?** Aumenta el valor; disminúyelo para un aspecto más ajustado. Recuerda que la distancia trabaja junto con el ángulo para posicionar la sombra correctamente. + +--- + +## Paso 4: Guardar el documento – Persistir tu trabajo + +Finalmente, escribimos el documento en disco. Cambia la ruta a donde desees que se guarde el archivo. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Ejecutar la clase crea un archivo `shadow.docx` que, al abrirse en Microsoft Word o LibreOffice, muestra un rectángulo cian con una sombra gris suave inclinada a 45° y desplazada 7 puntos. + +--- + +## Ejemplo completo y funcional + +A continuación tienes el código completo, listo para copiar y pegar. Incluye todas las importaciones, comentarios y la llamada final a `save`. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Salida esperada:** Abre `shadow.docx` → verás un rectángulo cian centrado en la primera página, proyectando una sombra gris sutil ligeramente desplazada hacia abajo‑derecha. El difuminado y la transparencia de la sombra le dan un aspecto de iluminación natural. + +--- + +## Preguntas frecuentes y casos especiales + +### “¿Puedo usar una forma diferente?” + +Claro. Sustituye `ShapeType.RECTANGLE` por `ShapeType.OVAL`, `ShapeType.LINE` o cualquier otro enum soportado. El resto del código de sombra permanece igual. + +### “¿Qué pasa si necesito múltiples sombras?” + +Aspose.Words solo admite una sombra por forma. Para simular varias sombras, duplica la forma, desplaza cada copia y ajusta la transparencia. + +### “¿La sombra se ve en LibreOffice?” + +Sí—Aspose.Words escribe OOXML estándar, que LibreOffice interpreta correctamente. La sombra puede verse ligeramente distinta debido a los motores de renderizado, pero el efecto persiste. + +### “¿Cómo cambio el color de la sombra para que coincida con mi marca?” + +Simplemente reemplaza `java.awt.Color.GRAY` por cualquier `java.awt.Color` que prefieras, por ejemplo `new java.awt.Color(0, 120, 215)` para un azul corporativo. + +--- + +## Ilustración + +![crear forma de rectángulo en documento Word con Java](https://example.com/images/rectangle-shadow.png) + +*Texto alternativo:* **crear forma de rectángulo** ilustración que muestra un rectángulo cian con una sombra gris en un documento Word. + +--- + +## Recapitulación y próximos pasos + +Hemos cubierto cómo **crear una forma de rectángulo**, **aplicar efecto de sombra**, **añadir sombra a la forma** y **establecer la distancia de la sombra** usando Aspose.Words para Java. El código es autónomo, se ejecuta en cualquier JDK moderno y produce un archivo `.docx` pulido listo para distribuir. + +¿Quieres ir más allá? Prueba: + +- Añadir texto dentro del rectángulo con `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Crear una tabla de formas para construir un diagrama. +- Exportar el documento a PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Cada una de estas extensiones se basa en los mismos fundamentos que acabamos de explorar, por lo que te sentirás cómodo ampliando el ejemplo. + +--- + +## Reflexiones finales + +Dominar tareas como **crear documentos Word con Java** —incluyendo formas y sombras— te brinda una gran ventaja al automatizar informes, contratos o material de marketing. El enfoque mostrado aquí es limpio, mantenible y, lo más importante, fácil de ajustar para cualquier estilo visual que necesites. + +Ejecuta el código, modifica el difuminado, el ángulo y la distancia, y observa cómo tus documentos pasan de ser simples a estar pulidos. Si te encuentras con algún obstáculo, deja un comentario abajo; estaré encantado de ayudar. + +¡Feliz codificación! + +## Tutoriales relacionados + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/swedish/java/document-conversion-and-export/_index.md index 0bc5825dec..0317931691 100644 --- a/words/swedish/java/document-conversion-and-export/_index.md +++ b/words/swedish/java/document-conversion-and-export/_index.md @@ -84,8 +84,14 @@ Utnyttja kraften i matematiska ekvationer i dokument med Aspose.Words for Java. ### [Spara dokument som TXT – Snabbguide för export av Word-matematik](./save-document-as-txt-quick-guide-to-exporting-word-math/) Lär dig hur du sparar ett Word‑dokument som TXT och exporterar matematiska ekvationer med Aspose.Words. +### [Exportera docx till txt med Java – Komplett programmeringsguide](./export-docx-to-txt-with-java-complete-programming-guide/) +Lär dig hur du exporterar DOCX-filer till TXT med Java och Aspose.Words i en komplett steg‑för‑steg‑guide. + ### [Konvertera docx till markdown – Exportera matematiska ekvationer till LaTeX med Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) -Lär dig hur du konverterar DOCX-filer till Markdown och exporterar matematiska ekvationer som LaTeX med Aspose.Words. +Lär dig hur du konverterar DOCX‑filer till Markdown och exporterar matematiska ekvationer som LaTeX med Aspose.Words. + +### [Spara Word som markdown – Exportera matematik till LaTeX med Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Lär dig hur du sparar ett Word‑dokument som markdown och exporterar matematiska ekvationer till LaTeX med Java. ### [Aspose Word till PDF – Konvertera DOCX till PDF i Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Lär dig hur du konverterar DOCX-filer till PDF med Aspose.Words for Java i några enkla steg. @@ -102,9 +108,18 @@ Lär dig hur du formaterar tabeller och tillämpar tabellstilar i Aspose.Words f ### [Hur man bäddar in bilder i Markdown vid konvertering av DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Lär dig hur du bäddar in bilder i Markdown när du konverterar DOCX-filer med Aspose.Words. +### [Bädda in bilder som Base64 vid konvertering av DOCX till Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Lär dig hur du bäddar in bilder som Base64 när du konverterar DOCX-filer till Markdown med Aspose.Words. + ### [Skapa tillgänglig PDF från DOCX – Komplett guide](./create-accessible-pdf-from-docx-complete-guide/) Lär dig hur du konverterar DOCX till en tillgänglig PDF med fullständig steg‑för‑steg‑guide och bästa praxis. +### [Spara dokument som PDF med Aspose.Words Java – Fullständig tillgänglighetsguide](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Lär dig hur du sparar ett dokument som PDF med full tillgänglighet med Aspose.Words för Java. + +### [Skapa tillgänglig PDF i Java – Fullständig taggningsguide](./create-accessible-pdf-in-java-full-tagging-guide/) +Lär dig hur du skapar PDF‑dokument med fullständig tillgänglighet och taggning i Java med Aspose.Words. + ## Vanliga frågor **Q: Hur lägger jag till en vattenstämpel i en befintlig PDF med Aspose.Words?** diff --git a/words/swedish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/swedish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..116745909b --- /dev/null +++ b/words/swedish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,225 @@ +--- +category: general +date: 2026-05-26 +description: Skapa tillgänglig PDF i Java med steg‑för‑steg‑kod. Lär dig hur du taggar + PDF för tillgänglighet och aktiverar PDF‑taggning med PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: sv +og_description: Skapa tillgänglig PDF i Java med steg‑för‑steg‑kod. Lär dig hur du + taggar PDF för tillgänglighet och aktiverar PDF‑taggning med PdfSaveOptions. +og_title: Skapa tillgänglig PDF i Java – Fullständig guide för taggning +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Skapa tillgänglig PDF i Java – Fullständig guide för taggning +url: /sv/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa tillgänglig PDF i Java – Fullständig guide för taggning + +Har du någonsin undrat hur man **skapar tillgängliga PDF**‑filer direkt från Java‑kod? Du är inte ensam. Många utvecklare måste stödja användare som förlitar sig på skärmläsare, och skillnaden mellan en vanlig PDF och en tillgänglig kan vara enorm. I den här handledningen går vi igenom **hur man taggar PDF för tillgänglighet**, visar dig **hur man skapar en taggad PDF** med Aspose PDF för Java, och avslöjar de exakta stegen för att **lägga till tillgänglighetstaggar i PDF** så att varje läsare får samma information. + +Vi kommer också att gå igenom bästa praxis för **aktivera PDF‑taggning**, vanliga fallgropar och ett komplett, körbart exempel som du kan lägga in i ditt projekt idag. Inga vaga referenser – bara konkret kod, förklaringar och en slutlig fil som du kan öppna i Adobe Acrobat för att verifiera taggarna. + +## Vad du kommer att lära dig + +- Varför PDF‑taggning och tillgänglighetsöverensstämmelse är viktigt. +- Förutsättningar och bibliotekskonfiguration (Aspose PDF för Java 23.10 eller senare). +- Hur man **skapar tillgänglig PDF** från grunden, steg för steg. +- Sätt att **lägga till tillgänglighetstaggar i PDF** utöver det grundläggande anropet `setTagDocumentStructure`. +- Tips för att testa resultatet och felsöka vanliga problem. + +När du har gått igenom den här guiden kommer du att kunna generera PDF‑filer som klarar WCAG 2.1 AA‑kontroller och samtidigt ser professionella ut. + +--- + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Moderna språkfunktioner och bättre Unicode‑hantering. | +| **Aspose PDF for Java** (v23.10 eller nyare) | Tillhandahåller klassen `PdfSaveOptions` och stöd för taggning. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, etc.) | För enkel kompilering och felsökning. | +| **Write permission** to a folder where the PDF will be saved | Anropet `doc.save` kräver en skrivbar sökväg. | + +Om du ännu inte har lagt till Aspose PDF i ditt projekt, lägg till följande Maven‑beroende i din `pom.xml`: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** Använd den senaste versionen; nyare releaser förbättrar taggningsnoggrannheten och lägger till språk‑specifika tillgänglighetsfunktioner. + +## Steg 1: Ställ in dokumentets skelett + +Först skapar vi ett nytt `Document`‑objekt. Tänk på det som en tom duk som senare kommer att hålla de taggar vi behöver för tillgänglighet. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Varför detta är viktigt:** Utan något innehåll finns det inget att tagga. Att lägga till även ett enkelt `TextFragment` ger taggningsmotorn något att arbeta med, och den skapar automatiskt en `

`‑tagg (paragraf) när vi senare aktiverar strukturtaggning. + +## Steg 2: Skapa PDF‑spara‑alternativ (kärnan i taggning) + +Nu förbereder vi alternativen som instruerar Aspose PDF att bädda in ett logiskt strukturtträd i filen. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Anropet `setTagDocumentStructure(true)` är **aktivera PDF‑taggning**‑omkopplaren. När den är sann bygger biblioteket ett taggträd som speglar den visuella layouten, vilket gör PDF‑filen läsbar för hjälpmedel. + +> **Obs:** Detta är det enklaste sättet att **hur man skapar en taggad pdf**. För mer detaljerad kontroll (t.ex. att ange språk eller anpassade taggar) kan du utforska `pdfOptions.setTagLanguage("en-US")` och `pdfOptions.setTagStructureTreeRoot(...)`. + +## Steg 3: Spara den tillgängliga PDF‑filen + +Till sist skriver vi dokumentet till disk med de alternativ vi just konfigurerade. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +När `doc.save` är klar hittar du `accessible.pdf` i mappen `output`. Öppna den i Adobe Acrobat och titta på **File → Properties → Description → Tags** – du bör se ett ifyllt taggträd. + +## Hur man taggar PDF för tillgänglighet – Utöver grunderna + +Det trestegs‑exemplet ovan **lägger redan till tillgänglighetstaggar i PDF**, men dokument i verkligheten behöver ofta lite mer finjustering. Här är några förbättringar du kan lägga till: + +### 1. Ange dokumentets språk + +Skärmläsare använder språk‑attributet för att uttala texten korrekt. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Ange en titel och ett ämne + +Metadata hjälper hjälpmedel att ge kontext innan användaren ens öppnar filen. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Tagga bilder med alternativ text + +Om du bäddar in bilder behöver de `alt`‑beskrivningar. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Markera tabellrubriker + +Tabeller är ökända för att förvirra läsare om du inte markerar rubrikrader. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Dessa extra steg gör din PDF inte bara *tekniskt* taggad, utan verkligen **tillgänglig** för en mångsidig publik. + +## Vanliga fallgropar när du aktiverar PDF‑taggning + +| Symptom | Trolig orsak | Åtgärd | +|---------|--------------|-----| +| Taggar saknas i Acrobat | `setTagDocumentStructure` lämnades som `false` | Se till att du anropar `pdfOptions.setTagDocumentStructure(true)`. | +| Fel läsordning | Komplex layout utan explicita taggar | Använd `pdfOptions.setTagStructureTreeRoot(...)` för att definiera en anpassad ordning. | +| Bilder läses som “image” utan beskrivning | Ingen alternativ text angiven | Anropa `image.getAlternativeText().setValue("...")`. | +| Språk känns inte igen | `setTagLanguage` utelämnad eller fel locale | Ange en BCP‑47 språkkod (`en-US`, `fr-FR`). | + +Att vara medveten om dessa problem sparar dig timmar av felsökning senare. + +## Verifiera resultatet – Vad du kan förvänta dig + +Efter att ha kört programmet, öppna `output/accessible.pdf` i Adobe Acrobat Reader: + +1. **Tagg‑panel** (`View → Show/Hide → Navigation Panes → Tags`) bör visa en hierarki som `/Document → /Part → /Sect → /Para`. +2. **Läsordning** bör följa den visuella flödet (text först, sedan bilder). +3. **Skärmläsare** (NVDA, VoiceOver) kommer att läsa “Hello, accessible PDF!” istället för bara “Page 1”. + +Om någon av dessa punkter saknas, dubbelkolla stegen ovan – särskilt anropet `setTagDocumentStructure`. + +## Fullt fungerande exempel (Klar att kopiera och klistra in) + + + +## Relaterade handledningar + +- [Skapa tillgänglig PDF från Word – Konvertera till PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Skapa tillgänglig PDF från DOCX – Komplett guide](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Hur man sparar dokument som PDF med Aspose.Words för Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/swedish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/swedish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..f69b4bf2f7 --- /dev/null +++ b/words/swedish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Infoga bilder som base64 när du konverterar docx till markdown med Aspose.Words + för Java. Lär dig att konvertera Word till markdown, spara Word som markdown och + hantera bilder. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: sv +og_description: Bädda in bilder som base64 när du konverterar docx till markdown med + Aspose.Words för Java. Komplett guide för att konvertera Word till markdown och + spara Word som markdown. +og_title: Bädda in bilder som Base64 vid konvertering av DOCX till Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Bädda in bilder som Base64 vid konvertering av DOCX till Markdown +url: /sv/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bädda in bilder som Base64 när du konverterar DOCX till Markdown + +Har du någonsin funderat på hur man **bäddar in bilder som base64** medan du **konverterar docx till markdown**? Du är inte ensam—utvecklare frågar ständigt hur man behåller bilder inline utan att hantera separata filer. Den goda nyheten är att Aspose.Words for Java gör det enkelt: du kan konvertera ett Word-dokument till Markdown och automatiskt bädda in varje bild som en Base64-sträng. + +I den här handledningen går vi igenom hela processen—från att läsa in en `.docx` som innehåller bilder, till att konfigurera en `MarkdownSaveOptions`-callback som gör det tunga arbetet, och slutligen spara resultatet som en ren `.md`-fil. När du är klar vet du exakt hur du **konverterar word till markdown**, **konverterar bilder till base64**, och **sparar word som markdown** utan att lämna kvar lösa bildmappar. Inga externa verktyg, ingen manuell efterbehandling—bara ren Java‑kod som du kan släppa in i vilket projekt som helst. + +## Vad du behöver + +- **Java 17** (eller någon nyare JDK) – koden använder lambda‑syntax, men du kan anpassa den till äldre versioner. +- **Aspose.Words for Java**-biblioteket (senaste versionen 2026). Lägg till Maven‑beroendet eller JAR‑filen i din classpath. +- En exempel **DOCX**‑fil som innehåller minst en bild. +- En IDE eller en enkel textredigerare—Visual Studio Code, IntelliJ IDEA, eller till och med `vim` fungerar. + +Om du redan har detta, bra—låt oss dyka rakt in. + +## Steg 1: Läs in Word‑dokumentet + +Först skapar vi en `Document`‑instans som pekar på källfilen. Detta är samma steg oavsett om du **konverterar docx till markdown** eller bara läser filen för andra ändamål. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Varför detta är viktigt:** `Document`‑objektet är startpunkten för varje Aspose‑operation. Det innehåller hela Word‑strukturen—inklusive bilder, tabeller och stilar—så att den senare callbacken kan inspektera varje resurs. + +## Steg 2: Skapa MarkdownSaveOptions och registrera en Resource‑Saving‑callback + +Magin finns i `MarkdownSaveOptions`. Genom att fästa en `IResourceSavingCallback` får vi kontroll över hur varje extern resurs (som en bild) skrivs. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Varför använda `setSaveToMemory(true)`? + +När `saveToMemory` är true skriver Aspose bildbytarna till ett minnesström istället för en fil. Markdown‑exportören konverterar sedan det strömmen till en Base64‑sträng och infogar den direkt i Markdown‑bildtaggen: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Det är kärnan i **bädda in bilder som base64**. + +## Steg 3: Spara dokumentet som Markdown + +Nu när callbacken är på plats är det sista steget helt enkelt att anropa `save`. Det är här vi faktiskt **konverterar word till markdown** och, på grund av callbacken, också **konverterar bilder till base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Resultat:** `out.md` innehåller Markdown‑text med varje bild representerad som en `data:`‑URI. Inga extra bildfiler skapas på disk, så mappen förblir prydlig. + +## Steg 4: Verifiera resultatet och vanliga fallgropar + +Öppna den genererade `out.md` i någon Markdown‑visare (VS Code, GitHub eller en statisk webbplatsgenerator). Du bör se något liknande: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Felsökningschecklista + +| Problem | Trolig orsak | Åtgärd | +|-------|--------------|-----| +| Bild visas som en trasig länk | `setSaveToMemory` utelämnades | Säkerställ att `args.setSaveToMemory(true);` finns i callbacken | +| Base64‑sträng är avklippt | Fel kodning på utdatafil | Spara Markdown med UTF‑8 (standard för Aspose) | +| Oväntade filnamn | `setKeepResourceOriginalName(true)` | Håll den `false` för att tvinga den anpassade namngivningslogiken | + +## Steg 5: Avancerade varianter (valfritt) + +### Konvertera endast utvalda bilder + +Om du bara vill bädda in vissa bilder (t.ex. de som är större än 100 KB), lägg till en storlekskontroll: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Använd ett annat bildformat + +`ResourceSavingArgs` ger dig de råa bytarna, så du kan åter‑koda JPEG‑bilder som PNG innan du bäddar in dem—användbart när mål‑Markdown‑klienten föredrar PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Dessa justeringar visar hur flexibel **bädda in bilder som base64**‑metoden är när du **konverterar docx till markdown**. + +## Slutsats + +Du har precis lärt dig hur du **bäddar in bilder som base64** medan du **konverterar docx till markdown** med Aspose.Words for Java. Genom att koppla en enkel `IResourceSavingCallback` sköter biblioteket allt tungt arbete: det **konverterar word till markdown**, **konverterar bilder till base64**, och slutligen **sparar word som markdown** med ett enda `save`‑anrop. + +Känn dig fri att experimentera—prova olika bildfiltreringsregler, byt till HTML‑utmatning, eller kedja detta steg med en statisk webbplatsgenerator. Samma mönster fungerar för andra format (HTML, EPUB) också, så du kan återanvända callbacken där du behöver inline‑resurser. + +**Nästa steg:** +- Utforska `HtmlSaveOptions` för HTML‑med‑Base64‑bilder. +- Kombinera detta med en CI‑pipeline för att automatisera dokumentationsgenerering. +- Fördjupa dig i Aspose’s `DocumentVisitor` om du behöver ännu finare kontroll över konverteringsprocessen. + +Lycka till med kodandet, och njut av dina rena, självständiga Markdown‑filer! + +## Relaterade handledningar + +- [Hur man bäddar in bilder i Markdown när man konverterar DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Konvertera docx till markdown – Exportera matematiska ekvationer till LaTeX med Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Spara bilder från Word – Aspose.Words för Java‑guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/swedish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..0788904e51 --- /dev/null +++ b/words/swedish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-26 +description: Exportera docx till txt med Java och Aspose.Words. Lär dig hur du konverterar + docx till text, bevarar Unicode och exporterar Word som txt på några få steg. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: sv +og_description: Exportera docx till txt i Java. Denna handledning visar hur man konverterar + docx till text, behåller vanlig Unicode‑text och exporterar Word som txt på ett + effektivt sätt. +og_title: Exportera docx till txt med Java – Komplett guide +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Exportera docx till txt med Java – Komplett programmeringsguide +url: /sv/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exportera docx till txt med Java – Komplett programmeringsguide + +Har du någonsin behövt **exportera docx till txt** men oroat dig för att förlora specialtecken? Du är inte ensam. När du konverterar Word-dokument till rena textfiler kan Unicode‑symboler, tabeller och till och med enkel formatering försvinna som magi. + +I den här guiden går vi igenom ett pålitligt sätt att **exportera docx till txt** med Aspose.Words för Java, bevara varje Unicode‑tecken och hålla tabelllayouten läsbar. I slutet kommer du också att veta hur man **konverterar docx till text**, **konverterar word till text**, och till och med **exporterar word som txt** utan problem. + +## Vad den här handledningen täcker + +* Installera Aspose.Words i ett Java‑projekt +* Ladda en DOCX‑fil och förbereda den för ren textutmatning +* Konfigurera stöd för **plain text unicode** via `TxtSaveOptions` +* Valfria knep för att hålla tabeller läsbara i den resulterande `.txt`‑filen +* Spara filen och verifiera resultatet + +Inga externa skript, inga mystiska kommandoradsverktyg—bara ren Java‑kod som du kan lägga in i vilket Maven‑ eller Gradle‑projekt som helst. + +> **Varför bry sig?** Textfiler är lätta, versionskontrollvänliga och perfekta för sök‑indexering eller efterföljande bearbetningspipelines. Om du någonsin har försökt `cat` en Word‑fil och fått nonsens, löser den här handledningen problemet. + +## Exportera docx till txt – Översikt + +Innan vi dyker ner i koden, låt oss klargöra terminologin. **Exportera docx till txt** betyder att ta ett Microsoft Word `.docx`‑paket och skriva dess textinnehåll till en enkel `.txt`‑fil. Till skillnad från en PDF‑konvertering tar en textexport bort formatering men kan behålla radbrytningar, styckemarkörer och—om du konfigurerar rätt—Unicode‑tecken såsom emojis, accentuerade bokstäver eller asiatiska skript. + +Aspose.Words gör detta smärtfritt eftersom det abstraherar Word‑filformatet och erbjuder en `TxtSaveOptions`‑klass där du kan ange kodning, tabellhantering och mer. + +### Förutsättningar + +* Java 11 eller nyare (API:t fungerar med Java 8+, men vi antar en recent JDK) +* Aspose.Words för Java JAR (tillgänglig via Maven Central) +* En exempel‑fil `unicode.docx` som innehåller olika Unicode‑tecken—tänk “こんにちは”, “😊”, och en enkel tabell + +Om du har dem, låt oss börja. + +## Steg 1: Ladda DOCX‑filen (Konvertera docx till text) + +Det första du behöver göra är att läsa källdokumentet till minnet. Det är här **konvertera docx till text**‑processen officiellt börjar. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Varför detta är viktigt:* `Document` är Aspose.Words representation av en Word‑fil. Genom att ladda den får du åtkomst till alla dess stycken, tabeller och även dolda element. Om filen inte hittas kastar Aspose ett tydligt `FileNotFoundException`, så du vet omedelbart vad som gick fel. + +## Steg 2: Konfigurera TxtSaveOptions för Unicode (Plain text unicode) + +Textfiler är bara byte‑strömmar, så du måste tala om för Java vilken teckenuppsättning som ska användas. UTF‑8 är de‑facto‑standard för **plain text unicode** eftersom den kan koda varje Unicode‑kodpunkt. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Proffstips:** Om du hoppar över anropet `setEncoding` använder Aspose plattformens standard‑charset, vilket på många Windows‑maskiner är Windows‑1252. Den standarden kommer tyst att ta bort tecken som “ß” eller “—”. + +## Steg 3: Bevara tabellayout (Valfritt, men praktiskt för läsbarhet) + +När du **exporterar word som txt**, plattar tabeller vanligtvis ut till en enda textrad, vilket gör dem oläsliga. Aspose.Words erbjuder en enkel flagga för att behålla den visuella strukturen. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*När du ska använda den:* Om ditt käll‑DOCX innehåller fakturor, scheman eller någon rutnäts‑liknande data, kommer aktivering av `PreserveTableLayout` att infoga tabbar och radbrytningar så att den resulterande filen fortfarande liknar en tabell. Om du inte behöver detta kan du utelämna raden och få en mer kompakt utdata. + +## Steg 4: Spara dokumentet som ren text (Exportera word som txt) + +Nu är det tunga arbetet gjort—skriv bara byte‑erna till disk. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +När programmet körs skapas `plain.txt` i samma mapp. Öppna den med vilken textredigerare som helst (Notepad++, VS Code, till och med `cat` i en terminal) så ser du: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Lägg märke till hur den japanska hälsningen och smileyn överlevde, och tabellen behöll sina kolumner tack vare `PreserveTableLayout`. Det är kärnan i en ren **export av docx till txt**. + +## Steg 5: Verifiera utdata (Kontroll av konvertera word till text) + +En snabb kontroll förhindrar tyst dataförlust. Här är några sätt att bekräfta att du verkligen **konverterar word till text** korrekt: + +1. **Kontroll av kontrollsumma** – beräkna en SHA‑256‑hash av `.txt`‑filen före och efter en rundresa‑konvertering (txt → docx → txt) för att säkerställa stabilitet. +2. **Sök efter Unicode‑markörer** – använd `grep` eller IDE:s sök‑i‑fil för att hitta tecken som “😊”. +3. **Öppna i flera redigerare** – vissa gamla Windows‑Notepad‑versioner tolkar fortfarande UTF‑8 utan BOM felaktigt; att öppna filen i VS Code bekräftar korrekt kodning. + +Om någon av dessa kontroller misslyckas, dubbelkolla att `saveOptions.setEncoding(StandardCharsets.UTF_8)` finns med och att ditt käll‑DOCX verkligen innehåller Unicode‑text. + +## Vanliga fallgropar & hur man undviker dem + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Saknade tecken** | Standard‑system‑charset (t.ex. Windows‑1252) släpper icke‑ASCII‑tecken. | Ange explicit UTF‑8 via `saveOptions.setEncoding`. | +| **Tabeller blir en enda rad** | `PreserveTableLayout` är kvar på standardvärdet `false`. | Anropa `saveOptions.setPreserveTableLayout(true)`. | +| **Fil ej hittad** | Fel sökväg eller saknade läsbehörigheter. | Använd absoluta sökvägar eller `Paths.get(...)` med korrekt felhantering. | +| **Prestandaförsämring på stora dokument** | Laddar hela dokumentet i minnet. | Strömma dokumentet i delar med `DocumentBuilder` om du bara behöver specifika sektioner. | + +## Bonus: Exportera flera DOCX‑filer i ett batch‑jobb + +Om du behöver **konvertera docx till text** för en hel mapp, omslut logiken i en loop: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Detta kodstycke **exporterar docx till txt** för varje fil i katalogen, vilket sparar dig timmar av manuellt arbete. + +## Slutsats + +Du har precis lärt dig hur man **exporterar docx till txt** med Java, vilket säkerställer att varje Unicode‑tecken förblir intakt, tabeller förblir läsbara och hela processen är repeterbar. Genom att konfigurera `TxtSaveOptions` för UTF‑8 och eventuellt bevara tabellayouten kan du på ett pålitligt sätt **konvertera docx till text**, **konvertera word till text**, och **exportera word som txt** för alla efterföljande arbetsflöden. + +Redo för nästa utmaning? Prova att exportera till andra rena textformat som markdown (`.md`) eller CSV, eller utforska Aspose.Words PDF‑konverteringsmöjligheter. Samma principer—explicit kodning, bevarande av layout och grundlig verifiering—gäller överallt. + +Lycklig kodning, och må dina textfiler alltid vara Unicode‑rika! + +--- + +![Diagram som visar export av docx till txt-pipelinen](/images/export-docx-to-txt-pipeline.png){alt="diagram för export av docx till txt-pipelinen"} + +## Relaterade handledningar + +- [Konvertera Docx till Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Konvertera DOCX till PDF i Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Konvertera docx till markdown – Exportera matematiska ekvationer till LaTeX med Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/swedish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..82f8c665b8 --- /dev/null +++ b/words/swedish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-05-26 +description: Spara dokument som PDF med Aspose.Words Java och lägg till tillgänglighet + i PDF. Lär dig konvertera docx till PDF, tagga horisontella linjer och säkerställ + PDF/UA‑2‑efterlevnad. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: sv +og_description: Spara dokument som PDF med Aspose.Words Java samtidigt som du lägger + till tillgänglighet i PDF. Steg‑för‑steg‑guide för att konvertera docx till PDF + och märka horisontella linjer för PDF/UA‑2‑efterlevnad. +og_title: Spara dokument som PDF med Aspose.Words Java – Tillgänglighet gjort enkelt +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Spara dokument som PDF med Aspose.Words Java – Fullständig guide för tillgänglighet +url: /sv/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + +Har du någonsin funderat på hur man **save document as PDF** samtidigt som du behåller tillgänglighet för skärmläsare? Du är inte ensam. Många utvecklare behöver *convert docx to pdf* och ändå uppfylla PDF/UA‑2‑standarder, särskilt när källan innehåller horisontella linjer som måste taggas korrekt. I den här handledningen går vi igenom de exakta stegen för att **save document as PDF** med Aspose.Words för Java, automatiskt **add accessibility to PDF**, och säkerställa att varje horisontell linje är **tagged** som ett artefakt. + +Vi börjar med ett rent Java‑projekt, laddar en DOCX som redan har horisontella linjer, konfigurerar PDF‑spara‑alternativen för PDF/UA‑2‑efterlevnad, och skriver slutligen ut en fullt tillgänglig PDF. När du är klar kommer du kunna **save document as pdf** med förtroende för att den klarar tillgänglighetskontroller. + +## Prerequisites + +Innan vi dyker ner, se till att du har: + +- Java 8 eller nyare installerat (handledningen testades på JDK 17). +- Maven 3.6+ (eller Gradle om du föredrar) för att hantera beroenden. +- En giltig Aspose.Words för Java‑licens (gratis provversion fungerar, men en licens tar bort utvärderingsvattenstämplar). +- En DOCX‑fil (`input.docx`) som innehåller minst en horisontell linje — tänk på en enkel linjeskiljare som du kan lägga till i Word. + +> **Pro tip:** Om du inte har en DOCX till hands, skapa bara ett nytt Word‑dokument, skriv några stycken, infoga *Insert → Horizontal Line*, spara som `input.docx` och placera den i en mapp du väljer. + +## Step 1: Set Up the Maven Project + +Först, skapa ett nytt Maven‑projekt (eller lägg till i ett befintligt). `pom.xml` behöver Aspose.Words‑beroendet: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** Att lägga till `aspose-words`‑artefakten är det första steget för att *convert docx to pdf*. Utan den kommer kompilatorn inte att känna igen `Document`, `PdfSaveOptions` och andra viktiga klasser. + +## Step 2: Load the Source DOCX Containing Horizontal Rules + +Nu skriver vi en liten Java‑klass som laddar DOCX‑filen. Detta är där delen **tag horizontal rules** börjar — Aspose.Words behandlar automatiskt en horisontell linje som ett stycke med en kant, men vi låter PDF/UA‑motorn hantera taggningen. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Observera att vi ännu inte har sparat något — vi **loading** bara DOCX‑filen, vilket är den första halvan av *convert docx to pdf*. `Document`‑objektet innehåller nu allt Word‑innehåll, inklusive eventuella horisontella linjer du har infogat. + +## Step 3: Configure PDF Save Options for PDF/UA‑2 Compliance + +Magin med **adding accessibility to PDF** finns i `PdfSaveOptions`. Genom att sätta efterlevnadsnivån till `PDF_UA_2` kommer Aspose.Words att: + +1. Tagga strukturella element (rubriker, tabeller osv.). +2. Markera dekorativa element — som horisontella linjer — som *artifacts*, så att skärmläsare ignorerar dem. +3. Infoga nödvändig PDF/UA‑metadata. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** Utan `PDF_UA_2` kan den resulterande PDF‑filen fortfarande vara läsbar men klarar inte automatiska tillgänglighetsvaliderare. Kravet **tag horizontal rules** uppfylls automatiskt eftersom PDF/UA behandlar dem som *artifacts* när efterlevnadsflaggan är på. + +## Step 4: Save the Document as a PDF + +Nu **save document as pdf** vi äntligen. Denna enda rad gör det tunga arbetet — konverterar DOCX, applicerar tillgänglighetstaggar och skriver filen till disk. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Kör klassen (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) så får du ett bekräftelsemeddelande. Öppna den resulterande `ua_compliant.pdf` i Adobe Acrobat och kontrollera **File → Properties → Description → PDF/A, PDF/UA** — du bör se “PDF/UA‑2” listat. + +### Expected Output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Öppna PDF‑filen, och du kommer märka: + +- Dokumenttexten är markerbar och sökbar. +- Den horisontella linjen är osynlig för skärmläsare (behandlad som ett artefakt). +- PDF‑filen klarar grundläggande PDF/UA‑valideringsverktyg (t.ex. PAC 3). + +## Step 5: Verify Accessibility – Quick Checklist + +Även om Aspose.Words gör det mesta av arbetet är det god praxis att verifiera resultatet. + +| Kontroll | Hur man verifierar | +|---|---| +| **Document title** | Öppna Acrobat → File → Properties → Title‑fältet (bör matcha `pdfOptions.setTitle`). | +| **Artifact tagging** | Använd Acrobats “Reading Order”-verktyg. Horisontella linjer bör visas som *Artifact* (grå). | +| **Logical reading order** | Kör “Accessibility Checker” i Acrobat; säkerställ att inga strukturella fel finns. | +| **Tagged PDF** | I Acrobat, titta under panelen “Tags” – du bör se en hierarki (Document → Section → Paragraph, etc.). | +| **PDF/UA compliance** | Acrobat visar “PDF/UA‑2” under fliken “Standards”. | + +Om någon av dessa kontroller misslyckas, dubbelkolla att du använder den senaste versionen av Aspose.Words och att `setCompliance(PdfCompliance.PDF_UA_2)` är korrekt tillämpad. + +## Common Pitfalls & How to Avoid Them + +1. **Missing License** – Den provversionen lägger till en vattenstämpel som kan bryta PDF/UA‑validering. Applicera din licens tidigt i `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – En `FileNotFoundException` stoppar konverteringen. Använd absoluta sökvägar eller placera DOCX‑filen i projektets rot och referera den med `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – PDF/UA‑stöd lades till i version 22.9. Uppgradera till den senaste releasen för att undvika saknade funktioner. +4. **Horizontal Rule as Image** – Om du infogade linjen som en bild istället för en inbyggd Word‑horisontell linje, behandlar Aspose den som en vanlig bild, inte ett artefakt. Ersätt bilden med Words inbyggda *Horizontal Line* för korrekt taggning. + +## Extending the Solution – What If You Need More? + +- **Custom Tags**: Om du har andra dekorativa element (t.ex. dekorativa ikoner) kan du manuellt markera dem som artefakter med `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Loopa över en mapp med DOCX‑filer och batch‑konvertera dem, återanvänd samma `PdfSaveOptions`‑instans för bättre prestanda. +- **Adding a Language Tag**: För flerspråkiga PDF‑filer, sätt `pdfOptions.setLanguage("en-US")` för att hjälpa hjälpmedel att välja rätt röst. + +## Full Working Example (All Code Together) + +Nedan är det kompletta, körbara Java‑programmet. Kopiera‑klistra in det i din IDE, justera sökvägarna och kör. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Kör det, öppna den genererade PDF‑filen, så har du en ren, tillgänglig fil redo för distribution. + +## Conclusion + +Vi har just demonstrerat hur man **save document as pdf** med Aspose.Words för Java samtidigt som man automatiskt **add accessibility to pdf** och **tag horizontal rules** som artefakter. De viktigaste slutsatserna: + +- Använd `PdfSaveOptions` med `PDF_UA_2`‑efterlevnad för att möta tillgänglighetsstandarder. +- Att ladda en DOCX och anropa `doc.save(..., pdfOptions)` är allt du behöver för att **convert docx to pdf**. +- Horisontella linjer hanteras automatiskt — ingen extra kod behövs, vilket uppfyller kravet **tag horizontal rules**. +- Metoden är fullt **aspose convert docx pdf**‑kompatibel, fungerar med den senaste biblioteksversionen och producerar en valideringsklar PDF. + +Redo för nästa utmaning? Prova att lägga till anpassad metadata, bädda in typsnitt eller batch‑processa en hel mapp med DOCX‑filer. Varje sådan utökning bygger på samma grund som vi lagt upp här. + +Har du frågor om PDF/UA‑efterlevnad, licensiering eller hantering av andra Word‑element? Lämna en kommentar eller kolla Asposes officiella dokumentation — det finns en mängd exempel att utforska. Lycka till med kodandet, och njut av att skapa tillgängliga PDF‑filer! + +![spara dokument som pdf med Aspose.Words Java – exempel på tillgänglig PDF](placeholder-image.png "spara dokument som pdf med Aspose.Words Java") + +## Related Tutorials + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) → **Hur man sparar dokument som pdf med Aspose.Words för Java** +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) → **Hur man konverterar Word till PDF med Aspose.Words för Java** +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) → **aspose word to pdf – Konvertera DOCX till PDF i Java** + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/swedish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..1aeb05d575 --- /dev/null +++ b/words/swedish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-26 +description: Spara Word som markdown och upptäck hur du exporterar matematiska ekvationer + till LaTeX med Aspose.Words för Java. Konvertera Word‑ekvationer till LaTeX på bara + några rader. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: sv +og_description: Spara Word som markdown och lär dig hur du exporterar matematiska + ekvationer till LaTeX med Aspose.Words för Java. En komplett, körbar guide. +og_title: Spara Word som markdown – Exportera matematik till LaTeX med Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Spara Word som markdown – Exportera matematik till LaTeX med Java +url: /sv/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Spara Word som markdown – Exportera matematik till LaTeX med Java + +Har du någonsin behövt **spara word som markdown** men oroat dig för att dina ekvationer skulle bli en rörig röra? Du är inte ensam. I den här guiden går vi igenom **hur man exporterar matematik** från en `.docx`-fil direkt till LaTeX medan resten av dokumentet blir ren Markdown. + +Vi kommer att gå igenom allt från att installera Aspose.Words‑biblioteket till att verifiera den slutliga `out.md`‑filen. I slutet kommer du att kunna **konvertera word equations latex** med ett enda metodanrop, och du kommer att förstå de små nyanserna som gör konverteringen pålitlig. + +--- + +## Vad du behöver + +- **Java 8+** – koden körs på vilken recent JDK som helst. +- **Aspose.Words for Java** – antingen Maven/Gradle‑beroendet eller JAR‑filen om du föredrar manuell installation. +- Ett Word‑dokument (`math.docx`) som innehåller minst en Office Math‑ekvation. +- En IDE eller vanlig `javac`/`java`‑kommandorad – vad du än föredrar. + +Om du redan har dem, bra. Om inte, visar nästa avsnitt exakt hur du får biblioteket in i ditt projekt. + +## Spara Word som markdown – Steg 1: Lägg till Aspose.Words i ditt projekt + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose erbjuder en gratis tillfällig licens för testning. Lägg `license.xml`‑filen i din resources‑mapp och anropa `License license = new License(); license.setLicense("license.xml");` innan du laddar något dokument. + +När beroendet är löst är du redo att skriva konverteringskoden. + +## Hur man exporterar matematikekvationer till LaTeX + +Det tunga arbetet utförs av `MarkdownSaveOptions`. Genom att byta dess `OfficeMathExportMode` till `LATEX` renderas varje Office Math‑objekt som ett LaTeX‑fragment i Markdown‑utdata. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Varför detta fungerar + +- **`Document`** är Asposes ingångspunkt; den abstraherar `.docx`‑filen och ger dig åtkomst till varje nod, inklusive ekvationer. +- **`MarkdownSaveOptions`** talar om för biblioteket *hur* du vill ha utdata. Standardbeteendet är att rendera ekvationer som bilder, vilket motverkar syftet med ett textbaserat format. +- **`OfficeMathExportMode.LATEX`** tvingar motorn att översätta varje `OfficeMath`‑nod till dess LaTeX‑ekvivalent, vilket Markdown‑tolkare (som GitHub eller Jekyll) kan rendera när de kombineras med ett MathJax‑plugin. + +## Konvertera Word‑ekvationer LaTeX – Steg 2: Verifiera Markdown‑utdata + +Efter att ha kört programmet, öppna `out.md`. Du bör se något liknande detta: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Obs:** LaTeX‑fragmenten är omslutna av `$…$` för inline‑matematik och `$$…$$` för block‑matematik. Detta är den standardsyntax som de flesta statiska webbplatsgeneratorer förstår när MathJax är aktiverat. + +Om du föredrar att ekvationerna bara ska vara inline kan du justera `MarkdownSaveOptions` ytterligare: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx till markdown latex – Steg 3: Edge Cases & Vanliga fallgropar + +| Situation | Vad att se upp för | Lösning | +|-----------|-------------------|-----| +| **Komplexa nästlade ekvationer** | Aspose kan generera extra klammerparenteser `{}` som vissa tolkar bokstavligt. | Post‑processa Markdown med ett enkelt regex för att kollapsa `{{` → `{`. | +| **Saknad MathJax på målwebbplatsen** | Ekvationer visas som rå LaTeX‑kod. | Lägg till `` i din HTML‑mall. | +| **Stora dokument** | Minnesanvändningen skjuter i höjden eftersom hela dokumentet laddas på en gång. | Använd `LoadOptions.setLoadFormat(LoadFormat.DOCX)` och överväg att bearbeta sidor i batcher om du får `OutOfMemoryError`. | +| **Licens ej satt** | Du får en varning och utdata kan bli vattenmärkt. | Läs in licensen tidigt i `main` som visas i Maven‑tipset ovan. | + +## Spara Word som markdown – Fullt fungerande exempel + +Nedan är en självständig klass som du kan kopiera och klistra in i vilket Java‑projekt som helst. Byt bara ut `YOUR_DIRECTORY` mot sökvägen till dina filer. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Kör programmet (`java MathToLatexMarkdown`) så får du ett konsolmeddelande som bekräftar att det lyckades. Öppna `out.md` i någon redigerare – ekvationerna bör vara rena LaTeX‑snuttar redo att renderas. + +## Förväntad utsnitt av resultatet + +![spara word som markdown-utdata med LaTeX‑ekvationer](https://example.com/images/markdown-latex-output.png "spara word som markdown-utdata med LaTeX‑ekvationer") + +*Bilden visar ett utdrag av den genererade Markdown där ekvationen `\int_{a}^{b} f(x)\,dx` är omsluten av `$$`.* + +## Slutsats + +Vi har just demonstrerat hur man **sparar word som markdown** samtidigt som varje Office Math‑ekvation bevaras som inbyggd LaTeX. Nyckelsteget var att konfigurera `MarkdownSaveOptions` med `OfficeMathExportMode.LATEX`, vilket förvandlar en vanlig Word‑till‑Markdown‑pipeline till ett fullt matematik‑medvetet konverteringsverktyg. + +Nu kan du: + +1. **Hur man exporterar matematik** från vilken `.docx` som helst utan att förlora noggrannhet. +2. **Konvertera word equations latex** för statiska webbplatsgeneratorer, dokumentation eller akademiska bloggar. +3. Utöka metoden för att batch‑processa många filer, integrera med CI‑pipelines eller till och med bygga en liten webbtjänst. + +Om du är nyfiken på nästa frontier, prova att kombinera detta med **docx to markdown latex** för bildtunga dokument, eller utforska Asposes `HtmlSaveOptions` för en webb‑klar HTML‑version. Möjligheterna är oändliga—experimentera, bryt saker, och dela sedan dina upptäckter med communityn. + +Har du frågor eller en knepig ekvation som inte renderades som förväntat? Lämna en kommentar nedan, och lycka till med kodandet! + +## Relaterade handledningar + +- [Hur man exporterar LaTeX från Word: Konvertera DOCX till Markdown & spara som PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Konvertera docx till markdown – Exportera matematikekvationer till LaTeX med Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Hur man konverterar Word till PDF med Aspose.Words för Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/swedish/java/document-loading-and-saving/_index.md index 96d078dce2..5ac12c73cc 100644 --- a/words/swedish/java/document-loading-and-saving/_index.md +++ b/words/swedish/java/document-loading-and-saving/_index.md @@ -133,6 +133,9 @@ Lär dig hur du upptäcker dokumentformat i Java med Aspose.Words. Identifiera D ### [Återställ korrupt docx – Komplett guide för att reparera och bearbeta dokument](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) Lär dig hur du reparerar skadade DOCX‑filer och bearbetar dem med Aspose.Words för Java. +### [Öppna korrupt Word-dokument – Ställ in återställningsläge i Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Lär dig hur du öppnar skadade Word‑dokument och aktiverar återställningsläge med Aspose.Words för Java för att reparera filer. + ### [Fånga varningar om teckensnittssubstitution i Java med Aspose.Words – Komplett guide](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## Vanliga frågor diff --git a/words/swedish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/swedish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..6b98d1411a --- /dev/null +++ b/words/swedish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: Öppna korrupt Word-dokument i Java med Aspose.Words. Lär dig hur du ställer + in återställningsläge och på ett pålitligt sätt återställer korrupta Word-filer. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: sv +og_description: Öppna korrupt Word-dokument i Java med Aspose.Words. Denna guide visar + hur du ställer in återställningsläge och återställer korrupta Word-filer effektivt. +og_title: Öppna korrupt Word-dokument – Ställ in återställningsläge i Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Öppna korrupt Word-dokument – Ställ in återställningsläge i Java +url: /sv/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Öppna korrupt Word-dokument – Ställ in återhämtningsläge i Java + +Har du någonsin försökt öppna ett korrupt Word-dokument och sett programmet kvävas av ett undantag? Du är inte ensam—de där trasiga .docx‑filerna kan vara ett riktigt huvudvärk. Den goda nyheten är att Aspose.Words for Java ger dig fin‑granulär kontroll så att du kan **open corrupted word document** utan att appen kraschar, och till och med bestämma om du vill ha varningar, tyst återhämtning eller ett hårt avslag. + +I den här handledningen går vi igenom hela processen: från att skapa rätt `LoadOptions`, till att välja rätt **set recovery mode**‑värde, och slutligen bekräfta att dokumentet faktiskt har laddats. I slutet kommer du att veta **how to recover corrupted word file** programatiskt, utan att behöva kopiera‑klistra manuellt. + +> **Vad du behöver** +> * Java 8 eller nyare (API:et fungerar även med Java 11) +> * Aspose.Words for Java 23.9 (eller den senaste versionen) +> * En exempelkorrupt .docx‑fil—byt bara namn på en giltig fil för att simulera korruption om du inte har en till hands + +Låt oss dyka in. + +## Öppna korrupt Word-dokument – Steg‑för‑steg‑översikt + +Nedan är den övergripande flödet vi kommer att implementera: + +1. **Create `LoadOptions`** – detta objekt talar om för Aspose.Words hur det ska bete sig när det stöter på problem. +2. **Set recovery mode** – välj `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` eller `REJECT_CORRUPTED`. +3. **Load the document** med de konfigurerade alternativen. +4. **Verify** att laddningen lyckades (t.ex. skriv ut sidantal). + +Varje steg förklaras i detalj, med kodsnuttar som du kan kopiera‑klistra direkt in i din IDE. + +## Ställ in återhämtningsläge för olika scenarier + +Aspose.Words definierar tre återhämtningsstrategier i `LoadOptions.RecoveryMode`: + +| Läge | Beteende | När den ska användas | +|------|----------|----------------------| +| `RECOVER_WITH_WARNINGS` | Försöker ladda dokumentet, men visar eventuella problem som varningar i konsolen. | Du vill se *vad* som gick fel utan att avbryta. | +| `RECOVER_WITHOUT_WARNINGS` | Fixar tyst vad den kan och undertrycker varningar. | Produktionsmiljöer där loggar måste hållas rena. | +| `REJECT_CORRUPTED` | Kastar ett undantag så snart korruption upptäcks. | Strikta valideringspipelines som måste misslyckas snabbt. | + +Att välja rätt läge är kärnan i att **set recovery mode** korrekt. I de flesta felsökningssessioner är `RECOVER_WITH_WARNINGS` den bästa balansen eftersom den visar exakt vilka delar som reparerades. + +## Så återställer du korrupt Word-fil med Aspose.Words + +Nedan är ett **komplett, körbart Java‑program** som demonstrerar hela processen. Känn dig fri att lägga det i en `RecoveryModeDemo.java`‑fil, justera sökvägen och köra. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Varför varje rad är viktig + +* **`LoadOptions loadOptions = new LoadOptions();`** – utan detta objekt använder Aspose.Words standardåterhämtning, som *avvisar* korrupta filer. Att skapa det ger dig en möjlighet att ändra det beteendet. +* **`setRecoveryMode(...)`** – detta är anropet **set recovery mode** som bestämmer om varningar visas, hålls dolda eller orsakar ett undantag. +* **`new Document(path, loadOptions);`** – konstruktorn accepterar de `LoadOptions` vi just konfigurerade, så biblioteket vet hur det ska behandla den trasiga filen från början. +* **`doc.getPageCount()`** – en snabb kontroll. Om dokumentet laddas och returnerar ett sidantal har du lyckats **how to recover corrupted word file**. +* **`doc.save(...)`** – valfri men praktisk; du kan skriva den reparerade versionen tillbaka till disk för senare bruk. + +## Hantera vanliga kantfall + +### 1. Filen hittades inte + +Om sökvägen är fel, kastar `Document` ett `FileNotFoundException`. Omge laddningen med ett try‑catch‑block och logga ett vänligt meddelande: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Oåterställbar korruption + +Även med `RECOVER_WITH_WARNINGS` är vissa strukturer bortom reparation. I så fall laddar Aspose.Words fortfarande vad den kan, men du kommer att se varningar som “Cannot read paragraph properties”. Uppmärksamma konsolutdata; dessa varningar pekar ofta på saknade sektioner som du kan behöva återskapa manuellt. + +### 3. Stora filer och prestanda + +Återhämtning lägger till en liten overhead eftersom biblioteket parsar filen två gånger—en gång för att upptäcka problem, en gång till för att bygga om. För dokument på flera gigabyte, överväg att strömma filen eller öka JVM‑heapen (`-Xmx2g`) för att undvika `OutOfMemoryError`. + +## Pro‑tips – Gör återhämtning robust + +* **Log warnings to a file** – omdirigera `System.err` till en logger så att du har ett revisionsspår av vad som har fixats. +* **Validate after recovery** – kör `doc.updatePageLayout();` och kontrollera sedan sidantalet igen; ibland ändras layouten efter att trasiga sektioner har fixats. +* **Automate batch recovery** – omge demon i en loop som bearbetar en mapp med korrupta filer, med samma `LoadOptions` varje gång. + +## Slutsats + +Du vet nu exakt **how to recover corrupted word file** med Aspose.Words för Java. Genom att skapa en `LoadOptions`‑instans, **set recovery mode** till den strategi som passar ditt scenario, och ladda dokumentet med dessa alternativ, kan du säkert **open corrupted word document** utan att krascha din applikation. Exempelkoden ovan är en komplett, färdig‑att‑köra lösning som skriver ut sidantalet och även sparar en rengjord kopia. + +Vad blir nästa? Prova att byta återhämtningsläget till `RECOVER_WITHOUT_WARNINGS` och jämför konsolutdata, eller experimentera med att ladda krypterade dokument (du måste ange ett lösenord via + +## Relaterade handledningar + +- [Aspose.Words Java: Omfattande guide till Word-dokumenthantering](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [Så konverterar du Word till PDF med Aspose.Words för Java](/words/english/java/document-converting/using-document-converting/) +- [Så jämför du två Word-filer med Aspose.Words för Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/swedish/java/document-styling/_index.md index a624633c29..f9b9ac5a56 100644 --- a/words/swedish/java/document-styling/_index.md +++ b/words/swedish/java/document-styling/_index.md @@ -43,6 +43,8 @@ Lär dig hur du anpassar dokumentteman med Aspose.Words för Java. Den här omfa Lär dig hur du använder vattenstämplar och konfigurerar sidkonfigurationer med Aspose.Words för Java. En omfattande guide med källkod. ### [Formatering av dokumentsidhuvud och sidfot](./document-header-footer-styling/) Lär dig hur du formaterar dokumentsidhuvuden och sidfot med Aspose.Words för Java i den här detaljerade guiden. Steg-för-steg-instruktioner och källkod ingår. +### [Ställ in standardteckensnitt i Aspose.Words för Java – Komplett guide](./set-default-font-settings-in-aspose-words-for-java-complete/) +Lär dig hur du ställer in standardteckensnitt för dokument med Aspose.Words för Java. En komplett guide med kodexempel. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/swedish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..2dc3501f4d --- /dev/null +++ b/words/swedish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,238 @@ +--- +category: general +date: 2026-05-26 +description: Ställ in standardteckensnittinställningar i Aspose.Words för Java och + lär dig hur du konfigurerar teckensnitt och upptäcker saknade teckensnitt med bara + några få kodrader. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: sv +og_description: Ställ in standardteckensnittinställningar i Aspose.Words för Java, + lär dig att ställa in teckensnittinställningar och upptäcka saknade teckensnitt + snabbt och pålitligt. +og_title: Ställ in standardteckensnittinställningar i Aspose.Words för Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Ställ in standardteckensnittinställningar i Aspose.Words för Java – Komplett + guide +url: /sv/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ställ in standardteckensnittinställningar i Aspose.Words för Java – Komplett guide + +Har du någonsin funderat på hur du **ställer in standardteckensnittinställningar** när du laddar ett Word‑dokument med Aspose.Words för Java? Du är inte ensam. Saknade glyfer kan förvandla en välpolerad rapport till ett rörigt mess, och att fånga dessa teckensnittssubstitutionsvarningar tidigt sparar timmar av felsökning. + +I den här handledningen går vi igenom ett kortfattat, end‑to‑end‑exempel som **ställer in standardteckensnittinställningar**, visar hur du **ställer in teckensnittinställningar** programatiskt, och demonstrerar ett pålitligt sätt att **upptäcka saknade teckensnitt** innan de förstör layouten. + +--- + +## Vad du kommer att lära dig + +- Hur du skapar ett `LoadOptions`‑objekt med en ny `FontSettings`‑instans. +- Hur du bifogar en varningslyssnare som **upptäcker saknade teckensnitt** under dokumentladdning. +- Hur du laddar en DOCX‑fil medan lyssnaren tyst rapporterar eventuella substitutioner. +- Tips för att anpassa reservteckensnitt och hantera kantfall i produktion. + +Inga extra bibliotek, inga kryptiska konfigurationsfiler—bara ren Java och Aspose.Words. + +--- + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +1. **Aspose.Words för Java** (version 23.10 eller nyare) på din classpath. +2. En Java 17 (eller senare) utvecklings‑kit – vilken modern JDK som helst fungerar. +3. En DOCX‑fil som medvetet använder ett teckensnitt du inte har installerat (t.ex. *“MissingFont.ttf”*). + +Om du saknar Aspose‑JAR‑filen, hämta den från det officiella Maven‑arkivet: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Det är allt—inga extra teckensnitt behöver installeras för detta demo. + +--- + +## Steg 1: Skapa LoadOptions och **ställ in standardteckensnittinställningar** + +Det första vi behöver är ett rent `LoadOptions`‑objekt som talar om för Aspose hur det ska bete sig när det stöter på okända teckensnitt. Genom att anropa `setFontSettings(new FontSettings())` **ställer vi in standardteckensnittinställningar** som börjar med en tom reservlista. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Varför detta är viktigt:** +> När du inte explicit konfigurerar teckensnitt faller Aspose tillbaka på systemets standardsamling, vilket kan dölja problem med saknade teckensnitt. Genom att starta från en ny `FontSettings`‑instans får du full kontroll över vilka teckensnitt som anses giltiga. + +--- + +## Steg 2: Bifoga en varningslyssnare för att **upptäcka saknade teckensnitt** + +Aspose genererar ett `WarningInfo`‑objekt för varje substitution den utför. Genom att lyssna på `WarningType.FONT_SUBSTITUTION` kan vi **upptäcka saknade teckensnitt** så snart dokumentet parsas. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro‑tips:** Lyssnaren körs på samma tråd som laddar dokumentet, så prestandapåverkan är praktiskt taget obefintlig. Om du behöver samla varningar för senare analys, lägg dem i en `List` istället för att skriva ut dem direkt. + +--- + +## Steg 3: Ladda dokumentet med de konfigurerade alternativen + +Nu när vi har **ställt in teckensnittinställningar** och förberett en lyssnare, laddar vi helt enkelt filen. Eventuella saknade teckensnitt triggar vår callback omedelbart. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Om källfilen refererar till ett teckensnitt som inte är installerat, får du en utskrift liknande: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Den raden talar om exakt vilket teckensnitt som saknades och vilket reservteckensnitt som användes—perfekt för loggning eller användarfeedback. + +--- + +## Steg 4: Fortsätt med normal bearbetning (valfritt) + +Vid detta tillfälle är dokumentet helt laddat, och du kan fortsätta med vilken manipulation du vill—redigering, konvertering till PDF eller extrahering av text. Varningslyssnaren har redan gjort sitt jobb, så du behöver inga extra kontroller. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Vad händer om du vill ha ett eget reservteckensnitt?** +> Istället för att låta `FontSettings` vara tom, kan du lägga till specifika teckensnitt: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Nu kommer alla saknade teckensnitt att ersättas med *Times New Roman*—ett pålitligt val för de flesta västerländska dokument. + +--- + +## Visuell översikt + +![Diagram som visar hur man ställer in standardteckensnittinställningar i Aspose.Words för Java](image.png "Diagram över flödet för att ställa in standardteckensnittinställningar") + +*Alt‑text: flöde för att ställa in standardteckensnittinställningar i Aspose.Words för Java.* + +Diagrammet illustrerar flödet från initiering av `LoadOptions` (där vi **ställer in standardteckensnittinställningar**) till att bifoga varningslyssnaren (för att **upptäcka saknade teckensnitt**) och slutligen ladda dokumentet. + +--- + +## Vanliga fallgropar & hur du undviker dem + +| Fallgrop | Varför det händer | Lösning | +|----------|-------------------|---------| +| **Glömt att anropa `setFontSettings`** | Aspose använder systemstandard, vilket döljer saknade teckensnitt. | Skapa alltid en ny `FontSettings`‑instans och tilldela den till `LoadOptions`. | +| **Lyssnaren triggas inte** | Lyssnaren lades till efter att dokumentet laddats. | Lägg till varningslyssnaren *innan* du anropar `new Document(...)`. | +| **Sökvägsfel leder till `FileNotFoundException`** | Hårdkodad sökväg matchar inte OS‑sensitivitet. | Använd `Paths.get("...").toAbsolutePath()` eller konfigurera en relativ sökväg från projektroten. | +| **Många saknade teckensnitt överväldigar loggarna** | Stora dokument kan generera dussintals varningar. | Filtrera dubletter eller samla meddelanden i ett `Set` innan du skriver ut. | + +--- + +## Utöka lösningen + +Om du behöver **ställa in teckensnittinställningar** för hela applikationen, överväg att skapa en singleton `FontSettings` och återanvända den i alla `LoadOptions`. På så sätt behåller du en konsekvent reservstrategi och undviker upprepade objektinstanseringar. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Nu kan vilken del av din kodbas som helst helt enkelt anropa `FontConfig.getLoadOptions()` och omedelbart dra nytta av samma logik för att **ställa in standardteckensnittinställningar**. + +--- + +## Slutsats + +Vi har nu gått igenom allt du behöver för att **ställa in standardteckensnittinställningar** i Aspose.Words för Java, **ställa in teckensnittinställningar** programatiskt, och **upptäcka saknade teckensnitt** innan de förstör ditt resultat. Det kompletta, körbara exemplet finns i kodsnuttarna ovan, och du kan klistra in det direkt i din IDE för att se varningarna i aktion. + +Nästa steg? Prova att byta reservteckensnitt, experimentera med olika dokumentformat (DOC, RTF, HTML), eller integrera varningssamlaren i en övervakningsdashboard. Ju mer du leker med `FontSettings`, desto säkrare blir du på att dina genererade dokument ser exakt ut som tänkt—inga överraskningar, inga trasiga glyfer. + +Har du frågor eller ett knepigt teckensnittssubstitutionsscenario? Lämna en kommentar nedan, och lycka till med kodandet! + + +## Relaterade handledningar + +- [Ställ in teckensnittets reservinställningar](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Ställ in teckensnittets reservinställningar](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Ställ in teckensnittets reservinställningar](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/java/images-shapes/_index.md b/words/swedish/java/images-shapes/_index.md index c2d81e16b8..d19db4af13 100644 --- a/words/swedish/java/images-shapes/_index.md +++ b/words/swedish/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Lär dig hur du genererar högkvalitativa miniatyrbilder och bitmappar i anpassa ### [Skapa Word-dokument Java – Lägg till rektangel med skuggeffekt](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Lär dig hur du lägger till en rektangel med skuggeffekt i ett Word-dokument med Aspose.Words för Java. +### [Skapa rektangelform i Java Word-dokument – Fullständig steg‑för‑steg‑guide](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Lär dig hur du skapar en rektangelform i ett Word-dokument med Aspose.Words för Java. + ## Ytterligare resurser - [Aspose.Words för Java-dokumentation](https://reference.aspose.com/words/java/) diff --git a/words/swedish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/swedish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..55bb8f7aff --- /dev/null +++ b/words/swedish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-05-26 +description: Skapa en rektangel i ett Java Word‑dokument och applicera skuggeffekt. + Lär dig hur du lägger till skugga på formen, ställer in skuggavstånd och sparar + filen. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: sv +og_description: Skapa en rektangelform i ett Java Word‑dokument, applicera skuggeffekt, + lägg till formskugga och ställ in skuggavståndet med Aspose.Words. +og_title: Skapa rektangelform i Java Word-dokument – Komplett guide +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Skapa rektangelform i Java Word-dokument – Fullständig steg‑för‑steg‑guide +url: /sv/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa rektangelform i Java Word-dokument – Full steg‑för‑steg‑guide + +Har du någonsin behövt **create rectangle shape** i ett Java Word-dokument men varit osäker på var du ska börja? Du är inte ensam—många utvecklare stöter på detta problem när de genererar rapporter eller fakturor programmässigt. I den här handledningen går vi igenom exakt hur du **create rectangle shape**, applicerar en polerad skugga och finjusterar skuggavståndet så resultatet ser professionellt ut. + +Vi kommer att använda Aspose.Words for Java, ett robust bibliotek som låter dig manipulera Word-filer utan att behöva Microsoft Office installerat. I slutet av den här guiden kommer du att kunna **create word document java**-projekt som **add shape shadow**, **apply shadow effect** och **set shadow distance** med bara några rader kod. + +--- + +## Vad du kommer att bygga + +- En ny `.docx`-fil som innehåller en cyan rektangel. +- En realistisk drop‑shadow som är suddig, vinklad och delvis transparent. +- Full kontroll över skuggans avstånd från formen. +- En färdig‑att‑köra Java-klass som du kan släppa in i vilket Maven- eller Gradle‑projekt som helst. + +Inga externa verktyg, inga manuella UI‑steg—bara ren kod. + +## Förutsättningar + +- Java 8 eller nyare (koden fungerar på Java 11, Java 17 osv.). +- Aspose.Words for Java‑biblioteket (tillgängligt via Maven Central). +- En IDE eller textredigerare du föredrar (IntelliJ IDEA, Eclipse, VS Code…). +- Grundläggande kunskap om Java‑syntax. + +Om du aldrig har lagt till ett Maven‑beroende tidigare, här är det snabba kodsnutten: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Nu, låt oss dyka in. + +## Steg 1: Skapa rektangelform i ett Word-dokument + +Det första vi behöver är ett tomt dokument och en `DocumentBuilder`. Tänk på buildern som en penna som skriver i dokumentet. När vi har den kan vi **create rectangle shape** med ett enda metodanrop. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Varför detta är viktigt:** `insertShape`‑metoden skapar inte bara geometrin utan lägger också till formen i dokumentets interna samling, så du kan omedelbart börja styla den. + +## Steg 2: Applicera skuggeffekt på formen + +Nu när rektangeln finns på sidan kommer vi att **apply shadow effect**. Skuggor ger djup, vilket får formen att kännas som om den lyfts från sidan—en subtil UI‑förbättring som kan öka läsbarheten i rapporter. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Proffstips:** En oskärpa på `5.0` ser naturlig ut för de flesta skärm‑visade dokument. Om du skriver ut kan du vilja ha ett något lägre värde för att undvika ett suddigt utseende. + +## Steg 3: Ställ in skuggavstånd – finjustera placeringen + +Skuggor handlar inte bara om oskärpa; de behöver också rätt förskjutning. Här är vi **set shadow distance**. Ett avstånd på `7.0` punkter skapar en måttlig förskjutning som är märkbar men inte överväldigande. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Vad händer om du behöver en större förskjutning?** Öka värdet; minska det för ett tajtare utseende. Kom ihåg att avståndet samverkar med vinkeln för att placera skuggan korrekt. + +## Steg 4: Spara dokumentet – bevara ditt arbete + +Till sist skriver vi dokumentet till disk. Ändra sökvägen till var du vill att filen ska ligga. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +När klassen körs skapas en `shadow.docx`‑fil som, när den öppnas i Microsoft Word eller LibreOffice, visar en cyan rektangel med en mjuk grå skugga vinklad 45° och förskjuten med 7 punkter. + +## Fullt fungerande exempel + +Nedan är den kompletta, kopiera‑och‑klistra‑klara koden. Den innehåller alla imports, kommentarer och det sista `save`‑anropet. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Förväntat resultat:** Öppna `shadow.docx` → du kommer att se en cyan rektangel centrerad på första sidan, som kastar en subtil grå skugga som är lite förskjuten mot nedre‑höger. Skuggans oskärpa och transparens får den att se ut som naturligt ljus. + +## Vanliga frågor & specialfall + +### “Kan jag använda en annan form?” + +Absolut. Byt ut `ShapeType.RECTANGLE` mot `ShapeType.OVAL`, `ShapeType.LINE` eller någon annan stödd enum. Resten av skuggkoden förblir densamma. + +### “Vad händer om jag behöver flera skuggor?” + +Aspose.Words stödjer bara en enda skugga per form. För att simulera flera skuggor, duplicera formen, förskjut varje kopia och justera transparensen. + +### “Är skuggan synlig i LibreOffice?” + +Ja—Aspose.Words skriver standard‑OOXML, vilket LibreOffice tolkar korrekt. Skuggan kan se något annorlunda ut på grund av renderingsmotorer, men effekten kvarstår. + +### “Hur ändrar jag skuggans färg så den matchar mitt varumärke?” + +Byt bara ut `java.awt.Color.GRAY` mot någon `java.awt.Color` du föredrar, till exempel `new java.awt.Color(0, 120, 215)` för en företagsblå. + +## Bildillustration + +![create rectangle shape i Java Word-dokument](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** illustration som visar en cyan rektangel med en grå drop‑shadow i ett Word‑dokument. + +## Sammanfattning & nästa steg + +Vi har gått igenom hur man **create rectangle shape**, **apply shadow effect**, **add shape shadow** och **set shadow distance** med Aspose.Words for Java. Koden är självständig, körs på vilken modern JDK som helst och producerar en polerad `.docx`‑fil klar för distribution. + +Vill du gå längre? Prova: + +- Lägg till text inuti rektangeln med `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Skapa en tabell med former för att bygga ett diagram. +- Exportera dokumentet till PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +Var och en av dessa bygger på samma grunder som vi just utforskade, så du kommer att känna dig bekväm med att utöka exemplet. + +## Slutliga tankar + +Att behärska **create word document java**‑uppgifter som formning och skuggning ger dig ett stort försprång när du automatiserar rapporter, kontrakt eller marknadsföringsmaterial. Tillvägagångssättet som visas här är rent, underhållbart och—framför allt—lätt att justera för vilken visuell stil du än behöver. + +Kör koden, justera oskärpan, vinkeln och avståndet, och se hur dina dokument förvandlas från tråkiga till polerade. Om du stöter på ett problem, lämna en kommentar nedan; jag hjälper gärna till. + +Lycka till med kodandet! + +## Relaterade handledningar + +- [Create Word Document Java – Add Rectangle Shape with Shadow Effect](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [How to create form fields and add content using DocumentBuilder in Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Create PDF from Word with Barcode Generation – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/thai/java/document-conversion-and-export/_index.md index f94035c8b1..8ee023a4fb 100644 --- a/words/thai/java/document-conversion-and-export/_index.md +++ b/words/thai/java/document-conversion-and-export/_index.md @@ -70,9 +70,15 @@ For more information, check out the [Aspose.Words for Java API Documentation](ht ### [แปลง docx เป็น markdown – ส่งออกสมการคณิตศาสตร์เป็น LaTeX ด้วย Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น Markdown พร้อมส่งออกสมการคณิตศาสตร์เป็นรูปแบบ LaTeX ด้วย Aspose.Words +### [บันทึก Word เป็น markdown – ส่งออกสมการเป็น LaTeX ด้วย Java](./save-word-as-markdown-export-math-to-latex-with-java/) +เรียนรู้วิธีบันทึกไฟล์ Word เป็น Markdown พร้อมส่งออกสมการคณิตศาสตร์เป็น LaTeX ด้วย Java และ Aspose.Words + ### [วิธีฝังรูปภาพใน Markdown เมื่อแปลง DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) เรียนรู้วิธีฝังรูปภาพลงในไฟล์ Markdown ระหว่างการแปลง DOCX ด้วย Aspose.Words +### [ฝังรูปภาพเป็น Base64 เมื่อแปลง DOCX เป็น Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +เรียนรู้วิธีฝังรูปภาพเป็น Base64 ระหว่างการแปลง DOCX เป็น Markdown ด้วย Aspose.Words for Java + ### [Generating Custom Barcode Labels in Aspose.Words for Java](./generating-custom-barcode-labels/) Generate Custom Barcode Labels in Aspose.Words for Java. Learn how to create personalized barcode solutions using Aspose.Words for Java in this step‑by‑step guide. @@ -97,12 +103,21 @@ Learn how to format tables and apply table styles in Aspose.Words for Java. Expl ### [บันทึกเอกสารเป็น TXT – คู่มือด่วนสำหรับการส่งออกสมการ Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) เรียนรู้วิธีบันทึกไฟล์ Word เป็น TXT พร้อมส่งออกสมการคณิตศาสตร์อย่างง่ายและรวดเร็วด้วย Aspose.Words for Java +### [ส่งออก docx เป็น txt ด้วย Java – คู่มือการเขียนโปรแกรมเต็มรูปแบบ](./export-docx-to-txt-with-java-complete-programming-guide/) +เรียนรู้วิธีแปลงไฟล์ DOCX เป็น TXT อย่างละเอียดด้วย Java และ Aspose.Words + ### [Aspose.Words to PDF – แปลง DOCX เป็น PDF ด้วย Java](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น PDF อย่างง่ายด้วย Aspose.Words for Java ### [สร้าง PDF ที่เข้าถึงได้จาก DOCX – คู่มือฉบับสมบูรณ์](./create-accessible-pdf-from-docx-complete-guide/) เรียนรู้วิธีแปลงไฟล์ DOCX เป็น PDF ที่รองรับการเข้าถึงสำหรับผู้ใช้ทุกคนด้วย Aspose.Words +### [สร้าง PDF ที่เข้าถึงได้ใน Java – คู่มือการทำแท็กเต็มรูปแบบ](./create-accessible-pdf-in-java-full-tagging-guide/) +เรียนรู้วิธีสร้าง PDF ที่เข้าถึงได้ด้วยการใส่แท็กครบถ้วนใน Java ด้วย Aspose.Words + +### [บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java – คู่มือการเข้าถึงเต็มรูปแบบ](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +เรียนรู้วิธีบันทึกเอกสารเป็น PDF พร้อมคุณสมบัติการเข้าถึงสำหรับผู้ใช้ทุกคนด้วย Aspose.Words for Java + ## คำถามที่พบบ่อย **Q: ฉันจะเพิ่มลายน้ำให้กับ PDF ที่มีอยู่โดยใช้ Aspose.Words อย่างไร?** diff --git a/words/thai/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/thai/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..edc188be18 --- /dev/null +++ b/words/thai/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-26 +description: สร้าง PDF ที่เข้าถึงได้ใน Java ด้วยโค้ดทีละขั้นตอน เรียนรู้วิธีการใส่แท็ก + PDF เพื่อการเข้าถึงและเปิดใช้งานการแท็ก PDF ด้วย PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: th +og_description: สร้าง PDF ที่เข้าถึงได้ใน Java ด้วยโค้ดทีละขั้นตอน เรียนรู้วิธีทำแท็ก + PDF เพื่อการเข้าถึงและเปิดใช้งานการทำแท็ก PDF ด้วย PdfSaveOptions. +og_title: สร้าง PDF ที่เข้าถึงได้ใน Java – คู่มือการทำแท็กเต็ม +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: สร้าง PDF ที่เข้าถึงได้ใน Java – คู่มือการทำแท็กเต็มรูปแบบ +url: /th/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง PDF ที่เข้าถึงได้ใน Java – คู่มือการทำแท็กเต็มรูปแบบ + +เคยสงสัยไหมว่าจะแบบ **create accessible PDF** อย่างไรโดยตรงจากโค้ด Java? คุณไม่ได้เป็นคนเดียว นักพัฒนาจำนวนมากต้องรองรับผู้ใช้ที่พึ่งพาโปรแกรมอ่านหน้าจอ และความแตกต่างระหว่าง PDF ธรรมดากับ PDF ที่เข้าถึงได้อาจใหญ่โตมาก ในบทแนะนำนี้เราจะอธิบาย **how to tag PDF for accessibility**, แสดงให้คุณเห็น **how to create tagged PDF** ด้วย Aspose PDF for Java, และเปิดเผยขั้นตอนที่แน่นอนเพื่อ **add accessibility tags to PDF** เพื่อให้ผู้อ่านทุกคนได้รับข้อมูลเดียวกัน. + +เราจะครอบคลุมแนวทางปฏิบัติที่ดีที่สุดสำหรับ **enable PDF tagging**, ปัญหาที่พบบ่อย, และตัวอย่างที่ทำงานได้ครบถ้วนที่คุณสามารถนำไปใส่ในโปรเจคของคุณได้ทันที ไม่มีการอ้างอิงที่คลุมเครือ—เพียงโค้ดที่เป็นรูปธรรม, คำอธิบาย, และไฟล์สุดท้ายที่คุณสามารถเปิดใน Adobe Acrobat เพื่อตรวจสอบแท็ก + +## สิ่งที่คุณจะได้เรียนรู้ + +- เหตุผลว่าทำไมต้องทำแท็ก PDF และการปฏิบัติตามมาตรฐานการเข้าถึง +- ข้อกำหนดเบื้องต้นและการตั้งค่าห้องสมุด (Aspose PDF for Java 23.10 หรือใหม่กว่า) +- วิธี **create accessible PDF** ตั้งแต่เริ่มต้น, ทีละขั้นตอน +- วิธี **add accessibility tags to PDF** นอกเหนือจากการเรียก `setTagDocumentStructure` พื้นฐาน +- เคล็ดลับสำหรับการทดสอบผลลัพธ์และการแก้ไขปัญหาที่พบบ่อย + +เมื่อจบคู่มือนี้คุณจะสามารถสร้าง PDF ที่ผ่านการตรวจสอบ WCAG 2.1 AA และดูเป็นมืออาชีพในเวลาเดียวกัน. + +--- + +## ข้อกำหนดเบื้องต้น + +| ข้อกำหนด | เหตุผล | +|-------------|--------| +| **Java 8+** | คุณสมบัติของภาษาที่ทันสมัยและการจัดการ Unicode ที่ดีกว่า. | +| **Aspose PDF for Java** (v23.10 หรือใหม่กว่า) | ให้คลาส `PdfSaveOptions` และการสนับสนุนการทำแท็ก. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, เป็นต้น) | เพื่อการคอมไพล์และดีบักที่ง่าย. | +| **Write permission** ไปยังโฟลเดอร์ที่ PDF จะถูกบันทึก | คำสั่ง `doc.save` ต้องการเส้นทางที่สามารถเขียนได้. | + +หากคุณยังไม่ได้เพิ่ม Aspose PDF เข้าในโปรเจคของคุณ ให้ใส่ dependency ของ Maven ด้านล่างนี้ลงในไฟล์ `pom.xml` ของคุณ: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro tip:** ใช้เวอร์ชันล่าสุด; การปล่อยเวอร์ชันใหม่ช่วยปรับปรุงความแม่นยำของการทำแท็กและเพิ่มคุณสมบัติการเข้าถึงที่เฉพาะเจาะจงตามภาษา. + +## ขั้นตอนที่ 1: ตั้งค่าโครงสร้างเอกสาร + +ขั้นแรก เราจะสร้างอ็อบเจกต์ `Document` ใหม่ คิดว่ามันเป็นผืนผ้าใบเปล่าที่ต่อไปจะบรรจุแท็กที่เราต้องการสำหรับการเข้าถึง. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Why this matters:** หากไม่มีเนื้อหาใด ๆ จะไม่มีอะไรให้ทำแท็ก การเพิ่มแม้แต่ `TextFragment` ง่าย ๆ จะให้เอนจินทำแท็กมีสิ่งที่ทำงานด้วย และมันจะสร้างแท็ก `

` (ย่อหน้า) โดยอัตโนมัติเมื่อเราต่อมาสามารถเปิดใช้งานการทำโครงสร้างแท็ก. + +## ขั้นตอนที่ 2: สร้าง PDF Save Options (หัวใจของการทำแท็ก) + +ตอนนี้เราจะเตรียมตัวเลือกที่บอกให้ Aspose PDF ฝังโครงสร้างต้นไม้เชิงตรรกะภายในไฟล์. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +การเรียก `setTagDocumentStructure(true)` คือสวิตช์ **enable PDF tagging** เมื่อเป็น true ไลบรารีจะสร้างต้นไม้แท็กที่สะท้อนการจัดวางภาพ ทำให้ PDF สามารถอ่านได้โดยเทคโนโลยีช่วยเหลือ. + +> **Note:** นี่เป็นวิธีที่ง่ายที่สุดในการ **how to create tagged pdf**. หากต้องการควบคุมที่ละเอียดกว่า (เช่น การตั้งค่าภาษา หรือแท็กกำหนดเอง) คุณสามารถสำรวจ `pdfOptions.setTagLanguage("en-US")` และ `pdfOptions.setTagStructureTreeRoot(...)`. + +## ขั้นตอนที่ 3: บันทึก PDF ที่เข้าถึงได้ + +สุดท้าย เราจะเขียนเอกสารลงดิสก์โดยใช้ตัวเลือกที่เราเพิ่งกำหนดค่า. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +เมื่อ `doc.save` เสร็จสิ้น คุณจะพบไฟล์ `accessible.pdf` ในโฟลเดอร์ `output` เปิดไฟล์ใน Adobe Acrobat แล้วดูที่ **File → Properties → Description → Tags** – คุณควรเห็นต้นไม้แท็กที่เต็ม. + +## วิธีทำแท็ก PDF เพื่อการเข้าถึง – เกินกว่าพื้นฐาน + +โค้ดสั้นสามขั้นตอนข้างต้นได้ **adds accessibility tags to PDF** แล้ว แต่เอกสารในโลกจริงมักต้องการการปรับแต่งเพิ่มเติม นี่คือการเสริมบางอย่างที่คุณสามารถเพิ่มเข้าไป: + +### 1. ตั้งค่าภาษาเอกสาร + +โปรแกรมอ่านหน้าจอใช้แอตทริบิวต์ภาษาเพื่อการออกเสียงข้อความอย่างถูกต้อง. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. ให้หัวเรื่องและหัวข้อเรื่อง + +เมตาดาต้าช่วยให้เครื่องมือช่วยเหลือให้บริบทก่อนที่ผู้ใช้จะเปิดไฟล์. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. ทำแท็กรูปภาพด้วยข้อความแทน (Alternative Text) + +หากคุณฝังรูปภาพเข้ามา พวกมันต้องมีคำอธิบาย `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. ทำเครื่องหมายหัวตาราง + +ตารางมักทำให้ผู้อ่านสับสนหากไม่ได้ทำเครื่องหมายแถวหัวตาราง. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +ขั้นตอนเพิ่มเติมเหล่านี้ทำให้ PDF ของคุณไม่เพียงแค่ *technically* tagged เท่านั้น แต่เป็น **accessible** อย่างแท้จริงสำหรับผู้ชมที่หลากหลาย. + +## ปัญหาที่พบบ่อยเมื่อคุณเปิดใช้งานการทำแท็ก PDF + +| อาการ | สาเหตุที่เป็นไปได้ | วิธีแก้ | +|---------|--------------|-----| +| แท็กหายไปใน Acrobat | `setTagDocumentStructure` ถูกตั้งเป็น `false` | ตรวจสอบให้แน่ใจว่าคุณเรียก `pdfOptions.setTagDocumentStructure(true)`. | +| ลำดับการอ่านผิด | เลย์เอาต์ซับซ้อนโดยไม่มีแท็กที่ชัดเจน | ใช้ `pdfOptions.setTagStructureTreeRoot(...)` เพื่อกำหนดลำดับแบบกำหนดเอง. | +| รูปภาพอ่านเป็น “image” โดยไม่มีคำอธิบาย | ไม่ได้ตั้งค่าข้อความแทน | เรียก `image.getAlternativeText().setValue("...")`. | +| ไม่รู้จักภาษา | `setTagLanguage` ถูกละเว้นหรือใช้โลคัลผิด | ระบุรหัสภาษา BCP‑47 (`en-US`, `fr-FR`). | + +## ตรวจสอบผลลัพธ์ – สิ่งที่คาดหวัง + +หลังจากรันโปรแกรม เปิดไฟล์ `output/accessible.pdf` ใน Adobe Acrobat Reader: + +1. **Tags panel** (`View → Show/Hide → Navigation Panes → Tags`) ควรแสดงลำดับชั้นเช่น `/Document → /Part → /Sect → /Para`. +2. **Reading order** ควรตามลำดับการแสดงผล (ข้อความก่อน, จากนั้นรูปภาพ). +3. **Screen reader** (NVDA, VoiceOver) จะอ่านว่า “Hello, accessible PDF!” แทนที่จะเป็นเพียง “Page 1”. + +หากรายการใดหายไป ให้ตรวจสอบขั้นตอนข้างต้นอีกครั้ง—โดยเฉพาะการเรียก `setTagDocumentStructure`. + +## ตัวอย่างทำงานเต็มรูปแบบ (พร้อมคัดลอก‑วาง) + + + +## บทแนะนำที่เกี่ยวข้อง + +- [สร้าง PDF ที่เข้าถึงได้จาก Word – แปลงเป็น PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [สร้าง PDF ที่เข้าถึงได้จาก DOCX – คู่มือฉบับสมบูรณ์](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [วิธีบันทึกเอกสารเป็น pdf ด้วย Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/thai/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..77e09cea18 --- /dev/null +++ b/words/thai/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-26 +description: ฝังรูปภาพเป็น base64 ขณะคุณแปลงไฟล์ docx เป็น markdown ด้วย Aspose.Words + for Java. เรียนรู้การแปลง Word เป็น markdown, บันทึก Word เป็น markdown, และจัดการรูปภาพ. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: th +og_description: ฝังรูปภาพเป็น base64 ระหว่างแปลงไฟล์ docx เป็น markdown ด้วย Aspose.Words + for Java. คู่มือครบถ้วนในการแปลง Word เป็น markdown และบันทึก Word เป็น markdown. +og_title: ฝังรูปภาพเป็น Base64 เมื่อแปลง DOCX เป็น Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: ฝังรูปภาพเป็น Base64 เมื่อแปลง DOCX เป็น Markdown +url: /th/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ฝังรูปภาพเป็น Base64 เมื่อแปลง DOCX เป็น Markdown + +เคยสงสัยไหมว่าจะแนบรูปภาพเป็น **base64** อย่างไรในขณะที่คุณ **convert docx to markdown**? คุณไม่ได้เป็นคนเดียว—นักพัฒนามักถามวิธีการทำให้รูปภาพอยู่ในบรรทัดเดียวโดยไม่ต้องจัดการไฟล์แยกต่างหาก ข่าวดีคือ Aspose.Words for Java ทำให้เรื่องนี้ง่ายมาก: คุณสามารถแปลงเอกสาร Word เป็น Markdown และแทรกรูปภาพทุกภาพเป็นสตริง Base64 โดยอัตโนมัติ + +ในบทเรียนนี้เราจะเดินผ่านกระบวนการทั้งหมด—from การโหลดไฟล์ `.docx` ที่มีรูปภาพ, การกำหนดค่า callback ของ `MarkdownSaveOptions` ที่ทำงานหนัก, และสุดท้ายการบันทึกผลลัพธ์เป็นไฟล์ `.md` ที่สะอาด เมื่อจบคุณจะรู้วิธี **convert word to markdown**, **convert images to base64**, และ **save word as markdown** โดยไม่ทิ้งโฟลเดอร์รูปภาพแยกออกมา ไม่มีเครื่องมือภายนอก, ไม่มีการประมวลผลหลังจากแปลง—เพียงโค้ด Java ธรรมดาที่คุณสามารถใส่ลงในโปรเจกต์ใดก็ได้ + +## สิ่งที่คุณต้องการ + +- **Java 17** (หรือ JDK ล่าสุด) – โค้ดใช้ไวยากรณ์ lambda แต่คุณสามารถปรับให้เข้ากับเวอร์ชันเก่าได้ +- **Aspose.Words for Java** library (เวอร์ชันล่าสุด ณ ปี 2026) เพิ่ม dependency ของ Maven หรือไฟล์ JAR ไปยัง classpath ของคุณ +- ไฟล์ **DOCX** ตัวอย่างที่มีรูปภาพอย่างน้อยหนึ่งรูป +- IDE หรือเครื่องมือแก้ไขข้อความอย่างง่าย—Visual Studio Code, IntelliJ IDEA หรือแม้แต่ `vim` ก็ใช้ได้ + +หากคุณมีทั้งหมดแล้ว ยอดเยี่ยม—มาเริ่มกันเลย + +## ขั้นตอนที่ 1: โหลดเอกสาร Word + +แรกเราจะสร้างอินสแตนซ์ `Document` ที่ชี้ไปยังไฟล์ต้นฉบับ ขั้นตอนนี้เหมือนกันไม่ว่าคุณจะ **convert docx to markdown** หรือเพียงอ่านไฟล์เพื่อวัตถุประสงค์อื่น + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** วัตถุ `Document` เป็นจุดเริ่มต้นของทุกการทำงานของ Aspose มันเก็บโครงสร้าง Word ทั้งหมด—รวมถึงรูปภาพ ตาราง และสไตล์—เพื่อให้ callback ที่ตามมาสามารถตรวจสอบแต่ละ resource ได้ + +## ขั้นตอนที่ 2: สร้าง MarkdownSaveOptions และลงทะเบียน Resource‑Saving Callback + +ความมหัศจรรย์อยู่ใน `MarkdownSaveOptions` โดยการแนบ `IResourceSavingCallback` เราจะได้ควบคุมวิธีการเขียนแต่ละ resource ภายนอก (เช่นรูปภาพ) + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: ทำไมต้องใช้ `setSaveToMemory(true)`? + +เมื่อ `saveToMemory` เป็น true, Aspose จะเขียนไบต์ของรูปภาพไปยังสตรีมในหน่วยความจำแทนไฟล์ ตัวส่งออก Markdown จากนั้นจะแปลงสตรีมนั้นเป็นสตริง Base64 และแทรกโดยตรงลงในแท็กรูปภาพของ Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +นี่คือหัวใจของ **embed images as base64**. + +## ขั้นตอนที่ 3: บันทึกเอกสารเป็น Markdown + +เมื่อ callback ถูกตั้งค่าแล้ว ขั้นตอนสุดท้ายคือการเรียก `save` เพียงอย่างเดียว นี่คือจุดที่เราจริง ๆ **convert word to markdown** และเนื่องจาก callback เรายัง **convert images to base64** ด้วย + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **ผลลัพธ์:** `out.md` มีข้อความ Markdown ที่แต่ละรูปภาพถูกแทนด้วย `data:` URI ไม่มีไฟล์รูปภาพเพิ่มเติมถูกสร้างบนดิสก์ ทำให้โฟลเดอร์สะอาดเรียบร้อย + +## ขั้นตอนที่ 4: ตรวจสอบผลลัพธ์และข้อผิดพลาดทั่วไป + +เปิด `out.md` ที่สร้างขึ้นในโปรแกรมดู Markdown ใดก็ได้ (VS Code, GitHub, หรือ static site generator) คุณควรเห็นอย่างนี้: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### รายการตรวจสอบการแก้ไขปัญหา + +| Issue | Likely Cause | Fix | +|-------|--------------|-----| +| รูปภาพแสดงเป็นลิงก์เสีย | `setSaveToMemory` ถูกละเว้น | ตรวจสอบให้แน่ใจว่า `args.setSaveToMemory(true);` อยู่ใน callback | +| สตริง Base64 ถูกตัด | การเข้ารหัสไฟล์ผลลัพธ์ไม่ตรงกัน | บันทึก Markdown ด้วย UTF‑8 (ค่าเริ่มต้นของ Aspose) | +| ชื่อไฟล์ที่ไม่คาดคิด | `setKeepResourceOriginalName(true)` | ตั้งค่าเป็น `false` เพื่อบังคับใช้ตรรกะการตั้งชื่อแบบกำหนดเอง | + +## ขั้นตอนที่ 5: ตัวแปรขั้นสูง (ไม่บังคับ) + +### แปลงเฉพาะรูปภาพที่เลือก + +หากคุณต้องการแทรกรูปภาพบางรูปเท่านั้น (เช่นรูปที่ใหญ่กว่า 100 KB) ให้เพิ่มการตรวจสอบขนาด: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### ใช้รูปแบบภาพอื่น + +`ResourceSavingArgs` ให้ไบต์ดิบของคุณ ดังนั้นคุณสามารถเข้ารหัส JPEG ใหม่เป็น PNG ก่อนแทรก—มีประโยชน์เมื่อผู้รับ Markdown ต้องการ PNG + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +การปรับแต่งเหล่านี้แสดงให้เห็นว่าการใช้วิธี **embed images as base64** มีความยืดหยุ่นแค่ไหนเมื่อคุณ **convert docx to markdown**. + +## สรุป + +คุณเพิ่งเรียนรู้วิธี **embed images as base64** ในขณะที่คุณ **convert docx to markdown** ด้วย Aspose.Words for Java โดยการเชื่อมต่อ `IResourceSavingCallback` ง่าย ๆ ไลบรารีจะทำงานหนักทั้งหมด: มัน **convert word to markdown**, **convert images to base64**, และสุดท้าย **save word as markdown** ด้วยการเรียก `save` เพียงครั้งเดียว + +ลองทดลองได้ตามสบาย—ลองใช้กฎการกรองรูปภาพต่าง ๆ, เปลี่ยนเป็นเอาต์พุต HTML, หรือเชื่อมต่อขั้นตอนนี้กับ static‑site generator รูปแบบเดียวกันทำงานกับฟอร์แมตอื่น ๆ (HTML, EPUB) ด้วยเช่นกัน ดังนั้นคุณสามารถใช้ callback นี้ซ้ำได้ทุกที่ที่ต้องการ resource แบบในบรรทัดเดียว + +**ขั้นตอนต่อไป:** +- สำรวจ `HtmlSaveOptions` สำหรับ HTML‑with‑Base64 images. +- ผสานกับ CI pipeline เพื่ออัตโนมัติการสร้างเอกสาร. +- ศึกษา `DocumentVisitor` ของ Aspose หากต้องการควบคุมการแปลงอย่างละเอียดยิ่งขึ้น + +ขอให้สนุกกับการเขียนโค้ดและเพลิดเพลินกับไฟล์ Markdown ที่สะอาดและเป็นอิสระ! + +## บทเรียนที่เกี่ยวข้อง + +- [วิธีฝังรูปภาพใน Markdown เมื่อแปลง DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [แปลง docx เป็น markdown – ส่งออกสมการคณิตศาสตร์เป็น LaTeX ด้วย Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [บันทึกรูปภาพจาก Word – คู่มือ Aspose.Words for Java](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/thai/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..8d8791d6a6 --- /dev/null +++ b/words/thai/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: ส่งออกไฟล์ docx เป็น txt ด้วย Java และ Aspose.Words เรียนรู้วิธีแปลง + docx เป็นข้อความ รักษา Unicode และส่งออกไฟล์ Word เป็น txt ในไม่กี่ขั้นตอน +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: th +og_description: ส่งออกไฟล์ docx เป็น txt ใน Java บทเรียนนี้แสดงวิธีแปลง docx เป็นข้อความ, + รักษา Unicode ของข้อความธรรมดา, และส่งออกไฟล์ Word เป็น txt อย่างมีประสิทธิภาพ. +og_title: ส่งออกไฟล์ docx เป็น txt ด้วย Java – คู่มือครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: ส่งออกไฟล์ docx เป็น txt ด้วย Java – คู่มือการเขียนโปรแกรมแบบครบถ้วน +url: /th/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ส่งออก docx เป็น txt ด้วย Java – คู่มือการเขียนโปรแกรมฉบับสมบูรณ์ + +เคยต้องการ **export docx to txt** แต่กังวลว่าจะสูญเสียอักขระพิเศษหรือไม่? คุณไม่ได้เป็นคนเดียว เมื่อคุณแปลงเอกสาร Word เป็นไฟล์ plain‑text สัญลักษณ์ Unicode ตาราง และแม้กระทั่งการจัดรูปแบบง่าย ๆ ก็อาจหายไปเหมือนกับเวทมนตร์ + +ในคู่มือนี้ เราจะพาคุณผ่านวิธีที่เชื่อถือได้ในการ **export docx to txt** ด้วย Aspose.Words for Java โดยคงอักขระ Unicode ทั้งหมดและทำให้การจัดตารางอ่านง่าย จนถึงตอนท้ายคุณจะรู้วิธี **convert docx to text**, **convert word to text**, และแม้กระทั่ง **export word as txt** อย่างไม่มีอุปสรรค + +## สิ่งที่คู่มือนี้ครอบคลุม + +* ตั้งค่า Aspose.Words ในโครงการ Java +* โหลดไฟล์ DOCX และเตรียมสำหรับการส่งออกเป็น plain‑text +* กำหนดค่าการสนับสนุน **plain text unicode** ผ่าน `TxtSaveOptions` +* เทคนิคเสริมเพื่อให้ตารางอ่านง่ายในไฟล์ `.txt` ที่ได้ +* บันทึกไฟล์และตรวจสอบผลลัพธ์ + +ไม่มีสคริปต์ภายนอก ไม่มีเครื่องมือบรรทัดคำสั่งที่ลึกลับ—เพียงโค้ด Java ธรรมดาที่คุณสามารถใส่ลงในโครงการ Maven หรือ Gradle ใดก็ได้ + +> **ทำไมต้องสนใจ?** ไฟล์ plain‑text มีขนาดเล็ก น้ำหนักเบา เหมาะกับระบบควบคุมเวอร์ชัน และเหมาะสำหรับการทำดัชนีการค้นหาหรือขั้นตอนการประมวลผลต่อเนื่อง หากคุณเคยพยายาม `cat` ไฟล์ Word แล้วได้ข้อความไร้สาระ คู่มือนี้จะแก้ปัญหานั้น + +--- + +## Export docx to txt – ภาพรวม + +ก่อนที่เราจะลงลึกในโค้ด มาทำความเข้าใจคำศัพท์กันก่อน **Export docx to txt** หมายถึงการนำแพ็กเกจ Microsoft Word `.docx` มาบันทึกเนื้อหาข้อความลงในไฟล์ `.txt` ธรรมดา ไม่เหมือนการแปลงเป็น PDF การส่งออกเป็นข้อความจะลบการจัดรูปแบบออก แต่สามารถคงการขึ้นบรรทัดใหม่ เครื่องหมายย่อหน้า และ—หากกำหนดค่าอย่างถูกต้อง—อักขระ Unicode เช่น อีโมจิ ตัวอักษรที่มีสำเนียง หรือสคริปต์เอเชีย + +Aspose.Words ทำให้เรื่องนี้ง่ายดายเพราะมันแยกการทำงานของรูปแบบไฟล์ Word ออกและให้คลาส `TxtSaveOptions` ที่คุณสามารถกำหนดการเข้ารหัส การจัดการตาราง และอื่น ๆ + +### ข้อกำหนดเบื้องต้น + +* Java 11 หรือใหม่กว่า (API ทำงานกับ Java 8+ แต่เราจะสมมติใช้ JDK ล่าสุด) +* Aspose.Words for Java JAR (สามารถดาวน์โหลดจาก Maven Central) +* ไฟล์ตัวอย่าง `unicode.docx` ที่มีอักขระ Unicode หลากหลาย—เช่น “こんにちは”, “😊”, และตารางง่าย ๆ + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปเริ่มกันเลย + +--- + +## ขั้นตอนที่ 1: โหลดไฟล์ DOCX (Convert docx to text) + +สิ่งแรกที่คุณต้องทำคืออ่านเอกสารต้นทางเข้าสู่หน่วยความจำ นี่คือจุดเริ่มต้นของกระบวนการ **convert docx to text** อย่างเป็นทางการ + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*ทำไมเรื่องนี้สำคัญ:* `Document` คือการแสดงผลของไฟล์ Word ใน Aspose.Words การโหลดไฟล์ทำให้คุณเข้าถึงย่อหน้า ตาราง และแม้แต่ส่วนที่ซ่อนได้ หากไฟล์ไม่พบ Aspose จะโยน `FileNotFoundException` ที่ชัดเจน ทำให้คุณทราบทันทีว่ามีอะไรผิดพลาด + +--- + +## ขั้นตอนที่ 2: กำหนดค่า TxtSaveOptions สำหรับ Unicode (Plain text unicode) + +ไฟล์ plain‑text เป็นเพียงสตรีมของไบต์เท่านั้น ดังนั้นคุณต้องบอก Java ว่าจะใช้ชุดอักขระใด UTF‑8 เป็นมาตรฐานที่ใช้กันทั่วไปสำหรับ **plain text unicode** เนื่องจากสามารถเข้ารหัสทุกโค้ดพอยต์ของ Unicode ได้ + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **เคล็ดลับ:** หากคุณละเว้นการเรียก `setEncoding` Aspose จะใช้ charset เริ่มต้นของแพลตฟอร์ม ซึ่งบนเครื่อง Windows จำนวนมากคือ Windows‑1252 ค่าเริ่มต้นนี้จะทำให้ตัวอักษรเช่น “ß” หรือ “—” หายไปโดยไม่แจ้งเตือน + +--- + +## ขั้นตอนที่ 3: คงโครงสร้างตาราง (Optional, but handy for readability) + +เมื่อคุณ **export word as txt** ตารางมักจะถูกแปลงเป็นบรรทัดเดียวของข้อความ ทำให้อ่านยาก Aspose.Words มีแฟล็กง่าย ๆ เพื่อคงโครงสร้างภาพ + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*เมื่อใดควรใช้:* หาก DOCX ต้นทางของคุณมีใบแจ้งหนี้ ตารางเวลา หรือข้อมูลรูปแบบกริด การเปิดใช้งาน `PreserveTableLayout` จะใส่แท็บและการขึ้นบรรทัดใหม่เพื่อให้ไฟล์ที่ได้ยังคงคล้ายตาราง หากคุณไม่ต้องการก็สามารถละเว้นบรรทัดนี้เพื่อให้ผลลัพธ์กระชับขึ้น + +--- + +## ขั้นตอนที่ 4: บันทึกเอกสารเป็น Plain‑Text (Export word as txt) + +ตอนนี้งานหนักเสร็จแล้ว—เพียงเขียนไบต์ลงดิสก์ + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +การรันโปรแกรมจะสร้างไฟล์ `plain.txt` ในโฟลเดอร์เดียวกัน เปิดไฟล์ด้วยโปรแกรมแก้ไขข้อความใดก็ได้ (Notepad++, VS Code, หรือแม้แต่ `cat` ในเทอร์มินัล) แล้วคุณจะเห็น: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +สังเกตว่าคำทักทายภาษาญี่ปุ่นและอีโมจิยังคงอยู่ และตารางยังคงคอลัมน์ไว้ได้ด้วย `PreserveTableLayout` นั่นคือสาระสำคัญของการ **export docx to txt** ที่สะอาด + +--- + +## ขั้นตอนที่ 5: ตรวจสอบผลลัพธ์ (Convert word to text sanity check) + +การตรวจสอบความถูกต้องอย่างรวดเร็วช่วยป้องกันการสูญเสียข้อมูลโดยไม่รู้ตัว นี่คือวิธีบางอย่างเพื่อยืนยันว่าคุณ **convert word to text** อย่างถูกต้อง: + +1. **Checksum comparison** – คำนวณแฮช SHA‑256 ของไฟล์ `.txt` ก่อนและหลังการแปลงรอบ (txt → docx → txt) เพื่อให้แน่ใจว่าคงที่ +2. **Search for Unicode markers** – ใช้ `grep` หรือฟังก์ชันค้นหาใน IDE เพื่อหาตัวอักษรเช่น “😊” +3. **Open in multiple editors** – บางเวอร์ชันเกาของ Windows Notepad ยังตีความ UTF‑8 ผิดเมื่อไม่มี BOM; การเปิดไฟล์ใน VS Code จะยืนยันการเข้ารหัสที่ถูกต้อง + +หากการตรวจสอบใดล้มเหลว ให้ตรวจสอบอีกครั้งว่าได้ใส่ `saveOptions.setEncoding(StandardCharsets.UTF_8)` ไว้และไฟล์ DOCX ต้นทางของคุณมีข้อความ Unicode จริง ๆ + +--- + +## ปัญหาที่พบบ่อยและวิธีหลีกเลี่ยง + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Missing characters** | ชุดอักขระเริ่มต้นของระบบ (เช่น Windows‑1252) ทำให้ตัวอักษรที่ไม่ใช่ ASCII หายไป | ตั้งค่า UTF‑8 อย่างชัดเจนด้วย `saveOptions.setEncoding` | +| **Tables become a single line** | `PreserveTableLayout` ถูกปล่อยให้เป็นค่าเริ่มต้น `false` | เรียก `saveOptions.setPreserveTableLayout(true)` | +| **File not found** | เส้นทางผิดหรือไม่มีสิทธิ์อ่าน | ใช้เส้นทางแบบ absolute หรือ `Paths.get(...)` พร้อมการจัดการข้อยกเว้นที่เหมาะสม | +| **Performance slowdown on huge docs** | โหลดเอกสารทั้งหมดเข้าสู่หน่วยความจำ | สตรีมเอกสารเป็นชิ้นส่วนโดยใช้ `DocumentBuilder` หากคุณต้องการเฉพาะส่วนบางส่วน | + +--- + +## โบนัส: การส่งออกหลายไฟล์ DOCX เป็นชุด + +หากคุณต้องการ **convert docx to text** สำหรับโฟลเดอร์ทั้งหมด ให้ใส่ตรรกะในลูป: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +โค้ดส่วนนี้ **export docx to txt** สำหรับทุกไฟล์ในไดเรกทอรี ช่วยคุณประหยัดเวลาหลายชั่วโมงจากการทำงานด้วยมือ + +--- + +## สรุป + +คุณเพิ่งเรียนรู้วิธี **export docx to txt** ด้วย Java โดยทำให้ทุกอักขระ Unicode คงอยู่ ตารางอ่านง่าย และกระบวนการทั้งหมดทำซ้ำได้โดยง่าย ด้วยการกำหนดค่า `TxtSaveOptions` ให้เป็น UTF‑8 และเลือกคงโครงสร้างตาราง คุณสามารถ **convert docx to text**, **convert word to text**, และ **export word as txt** อย่างเชื่อถือได้สำหรับกระบวนการต่อเนื่องใด ๆ + +พร้อมสำหรับความท้าทายต่อไปหรือยัง? ลองส่งออกเป็นรูปแบบ plain‑text อื่น ๆ เช่น markdown (`.md`) หรือ CSV หรือสำรวจความสามารถการแปลงเป็น PDF ของ Aspose.Words หลักการเดียวกัน—การกำหนดการเข้ารหัสอย่างชัดเจน การคงโครงสร้าง และการตรวจสอบอย่างละเอียด—ใช้ได้กับทุกกรณี + +ขอให้เขียนโค้ดอย่างสนุกสนานและไฟล์ข้อความของคุณเต็มไปด้วย Unicode เสมอ! + +--- + +![แผนภาพแสดงกระบวนการส่งออก docx เป็น txt](/images/export-docx-to-txt-pipeline.png){alt="แผนภาพการส่งออก docx เป็น txt"} + +## บทแนะนำที่เกี่ยวข้อง + +- [แปลง Docx เป็น Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – แปลง DOCX เป็น PDF ด้วย Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [แปลง docx เป็น markdown – ส่งออกสมการคณิตศาสตร์เป็น LaTeX ด้วย Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/thai/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..b9cad563bd --- /dev/null +++ b/words/thai/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java และเพิ่มความสามารถในการเข้าถึง + PDF เรียนรู้การแปลง docx เป็น PDF, แท็กเส้นแนวนอน, และรับรองการปฏิบัติตามมาตรฐาน + PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: th +og_description: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java พร้อมเพิ่มการเข้าถึงให้กับ + PDF คู่มือขั้นตอนต่อขั้นตอนในการแปลง docx เป็น PDF และทำเครื่องหมายกฎแนวนอนเพื่อให้สอดคล้องกับ + PDF/UA‑2 +og_title: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java – ทำให้การเข้าถึงเป็นเรื่องง่าย +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java – คู่มือการเข้าถึงเต็มรูปแบบ +url: /th/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# บันทึกเอกสารเป็น PDF ด้วย Aspose.Words Java – คู่มือการเข้าถึงเต็มรูปแบบ + +เคยสงสัยไหมว่าจะแปลง **save document as PDF** อย่างไรให้ยังคงเข้าถึงได้สำหรับโปรแกรมอ่านหน้าจอ? คุณไม่ได้เป็นคนเดียวที่มีคำถามนี้ นักพัฒนาหลายคนต้องการ *convert docx to pdf* และยังคงมาตรฐาน PDF/UA‑2 โดยเฉพาะเมื่อแหล่งที่มามีเส้นแนวนอนที่ต้องทำแท็กอย่างถูกต้อง ในบทแนะนำนี้เราจะพาคุณผ่านขั้นตอนที่แน่นอนเพื่อ **save document as PDF** ด้วย Aspose.Words for Java, โดยอัตโนมัติ **add accessibility to PDF**, และทำให้ทุกเส้นแนวนอน **tagged** เป็น artifact + +เราจะเริ่มด้วยโครงการ Java ที่สะอาด, โหลดไฟล์ DOCX ที่มีเส้นแนวนอนอยู่แล้ว, ตั้งค่าตัวเลือกการบันทึก PDF ให้สอดคล้องกับ PDF/UA‑2, และสุดท้ายเขียนไฟล์ PDF ที่เข้าถึงได้เต็มรูปแบบ. เมื่อเสร็จสิ้นคุณจะสามารถ **save document as pdf** ด้วยความมั่นใจว่าผ่านการตรวจสอบการเข้าถึง + +## ข้อกำหนดเบื้องต้น + +- Java 8 หรือใหม่กว่า ติดตั้งแล้ว (บทแนะนำนี้ทดสอบบน JDK 17). +- Maven 3.6+ (หรือ Gradle หากคุณต้องการ) เพื่อจัดการ dependencies. +- ใบอนุญาต Aspose.Words for Java ที่ถูกต้อง (รุ่นทดลองใช้งานได้, แต่ใบอนุญาตจะลบลายน้ำการประเมิน). +- ไฟล์ DOCX (`input.docx`) ที่มีอย่างน้อยหนึ่งเส้นแนวนอน—คิดเป็นเส้นแบ่งง่าย ๆ ที่คุณเพิ่มใน Word. + +> **เคล็ดลับ:** หากคุณไม่มีไฟล์ DOCX พร้อมใช้งาน, เพียงสร้างเอกสาร Word ใหม่, พิมพ์ย่อหน้าบางส่วน, แทรก *Insert → Horizontal Line*, บันทึกเป็น `input.docx`, แล้ววางไว้ในโฟลเดอร์ที่คุณต้องการ. + +## ขั้นตอนที่ 1: ตั้งค่าโครงการ Maven + +แรก, สร้างโครงการ Maven ใหม่ (หรือเพิ่มในโครงการที่มีอยู่). ไฟล์ `pom.xml` ต้องมี dependency ของ Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **ทำไมเรื่องนี้สำคัญ:** การเพิ่ม artifact `aspose-words` เป็นขั้นตอนแรกในการ *convert docx to pdf*. หากไม่มี, คอมไพเลอร์จะไม่รู้จัก `Document`, `PdfSaveOptions`, และคลาสสำคัญอื่น ๆ. + +## ขั้นตอนที่ 2: โหลดไฟล์ DOCX ต้นฉบับที่มีเส้นแนวนอน + +ตอนนี้เราจะเขียนคลาส Java เล็ก ๆ ที่โหลดไฟล์ DOCX. นี่คือจุดเริ่มต้นของส่วน **tag horizontal rules**—Aspose.Words จะจัดการเส้นแนวนอนเป็นย่อหน้าที่มีขอบโดยอัตโนมัติ, แต่เราจะให้เอนจิน PDF/UA ทำการแท็ก. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +สังเกตว่าเรายังไม่ได้บันทึกอะไร—เราแค่ **loading** ไฟล์ DOCX, ซึ่งเป็นครึ่งแรกของ *convert docx to pdf*. วัตถุ `Document` ตอนนี้ถือเนื้อหา Word ทั้งหมด, รวมถึงเส้นแนวนอนที่คุณแทรก. + +## ขั้นตอนที่ 3: ตั้งค่าตัวเลือกการบันทึก PDF เพื่อให้สอดคล้องกับ PDF/UA‑2 + +ความมหัศจรรย์ของ **add accessibility to PDF** อยู่ใน `PdfSaveOptions`. โดยตั้งค่าระดับ compliance เป็น `PDF_UA_2`, Aspose.Words จะ: + +1. ทำแท็กให้กับองค์ประกอบโครงสร้าง (หัวเรื่อง, ตาราง, ฯลฯ). +2. ทำเครื่องหมายให้กับองค์ประกอบตกแต่ง—เช่นเส้นแนวนอน—เป็น *artifacts*, เพื่อให้โปรแกรมอ่านหน้าจอไม่สนใจ. +3. แทรกเมตาดาต้า PDF/UA ที่จำเป็น. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **ทำไมต้องตั้ง compliance?** หากไม่มี `PDF_UA_2`, PDF ที่ได้อาจยังอ่านได้แต่จะไม่ผ่านตัวตรวจสอบการเข้าถึงอัตโนมัติ. ความต้องการ **tag horizontal rules** จะได้รับการตอบสนองโดยอัตโนมัติเนื่องจาก PDF/UA จะถือว่าเป็น *artifacts* เมื่อเปิดค่าสถานะ compliance. + +## ขั้นตอนที่ 4: บันทึกเอกสารเป็น PDF + +ตอนนี้เราสุดท้ายก็ **save document as pdf**. บรรทัดเดียวนี้ทำงานหนัก—แปลง DOCX, ใส่แท็กการเข้าถึง, และเขียนไฟล์ลงดิสก์. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +เรียกใช้คลาส (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) แล้วคุณจะเห็นข้อความยืนยัน. เปิดไฟล์ `ua_compliant.pdf` ที่สร้างขึ้นใน Adobe Acrobat และตรวจสอบ **File → Properties → Description → PDF/A, PDF/UA**—คุณควรเห็น “PDF/UA‑2” ปรากฏ. + +### ผลลัพธ์ที่คาดหวัง + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +เปิด PDF, แล้วคุณจะสังเกตว่า: + +- ข้อความในเอกสารสามารถเลือกและค้นหาได้. +- เส้นแนวนอนไม่ปรากฏต่อโปรแกรมอ่านหน้าจอ (ถือเป็น artifact). +- PDF ผ่านเครื่องมือการตรวจสอบ PDF/UA เบื้องต้น (เช่น PAC 3). + +## ขั้นตอนที่ 5: ตรวจสอบการเข้าถึง – รายการตรวจสอบอย่างรวดเร็ว + +แม้ว่า Aspose.Words จะทำงานส่วนใหญ่, การตรวจสอบผลลัพธ์เป็นแนวปฏิบัติที่ดี. + +| ตรวจสอบ | วิธีตรวจสอบ | +|-------|----------------| +| **Document title** | เปิด Acrobat → File → Properties → ฟิลด์ Title (ควรตรงกับ `pdfOptions.setTitle`). | +| **Artifact tagging** | ใช้เครื่องมือ “Reading Order” ของ Acrobat. เส้นแนวนอนควรปรากฏเป็น *Artifact* (สีเทา). | +| **Logical reading order** | รัน “Accessibility Checker” ใน Acrobat; ตรวจสอบว่าไม่มีข้อผิดพลาดโครงสร้าง. | +| **Tagged PDF** | ใน Acrobat, ดูที่แผง “Tags” – คุณควรเห็นลำดับชั้น (Document → Section → Paragraph, ฯลฯ). | +| **PDF/UA compliance** | Acrobat จะแสดง “PDF/UA‑2” ใต้แท็บ “Standards”. | + +หากการตรวจสอบใดล้มเหลว, ให้ตรวจสอบอีกครั้งว่าคุณใช้เวอร์ชันล่าสุดของ Aspose.Words และว่า `setCompliance(PdfCompliance.PDF_UA_2)` ถูกตั้งค่าอย่างถูกต้อง. + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +1. **Missing License** – รุ่นทดลองเพิ่มลายน้ำที่อาจทำให้การตรวจสอบ PDF/UA ล้มเหลว. ใส่ใบอนุญาตของคุณตั้งแต่ต้นใน `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` จะหยุดการแปลง. ใช้เส้นทางแบบ absolute หรือวางไฟล์ DOCX ที่โฟลเดอร์รากของโครงการและอ้างอิงด้วย `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – การสนับสนุน PDF/UA ถูกเพิ่มในเวอร์ชัน 22.9. อัปเกรดเป็นรุ่นล่าสุดเพื่อหลีกเลี่ยงฟีเจอร์ที่หายไป. +4. **Horizontal Rule as Image** – หากคุณแทรกเส้นเป็นรูปภาพแทนการใช้เส้นแนวนอนของ Word, Aspose จะถือว่าเป็นรูปภาพปกติ, ไม่ใช่ artifact. แทนที่รูปภาพด้วย *Horizontal Line* ที่มาพร้อมใน Word เพื่อให้แท็กอย่างถูกต้อง. + +## การขยายโซลูชัน – ถ้าต้องการเพิ่มเติม? + +- **Custom Tags**: หากคุณมีองค์ประกอบตกแต่งอื่น (เช่นไอคอนตกแต่ง), คุณสามารถทำเครื่องหมายเป็น artifact ด้วยตนเองโดยใช้ `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: วนลูปผ่านโฟลเดอร์ของไฟล์ DOCX และแปลงเป็นชุด, ใช้ instance ของ `PdfSaveOptions` เดียวกันเพื่อประสิทธิภาพ. +- **Adding a Language Tag**: สำหรับ PDF หลายภาษา, ตั้งค่า `pdfOptions.setLanguage("en-US")` เพื่อช่วยเทคโนโลยีช่วยเหลือเลือกเสียงที่เหมาะ. + +## ตัวอย่างทำงานเต็ม (รวมโค้ดทั้งหมด) + +ด้านล่างเป็นโปรแกรม Java ที่สมบูรณ์และสามารถรันได้. คัดลอก‑วางลงใน IDE ของคุณ, ปรับเส้นทางตามต้องการ, แล้วรัน. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +รันโปรแกรม, เปิด PDF ที่สร้างขึ้น, แล้วคุณจะได้ไฟล์ที่สะอาดและเข้าถึงได้พร้อมสำหรับการแจกจ่าย. + +## สรุป + +เราได้สาธิตวิธี **save document as pdf** ด้วย Aspose.Words for Java พร้อมกับการ **add accessibility to pdf** โดยอัตโนมัติและ **tag horizontal rules** เป็น artifacts. สิ่งที่ควรจำ: + +- ใช้ `PdfSaveOptions` พร้อม compliance `PDF_UA_2` เพื่อให้ตรงตามมาตรฐานการเข้าถึง. +- การโหลด DOCX แล้วเรียก `doc.save(..., pdfOptions)` คือทั้งหมดที่คุณต้องการเพื่อ **convert docx to pdf**. +- เส้นแนวนอนจะถูกจัดการให้คุณ—ไม่ต้องเขียนโค้ดเพิ่มเติม, ตรงตามความต้องการ **tag horizontal rules**. +- วิธีนี้สอดคล้องกับ **aspose convert docx pdf** อย่างเต็มที่, ทำงานกับไลบรารีเวอร์ชันล่าสุด, และสร้าง PDF ที่พร้อมตรวจสอบ. + +พร้อมสำหรับความท้าทายต่อไป? ลองเพิ่มเมตาดาต้ากำหนดเอง, ฝังฟอนต์, หรือประมวลผลเป็นชุดของโฟลเดอร์ DOCX ทั้งหมด. แต่ละส่วนขยายเหล่านี้สร้างบนพื้นฐานเดียวกันที่เราได้อธิบายไว้. + +มีคำถามเกี่ยวกับการปฏิบัติตาม PDF/UA, ใบอนุญาต, หรือการจัดการองค์ประกอบ Word อื่น ๆ? แสดงความคิดเห็นหรือดูเอกสารอย่างเป็นทางการของ Aspose—มีตัวอย่างมากมายให้สำรวจ. ขอให้สนุกกับการเขียนโค้ดและสร้าง PDF ที่เข้าถึงได้! + +![save document as pdf using Aspose.Words Java – accessible PDF example](placeholder-image.png "save document as pdf using Aspose.Words Java") + +## Related Tutorials + +- [วิธีบันทึกเอกสารเป็น pdf ด้วย Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [วิธีแปลง Word เป็น PDF ด้วย Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – แปลง DOCX เป็น PDF ใน Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/thai/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..53c74a336f --- /dev/null +++ b/words/thai/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-26 +description: บันทึกไฟล์ Word เป็น markdown และค้นพบวิธีส่งออกสมการคณิตศาสตร์เป็น LaTeX + ด้วย Aspose.Words for Java. แปลงสมการ Word เป็น LaTeX เพียงไม่กี่บรรทัด. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: th +og_description: บันทึกไฟล์ Word เป็น Markdown และเรียนรู้วิธีส่งออกสมการคณิตศาสตร์เป็น + LaTeX ด้วย Aspose.Words สำหรับ Java คู่มือที่สมบูรณ์และสามารถทำงานได้ +og_title: บันทึกคำเป็น markdown – ส่งออกคณิตศาสตร์เป็น LaTeX ด้วย Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: บันทึก Word เป็น Markdown – ส่งออกคณิตศาสตร์เป็น LaTeX ด้วย Java +url: /th/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Save word as markdown – Export Math to LaTeX with Java + +เคยต้องการ **save word as markdown** แต่กังวลว่าสมการของคุณจะกลายเป็นข้อความที่สับสน? คุณไม่ได้อยู่คนเดียว ในคู่มือนี้เราจะพาคุณผ่าน **how to export math** จากไฟล์ `.docx` ไปยัง LaTeX โดยที่ส่วนที่เหลือของเอกสารจะกลายเป็น Markdown ที่สะอาด + +เราจะครอบคลุมทุกอย่างตั้งแต่การตั้งค่าไลบรารี Aspose.Words จนถึงการตรวจสอบไฟล์ `out.md` สุดท้าย เมื่อเสร็จคุณจะสามารถ **convert word equations latex** ด้วยการเรียกเมธอดเดียว และคุณจะเข้าใจรายละเอียดเล็ก ๆ ที่ทำให้การแปลงมีความน่าเชื่อถือ + +--- + +## สิ่งที่คุณต้องการ + +- **Java 8+** – โค้ดทำงานบน JDK เวอร์ชันล่าสุดใดก็ได้. +- **Aspose.Words for Java** – ไม่ว่าจะเป็นการพึ่งพา Maven/Gradle หรือไฟล์ JAR หากคุณต้องการตั้งค่าแบบแมนนวล. +- เอกสาร Word (`math.docx`) ที่มีอย่างน้อยหนึ่งสมการ Office Math. +- IDE หรือบรรทัดคำสั่ง `javac`/`java` ธรรมดา – ตามที่คุณถนัด. + +หากคุณมีทั้งหมดแล้ว เยี่ยมมาก หากยังไม่มี ส่วนต่อไปจะแสดงวิธีนำไลบรารีเข้าสู่โปรเจกต์ของคุณอย่างละเอียด + +## Save word as markdown – ขั้นตอนที่ 1: เพิ่ม Aspose.Words ลงในโปรเจกต์ของคุณ + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose มีไลเซนส์ชั่วคราวฟรีสำหรับการทดสอบ วางไฟล์ `license.xml` ในโฟลเดอร์ resources ของคุณและเรียก `License license = new License(); license.setLicense("license.xml");` ก่อนโหลดเอกสารใด ๆ + +เมื่อการพึ่งพาถูกแก้ไขแล้ว คุณพร้อมที่จะเขียนโค้ดการแปลงแล้ว + +## วิธีการส่งออกสมการคณิตศาสตร์เป็น LaTeX + +การทำงานหลักทำโดย `MarkdownSaveOptions` โดยการสลับ `OfficeMathExportMode` ของมันเป็น `LATEX` ทุกวัตถุ Office Math จะถูกแปลงเป็นส่วนย่อย LaTeX ภายในผลลัพธ์ Markdown + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### ทำไมวิธีนี้ถึงได้ผล + +- **`Document`** คือจุดเริ่มต้นของ Aspose; มันเป็นการนามธรรมของไฟล์ `.docx` และให้คุณเข้าถึงทุกโหนดรวมถึงสมการ. +- **`MarkdownSaveOptions`** บอกไลบรารีว่า *อย่างไร* ที่คุณต้องการผลลัพธ์ พฤติกรรมเริ่มต้นคือการแสดงสมการเป็นรูปภาพ ซึ่งขัดกับจุดประสงค์ของรูปแบบที่เป็นข้อความ. +- **`OfficeMathExportMode.LATEX`** บังคับให้เอนจินแปลงแต่ละโหนด `OfficeMath` ให้เป็นรูปแบบ LaTeX ที่สอดคล้องกัน ซึ่งตัวแยกวิเคราะห์ Markdown (เช่น GitHub หรือ Jekyll) สามารถแสดงผลได้เมื่อรวมกับปลั๊กอิน MathJax. + +## Convert word equations LaTeX – ขั้นตอนที่ 2: ตรวจสอบผลลัพธ์ Markdown + +หลังจากรันโปรแกรมแล้ว เปิดไฟล์ `out.md` คุณควรเห็นสิ่งคล้ายกับนี้: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** ส่วนย่อย LaTeX จะถูกล้อมด้วย `$…$` สำหรับคณิตศาสตร์แบบอินไลน์และ `$$…$$` สำหรับคณิตศาสตร์แบบบล็อก นี่เป็นไวยากรณ์มาตรฐานที่เครื่องสร้างเว็บไซต์แบบสถิติจำนวนมากเข้าใจเมื่อเปิดใช้งาน MathJax. + +หากคุณต้องการให้สมการอยู่ในรูปแบบอินไลน์เท่านั้น คุณสามารถปรับ `MarkdownSaveOptions` เพิ่มเติมได้: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx to markdown latex – ขั้นตอนที่ 3: กรณีขอบและข้อผิดพลาดทั่วไป + +| สถานการณ์ | สิ่งที่ควรระวัง | วิธีแก้ | +|-----------|-------------------|-----| +| **Complex nested equations** | Aspose อาจสร้างวงเล็บปีกกาเพิ่มเติม `{}` ที่บางตัวแยกวิเคราะห์อาจตีความตามตัวอักษร. | ประมวลผลหลัง Markdown ด้วย regex ง่าย ๆ เพื่อยุบ `{{` → `{`. | +| **Missing MathJax on the target site** | สมการปรากฏเป็นโค้ด LaTeX ดิบ. | เพิ่ม `` ลงในเทมเพลต HTML ของคุณ. | +| **Large documents** | การใช้หน่วยความจำพุ่งสูงเนื่องจากโหลดเอกสารทั้งหมดพร้อมกัน. | ใช้ `LoadOptions.setLoadFormat(LoadFormat.DOCX)` และพิจารณาประมวลผลหน้าเป็นชุดถ้าพบ `OutOfMemoryError`. | +| **License not set** | คุณจะได้รับคำเตือนและผลลัพธ์อาจมีลายน้ำ. | โหลดไลเซนส์ตั้งแต่ต้นใน `main` ตามที่แสดงในเคล็ดลับ Maven ด้านบน. | + +## Save word as markdown – ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นคลาสที่ทำงานอิสระซึ่งคุณสามารถคัดลอกและวางลงในโปรเจกต์ Java ใดก็ได้ เพียงแทนที่ `YOUR_DIRECTORY` ด้วยพาธไปยังไฟล์ของคุณ. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +รันโปรแกรม (`java MathToLatexMarkdown`) แล้วคุณจะเห็นข้อความในคอนโซลยืนยันความสำเร็จ เปิดไฟล์ `out.md` ในโปรแกรมแก้ไขใดก็ได้ – สมการควรเป็นส่วนย่อย LaTeX ที่สะอาดพร้อมสำหรับการแสดงผล. + +## ตัวอย่างผลลัพธ์ที่คาดหวัง + +![ผลลัพธ์การบันทึก word เป็น markdown พร้อมสมการ LaTeX](https://example.com/images/markdown-latex-output.png "ผลลัพธ์การบันทึก word เป็น markdown พร้อมสมการ LaTeX") + +*ภาพแสดงส่วนย่อยของ Markdown ที่สร้างขึ้นซึ่งสมการ `\int_{a}^{b} f(x)\,dx` ถูกล้อมด้วย `$$`.* + +## สรุป + +เราเพิ่งสาธิตวิธี **save word as markdown** พร้อมคงสมการ Office Math ทุกสมการเป็น LaTeX ดั้งเดิม ขั้นตอนสำคัญคือการกำหนดค่า `MarkdownSaveOptions` ด้วย `OfficeMathExportMode.LATEX` ซึ่งทำให้กระบวนการแปลงจาก Word ไปเป็น Markdown ปกติกลายเป็นเครื่องมือแปลงที่รับรู้คณิตศาสตร์อย่างเต็มรูปแบบ. + +ตอนนี้คุณสามารถ: + +1. **How to export math** จากไฟล์ `.docx` ใดก็ได้โดยไม่สูญเสียความแม่นยำ. +2. **Convert word equations latex** สำหรับเครื่องสร้างเว็บไซต์แบบสถิติ, เอกสาร, หรือบล็อกเชิงวิชาการ. +3. ขยายวิธีการเพื่อประมวลผลหลายไฟล์เป็นชุด, ผสานกับ CI pipelines, หรือแม้แต่สร้างเว็บเซอร์วิสขนาดเล็ก. + +หากคุณสนใจขอบเขตต่อไป ลองผสานวิธีนี้กับ **docx to markdown latex** สำหรับเอกสารที่มีรูปภาพจำนวนมาก, หรือสำรวจ `HtmlSaveOptions` ของ Aspose เพื่อเวอร์ชัน HTML ที่พร้อมใช้งานบนเว็บ ความเป็นไปได้ไม่มีที่สิ้นสุด—ทดลอง, ทำให้เกิดข้อผิดพลาด, แล้วแชร์ผลลัพธ์ของคุณกับชุมชน! + +มีคำถามหรือสมการที่ซับซ้อนซึ่งไม่แสดงผลตามที่คาดไว้? แสดงความคิดเห็นด้านล่าง แล้วขอให้สนุกกับการเขียนโค้ด! + +## บทแนะนำที่เกี่ยวข้อง + +- [วิธีส่งออก LaTeX จาก Word: แปลง DOCX เป็น Markdown & บันทึกเป็น PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [แปลง docx เป็น markdown – ส่งออกสมการคณิตศาสตร์เป็น LaTeX ด้วย Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [วิธีแปลง Word เป็น PDF ด้วย Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/thai/java/document-loading-and-saving/_index.md index 9b47ff9142..fb0301d1b3 100644 --- a/words/thai/java/document-loading-and-saving/_index.md +++ b/words/thai/java/document-loading-and-saving/_index.md @@ -93,6 +93,7 @@ Aspose.Words for Java ทำให้การ **บันทึกภาพจ ### [การบันทึกเอกสารเป็นไฟล์ข้อความใน Aspose.Words for Java](./saving-documents-as-text-files/) ### [การกำหนดรูปแบบเอกสารใน Aspose.Words for Java](./determining-document-format/) ### [กู้ไฟล์ docx ที่เสีย – คู่มือฉบับเต็มสำหรับการแก้ไขและประมวลผลเอกสาร](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [เปิดไฟล์ Word ที่เสีย – ตั้งค่าโหมดการกู้คืนใน Java](./open-corrupted-word-document-set-recovery-mode-in-java/) ### [บันทึกคำเตือนการแทนที่ฟอนต์ใน Java ด้วย Aspose.Words – คู่มือฉบับสมบูรณ์](./capture-font-substitution-warnings-in-java-with-aspose-words/) ## คำถามที่พบบ่อย diff --git a/words/thai/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/thai/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..d5a7a2f39a --- /dev/null +++ b/words/thai/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,190 @@ +--- +category: general +date: 2026-05-26 +description: เปิดเอกสาร Word ที่เสียหายใน Java ด้วย Aspose.Words. เรียนรู้วิธีตั้งค่าโหมดการกู้คืนและกู้ไฟล์ + Word ที่เสียหายได้อย่างน่าเชื่อถือ. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: th +og_description: เปิดเอกสาร Word ที่เสียหายใน Java ด้วย Aspose.Words คู่มือนี้แสดงวิธีตั้งค่าโหมดการกู้คืนและกู้คืนไฟล์ + Word ที่เสียหายอย่างมีประสิทธิภาพ +og_title: เปิดเอกสาร Word ที่เสียหาย – ตั้งค่าโหมดการกู้คืนใน Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: เปิดไฟล์ Word ที่เสียหาย – ตั้งค่าโหมดการกู้คืนใน Java +url: /th/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# เปิดไฟล์ Word ที่เสีย – ตั้งค่าโหมดการกู้คืนใน Java + +เคยลองเปิดไฟล์ Word ที่เสียและเห็นโปรแกรมหยุดทำงานด้วยข้อยกเว้นหรือไม่? คุณไม่ได้เป็นคนเดียว—ไฟล์ .docx ที่เสียเหล่านั้นอาจทำให้ศีรษะปวด ข่าวดีคือ Aspose.Words for Java ให้คุณควบคุมได้ละเอียดเพื่อที่คุณจะสามารถ **เปิดไฟล์ Word ที่เสีย** โดยไม่ทำให้แอปพัง, และยังสามารถเลือกว่าจะให้แสดงคำเตือน, การกู้คืนแบบเงียบ, หรือการปฏิเสธอย่างเด็ดขาด + +ในบทแนะนำนี้เราจะเดินผ่านกระบวนการทั้งหมด: ตั้งแต่การสร้าง `LoadOptions` ที่เหมาะสม, การเลือกค่าของ **set recovery mode** ที่เหมาะสม, และสุดท้ายยืนยันว่าเอกสารถูกโหลดสำเร็จแล้ว. เมื่อจบคุณจะรู้ **how to recover corrupted word file** ด้วยโปรแกรม, ไม่ต้องคัดลอก‑วางด้วยตนเอง + +> **สิ่งที่คุณต้องการ** +> * Java 8 หรือใหม่กว่า (API ทำงานกับ Java 11 ด้วยเช่นกัน) +> * Aspose.Words for Java 23.9 (หรือเวอร์ชันล่าสุด) +> * ไฟล์ .docx ที่เสียตัวอย่าง—เพียงเปลี่ยนชื่อไฟล์ที่ใช้งานได้ใด ๆ เพื่อจำลองการเสียหายหากคุณไม่มีไฟล์พร้อมใช้งาน + +Let’s dive in. + +## เปิดไฟล์ Word ที่เสีย – ภาพรวมขั้นตอนโดยละเอียด + +ต่อไปนี้คือกระบวนการระดับสูงที่เราจะดำเนินการ: + +1. **Create `LoadOptions`** – วัตถุนี้บอก Aspose.Words ว่าจะทำอย่างไรเมื่อเจอปัญหา. +2. **Set recovery mode** – เลือก `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, หรือ `REJECT_CORRUPTED`. +3. **Load the document** โดยใช้ตัวเลือกที่กำหนดค่าไว้. +4. **Verify** การโหลดสำเร็จ (เช่น พิมพ์จำนวนหน้า). + +แต่ละขั้นตอนจะอธิบายอย่างละเอียด พร้อมตัวอย่างโค้ดที่คุณสามารถคัดลอก‑วางโดยตรงลงใน IDE ของคุณ. + +## ตั้งค่าโหมดการกู้คืนสำหรับสถานการณ์ต่าง ๆ + +Aspose.Words กำหนดกลยุทธ์การกู้คืนสามแบบภายใน `LoadOptions.RecoveryMode`: + +| โหมด | พฤติกรรม | เมื่อใช้ | +|------|-----------|----------| +| `RECOVER_WITH_WARNINGS` | พยายามโหลดเอกสาร แต่แสดงปัญหาใด ๆ เป็นคำเตือนในคอนโซล. | คุณต้องการดู *ว่า* สิ่งใดผิดพลาดโดยไม่หยุดการทำงาน. | +| `RECOVER_WITHOUT_WARNINGS` | แก้ไขโดยเงียบ ๆ สิ่งที่ทำได้และซ่อนคำเตือน. | สภาพแวดล้อมการผลิตที่ต้องการให้บันทึกสะอาด. | +| `REJECT_CORRUPTED` | ขว้างข้อยกเว้นทันทีที่ตรวจพบความเสียหาย. | กระบวนการตรวจสอบที่เข้มงวดซึ่งต้องล้มเหลวอย่างรวดเร็ว. | + +การเลือกโหมดที่เหมาะสมนั้นเป็นหัวใจของการใช้ **set recovery mode** อย่างถูกต้อง. ในการดีบักส่วนใหญ่ `RECOVER_WITH_WARNINGS` เป็นจุดที่เหมาะที่สุดเพราะมันบอกคุณอย่างชัดเจนว่ามีส่วนใดบ้างที่ถูกซ่อมแซม. + +## วิธีการกู้คืนไฟล์ Word ที่เสียโดยใช้ Aspose.Words + +ต่อไปนี้เป็น **โปรแกรม Java ที่สมบูรณ์และสามารถรันได้** ที่แสดงกระบวนการทั้งหมด. คุณสามารถวางลงในไฟล์ `RecoveryModeDemo.java`, ปรับเส้นทาง, แล้วรันได้เลย. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### ทำไมแต่ละบรรทัดจึงสำคัญ + +* **`LoadOptions loadOptions = new LoadOptions();`** – หากไม่มีวัตถุนี้ Aspose.Words จะใช้การกู้คืนค่าเริ่มต้น ซึ่ง *ปฏิเสธ* ไฟล์ที่เสีย. การสร้างมันให้คุณมีจุดเชื่อมต่อเพื่อเปลี่ยนพฤติกรรมนั้น. +* **`setRecoveryMode(...)`** – นี่คือการเรียก **set recovery mode** ที่กำหนดว่าคำเตือนจะแสดง, ซ่อน, หรือทำให้เกิดข้อยกเว้น. +* **`new Document(path, loadOptions);`** – ตัวสร้างรับ `LoadOptions` ที่เราตั้งค่าไว้, ดังนั้นไลบรารีจะรู้ว่าจะจัดการไฟล์ที่เสียอย่างไรตั้งแต่แรก. +* **`doc.getPageCount()`** – การตรวจสอบอย่างรวดเร็ว. หากเอกสารถูกโหลดและคืนค่าจำนวนหน้า, คุณได้ทำ **how to recover corrupted word file** สำเร็จแล้ว. +* **`doc.save(...)`** – เป็นตัวเลือกแต่สะดวก; คุณสามารถบันทึกเวอร์ชันที่ซ่อมแซมกลับไปยังดิสก์เพื่อใช้ในภายหลัง. + +## การจัดการกรณีขอบที่พบบ่อย + +### 1. ไม่พบไฟล์ + +หากเส้นทางผิด, `Document` จะขว้าง `FileNotFoundException`. ห่อการโหลดในบล็อก try‑catch และบันทึกข้อความที่เป็นมิตร: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. ความเสียหายที่ไม่สามารถกู้คืนได้ + +แม้จะใช้ `RECOVER_WITH_WARNINGS`, โครงสร้างบางอย่างก็เกินกว่าจะซ่อมแซมได้. ในกรณีนั้น Aspose.Words ยังโหลดสิ่งที่ทำได้, แต่คุณจะเห็นคำเตือนเช่น “Cannot read paragraph properties”. ให้ใส่ใจผลลัพธ์ในคอนโซล; คำเตือนเหล่านั้นมักชี้ไปยังส่วนที่หายไปซึ่งคุณอาจต้องสร้างใหม่ด้วยตนเอง. + +### 3. ไฟล์ขนาดใหญ่และประสิทธิภาพ + +การกู้คืนเพิ่มภาระเล็กน้อยเนื่องจากไลบรารีต้องวิเคราะห์ไฟล์สองครั้ง—ครั้งแรกเพื่อตรวจจับปัญหา, ครั้งที่สองเพื่อสร้างใหม่. สำหรับเอกสารหลายกิกะไบต์, พิจารณา stream ไฟล์หรือเพิ่ม heap ของ JVM (`-Xmx2g`) เพื่อหลีกเลี่ยง `OutOfMemoryError`. + +## เคล็ดลับระดับมืออาชีพ – ทำให้การกู้คืนมั่นคง + +* **Log warnings to a file** – เปลี่ยนการส่งออก `System.err` ไปยัง logger เพื่อให้คุณมีบันทึกการตรวจสอบว่ามีอะไรถูกแก้ไข. +* **Validate after recovery** – เรียก `doc.updatePageLayout();` แล้วตรวจสอบจำนวนหน้าใหม่; บางครั้งการจัดวางเปลี่ยนหลังจากซ่อมแซมส่วนที่เสีย. +* **Automate batch recovery** – ห่อเดโมในลูปที่ประมวลผลโฟลเดอร์ของไฟล์ที่เสีย, ใช้ `LoadOptions` เดียวกันทุกครั้ง. + +## สรุป + +ตอนนี้คุณรู้วิธี **how to recover corrupted word file** ด้วย Aspose.Words for Java อย่างแม่นยำ. ด้วยการสร้างอินสแตนซ์ `LoadOptions`, **set recovery mode** ให้เป็นกลยุทธ์ที่เหมาะกับสถานการณ์ของคุณ, และโหลดเอกสารด้วยตัวเลือกเหล่านั้น, คุณสามารถ **เปิดไฟล์ Word ที่เสีย** อย่างปลอดภัยโดยไม่ทำให้แอปพัง. ตัวอย่างโค้ดข้างต้นเป็นโซลูชันที่สมบูรณ์และพร้อมรันที่พิมพ์จำนวนหน้าและแม้แต่บันทึกสำเนาที่ทำความสะอาดแล้ว. + +ต่อไปคุณจะทำอะไร? ลองสลับโหมดการกู้คืนเป็น `RECOVER_WITHOUT_WARNINGS` และเปรียบเทียบผลลัพธ์ในคอนโซล, หรือทดลองโหลดเอกสารที่เข้ารหัส (คุณจะต้องให้รหัสผ่านผ่าน + +## บทแนะนำที่เกี่ยวข้อง + +- [Aspose.Words Java: คู่มือครอบคลุมการประมวลผลเอกสาร Word](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [วิธีแปลง Word เป็น PDF ด้วย Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [วิธีเปรียบเทียบไฟล์ Word สองไฟล์ด้วย Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/thai/java/document-styling/_index.md index 14b6cb043c..4697c34e54 100644 --- a/words/thai/java/document-styling/_index.md +++ b/words/thai/java/document-styling/_index.md @@ -42,7 +42,9 @@ Aspose.Words for Java มอบเครื่องมืออันทรง ### [การใส่ลายน้ำเอกสารและการตั้งค่าหน้า](./document-watermarking-page-setup/) เรียนรู้วิธีการใช้ลายน้ำและตั้งค่าคอนฟิกูเรชันหน้าด้วย Aspose.Words สำหรับ Java คู่มือที่ครอบคลุมพร้อมโค้ดต้นฉบับ ### [การจัดรูปแบบส่วนหัวและส่วนท้ายเอกสาร](./document-header-footer-styling/) -เรียนรู้วิธีกำหนดรูปแบบส่วนหัวและส่วนท้ายของเอกสารโดยใช้ Aspose.Words สำหรับ Java ในคู่มือโดยละเอียดนี้ มีคำแนะนำทีละขั้นตอนและโค้ดต้นฉบับรวมอยู่ด้วย +เรียนวิธีกำหนดรูปแบบส่วนหัวและส่วนท้ายของเอกสารโดยใช้ Aspose.Words สำหรับ Java ในคู่มือโดยละเอียดนี้ มีคำแนะนำทีละขั้นตอนและโค้ดต้นฉบับรวมอยู่ด้วย +### [ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words สำหรับ Java – คู่มือเต็ม](./set-default-font-settings-in-aspose-words-for-java-complete/) +เรียนรู้วิธีตั้งค่าฟอนต์เริ่มต้นสำหรับเอกสารด้วย Aspose.Words สำหรับ Java พร้อมตัวอย่างโค้ดต้นฉบับ {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/thai/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..f7692f6312 --- /dev/null +++ b/words/thai/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-26 +description: ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words for Java และเรียนรู้วิธีตั้งค่าฟอนต์และตรวจจับฟอนต์ที่หายไปด้วยเพียงไม่กี่บรรทัดของโค้ด +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: th +og_description: ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words for Java, เรียนรู้วิธีตั้งค่าฟอนต์และตรวจจับฟอนต์ที่หายไปอย่างรวดเร็วและเชื่อถือได้. +og_title: ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words สำหรับ Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words สำหรับ Java – คู่มือฉบับสมบูรณ์ +url: /th/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words for Java – คู่มือฉบับสมบูรณ์ + +เคยสงสัยไหมว่าจะแ**ตั้งค่าฟอนต์เริ่มต้น**อย่างไรเมื่อโหลดเอกสาร Word ด้วย Aspose.Words for Java? คุณไม่ได้เป็นคนเดียวที่มีคำถามนี้ ตัวอักษรที่หายไปอาจทำให้รายงานที่ดูดีกลายเป็นข้อความสับสน และการจับคำเตือนการแทนที่ฟอนต์ตั้งแต่แรกจะช่วยประหยัดเวลาการดีบักหลายชั่วโมง + +ในบทแนะนำนี้เราจะพาคุณผ่านตัวอย่างสั้น ๆ แบบครบวงจรที่ **ตั้งค่าฟอนต์เริ่มต้น**, แสดงวิธี **ตั้งค่าฟอนต์** ด้วยโปรแกรม, และสาธิตวิธีที่เชื่อถือได้ในการ **ตรวจจับฟอนต์ที่หายไป** ก่อนที่มันจะทำให้เลย์เอาต์ของคุณพัง + +--- + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีสร้างอ็อบเจ็กต์ `LoadOptions` พร้อมอินสแตนซ์ `FontSettings` ใหม่ +- วิธีแนบตัวฟังการเตือนที่ **ตรวจจับฟอนต์ที่หายไป** ระหว่างการโหลดเอกสาร +- วิธีโหลดไฟล์ DOCX พร้อมให้ตัวฟังรายงานการแทนที่โดยเงียบ ๆ +- เคล็ดลับการปรับแต่งฟอนต์สำรองและจัดการกรณีขอบในสภาพการผลิต + +ไม่มีไลบรารีเพิ่มเติม, ไม่มีไฟล์กำหนดค่าที่ซับซ้อน—เพียงแค่ Java ธรรมดาและ Aspose.Words + +--- + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะลงลึก, โปรดตรวจสอบว่าคุณมี: + +1. **Aspose.Words for Java** (เวอร์ชัน 23.10 หรือใหม่กว่า) อยู่ใน classpath ของคุณ +2. ชุดพัฒนา Java 17 (หรือใหม่กว่า) – JDK สมัยใหม่ใดก็ได้ +3. ไฟล์ DOCX ที่ตั้งใจใช้ฟอนต์ที่คุณไม่ได้ติดตั้ง (เช่น *“MissingFont.ttf”*) + +หากคุณยังไม่มีไฟล์ JAR ของ Aspose, ดาวน์โหลดได้จาก Maven repository อย่างเป็นทางการ: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +เท่านี้—ไม่ต้องติดตั้งฟอนต์เพิ่มเติมสำหรับการสาธิตนี้ + +--- + +## ขั้นตอนที่ 1: สร้าง LoadOptions และ **ตั้งค่าฟอนต์เริ่มต้น** + +สิ่งแรกที่เราต้องการคืออ็อบเจ็กต์ `LoadOptions` ที่สะอาดซึ่งบอก Aspose ว่าจะทำอย่างไรเมื่อเจอฟอนต์ที่ไม่รู้จัก โดยการเรียก `setFontSettings(new FontSettings())` เรา **ตั้งค่าฟอนต์เริ่มต้น** ที่เริ่มต้นด้วยรายการฟอนต์สำรองว่างเปล่า + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** +> เมื่อคุณไม่ได้กำหนดค่าฟอนต์อย่างชัดเจน, Aspose จะย้อนกลับไปใช้คอลเลกชันฟอนต์เริ่มต้นของระบบ, ซึ่งอาจทำให้ปัญหาฟอนต์ที่หายไปไม่ถูกสังเกตเห็น การเริ่มจาก `FontSettings` ใหม่ทำให้คุณควบคุมได้เต็มที่ว่าฟอนต์ใดถือว่าเป็นฟอนต์ที่ถูกต้อง + +--- + +## ขั้นตอนที่ 2: แนบตัวฟังการเตือนเพื่อ **ตรวจจับฟอนต์ที่หายไป** + +Aspose จะสร้างอ็อบเจ็กต์ `WarningInfo` สำหรับการแทนที่แต่ละครั้ง โดยการฟัง `WarningType.FONT_SUBSTITUTION` เราสามารถ **ตรวจจับฟอนต์ที่หายไป** ทันทีที่เอกสารถูกพาร์ส + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **เคล็ดลับระดับมืออาชีพ:** ตัวฟังทำงานบนเธรดเดียวกับการโหลดเอกสาร, ดังนั้นจึงแทบไม่มีผลกระทบต่อประสิทธิภาพ หากคุณต้องการเก็บคำเตือนเพื่อนำไปวิเคราะห์ต่อ, ให้ผลักข้อมูลลงใน `List` แทนการพิมพ์ออกโดยตรง + +--- + +## ขั้นตอนที่ 3: โหลดเอกสารโดยใช้ตัวเลือกที่กำหนดไว้ + +ตอนนี้เราได้ **ตั้งค่าฟอนต์** และเตรียมตัวฟังแล้ว, เราก็เพียงโหลดไฟล์. ฟอนต์ใดที่หายไปจะกระตุ้นคอลแบ็กของเราทันที + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +หากไฟล์ต้นทางอ้างอิงฟอนต์ที่ไม่ได้ติดตั้ง, คุณจะเห็นผลลัพธ์คล้ายกับ: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +บรรทัดนั้นบอกคุณโดยตรงว่าฟอนต์ใดหายไปและฟอนต์สำรองใดที่ถูกใช้—เหมาะสำหรับการบันทึกหรือแจ้งผู้ใช้ + +--- + +## ขั้นตอนที่ 4: ดำเนินการต่อปกติ (ตามต้องการ) + +ในขณะนี้เอกสารถูกโหลดเต็มที่แล้ว, คุณสามารถทำการปรับแต่งต่อได้ตามต้องการ—แก้ไข, แปลงเป็น PDF, หรือดึงข้อความออก ตัวฟังการเตือนได้ทำหน้าที่แล้ว, ดังนั้นคุณไม่จำเป็นต้องตรวจสอบเพิ่มเติม + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **ถ้าต้องการฟอนต์สำรองแบบกำหนดเอง?** +> แทนที่จะปล่อยให้ `FontSettings` ว่างเปล่า, คุณสามารถเพิ่มฟอนต์เฉพาะได้: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +ตอนนี้ฟอนต์ใดที่หายไปจะถูกแทนที่ด้วย *Times New Roman*—เป็นตัวเลือกที่เชื่อถือได้สำหรับเอกสารตะวันตกส่วนใหญ่ + +--- + +## ภาพรวมโดยรวม + +![แผนภาพแสดงวิธีตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words for Java](image.png "แผนภาพของกระบวนการตั้งค่าฟอนต์เริ่มต้น") + +*ข้อความแทน: กระบวนการตั้งค่าฟอนต์เริ่มต้นใน Aspose.Words for Java* + +แผนภาพแสดงขั้นตอนจากการเริ่มต้น `LoadOptions` (ที่เรา **ตั้งค่าฟอนต์เริ่มต้น**) ไปจนถึงการแนบตัวฟังการเตือน (เพื่อ **ตรวจจับฟอนต์ที่หายไป**) และสุดท้ายการโหลดเอกสาร + +--- + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| ข้อผิดพลาด | สาเหตุ | วิธีแก้ | +|------------|--------|--------| +| **ลืมเรียก `setFontSettings`** | Aspose ใช้ค่าตั้งต้นของระบบ, ทำให้ฟอนต์ที่หายไปไม่แสดง | สร้างอินสแตนซ์ `FontSettings` ใหม่และกำหนดให้กับ `LoadOptions` เสมอ | +| **ตัวฟังไม่ทำงาน** | ตัวฟังถูกเพิ่มหลังจากโหลดเอกสาร | เพิ่มตัวฟังการเตือน *ก่อน* เรียก `new Document(...)` | +| **พิมพ์พาธผิดทำให้เกิด `FileNotFoundException`** | พาธที่กำหนดแบบคงที่ไม่ตรงกับความละเอียดของระบบปฏิบัติการ | ใช้ `Paths.get("...").toAbsolutePath()` หรือกำหนดพาธสัมพันธ์จากรูทของโปรเจกต์ | +| **ฟอนต์ที่หายไปหลายตัวทำให้บันทึกเต็ม** | เอกสารขนาดใหญ่อาจสร้างคำเตือนหลายสิบรายการ | กรองคำซ้ำหรือรวมข้อความใน `Set` ก่อนพิมพ์ | + +--- + +## การขยายโซลูชัน + +หากคุณต้องการ **ตั้งค่าฟอนต์** สำหรับแอปพลิเคชันทั้งหมด, พิจารณาสร้าง `FontSettings` แบบ singleton และใช้ซ้ำในทุก `LoadOptions`. วิธีนี้ทำให้กลยุทธ์ฟอนต์สำรองสอดคล้องกันและลดการสร้างอ็อบเจ็กต์ซ้ำ ๆ + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +ตอนนี้ส่วนใดของโค้ดก็สามารถเรียก `FontConfig.getLoadOptions()` เพื่อรับประโยชน์จากตรรกะ **ตั้งค่าฟอนต์เริ่มต้น** เดียวกันได้ทันที + +--- + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **ตั้งค่าฟอนต์เริ่มต้น** ใน Aspose.Words for Java, **ตั้งค่าฟอนต์** ผ่านโปรแกรม, และ **ตรวจจับฟอนต์ที่หายไป** ก่อนที่มันจะทำลายผลลัพธ์ของคุณ ตัวอย่างที่ทำงานได้เต็มรูปแบบอยู่ในโค้ดสแนปช็อตข้างต้น, คุณสามารถคัดลอกไปวางใน IDE ของคุณเพื่อดูคำเตือนทำงานจริง + +ขั้นตอนต่อไป? ลองเปลี่ยนฟอนต์สำรอง, ทดลองกับรูปแบบเอกสารอื่น ๆ (DOC, RTF, HTML), หรือผสานตัวเก็บคำเตือนเข้ากับแดชบอร์ดการตรวจสอบ. ยิ่งคุณเล่นกับ `FontSettings` มากเท่าไหร่, ความมั่นใจว่าดอกเอกสารที่สร้างขึ้นจะดูตรงตามที่ต้องการก็จะยิ่งสูง—ไม่มีเซอร์ไพรส์, ไม่มีอักขระหายไป + +มีคำถามหรือกรณีการแทนที่ฟอนต์ที่ซับซ้อน? แสดงความคิดเห็นด้านล่าง, แล้วขอให้สนุกกับการเขียนโค้ด! + +## บทแนะนำที่เกี่ยวข้อง + +- [Set Font Fallback Settings](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Set Font Fallback Settings](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/java/images-shapes/_index.md b/words/thai/java/images-shapes/_index.md index 8a4880b0dd..51eea35d66 100644 --- a/words/thai/java/images-shapes/_index.md +++ b/words/thai/java/images-shapes/_index.md @@ -37,6 +37,9 @@ ### [สร้างเอกสาร Word ด้วย Java – เพิ่มรูปสี่เหลี่ยมผืนผ้าพร้อมเงา](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) เรียนรู้วิธีเพิ่มรูปสี่เหลี่ยมผืนผ้าพร้อมเงาในเอกสาร Word ด้วย Aspose.Words สำหรับ Java +### [สร้างรูปสี่เหลี่ยมผืนผ้าในเอกสาร Word ด้วย Java – คู่มือเต็มขั้นตอน](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +เรียนรู้วิธีสร้างรูปสี่เหลี่ยมผืนผ้าในเอกสาร Word ด้วย Aspose.Words สำหรับ Java อย่างละเอียดขั้นตอนต่อขั้นตอน + ## แหล่งข้อมูลเพิ่มเติม - [เอกสาร Aspose.Words สำหรับ Java](https://reference.aspose.com/words/java/) diff --git a/words/thai/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/thai/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..004629ec73 --- /dev/null +++ b/words/thai/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-05-26 +description: สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java และใช้เอฟเฟกต์เงา เรียนรู้วิธีเพิ่มเงาให้รูปทรง + ตั้งค่าระยะเงา และบันทึกไฟล์ +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: th +og_description: สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java, ใช้เอฟเฟกต์เงา, เพิ่มเงารูป, + และตั้งค่าระยะห่างของเงาด้วย Aspose.Words. +og_title: สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java – คู่มือฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java – คู่มือขั้นตอนเต็ม +url: /th/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java – คู่มือเต็มขั้นตอน + +เคยต้องการ **create rectangle shape** ในเอกสาร Word ด้วย Java แต่ไม่แน่ใจว่าจะเริ่มอย่างไรหรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนาหลายคนเจออุปสรรคนี้เมื่อสร้างรายงานหรือใบแจ้งหนี้โดยอัตโนมัติ ในบทเรียนนี้เราจะอธิบายขั้นตอนการ **create rectangle shape**, การเพิ่มเงาที่ดูเรียบหรู, และการปรับระยะห่างของเงาให้ผลลัพธ์ดูเป็นมืออาชีพ + +เราจะใช้ Aspose.Words for Java ซึ่งเป็นไลบรารีที่แข็งแรงที่ช่วยให้คุณจัดการไฟล์ Word ได้โดยไม่ต้องติดตั้ง Microsoft Office เมื่อคุณอ่านจบคู่มือนี้คุณจะสามารถสร้างโปรเจกต์ **create word document java** ที่ **add shape shadow**, **apply shadow effect**, และ **set shadow distance** ด้วยเพียงไม่กี่บรรทัดของโค้ด + +--- + +## สิ่งที่คุณจะสร้าง + +- ไฟล์ `.docx` ใหม่ที่มีสี่เหลี่ยมสีฟ้าไซอาน +- เงาตกที่ดูสมจริง มีการเบลอ มีมุม และมีความโปร่งแสงบางส่วน +- ควบคุมระยะห่างของเงาจากรูปได้เต็มที่ +- คลาส Java ที่พร้อมรันที่คุณสามารถใส่ลงในโปรเจกต์ Maven หรือ Gradle ใดก็ได้ + +ไม่มีเครื่องมือภายนอก ไม่มีขั้นตอน UI แบบมือ—เพียงโค้ดเท่านั้น + +--- + +## ข้อกำหนดเบื้องต้น + +- Java 8 หรือใหม่กว่า (โค้ดทำงานบน Java 11, Java 17 เป็นต้น) +- ไลบรารี Aspose.Words for Java (สามารถดาวน์โหลดได้จาก Maven Central) +- IDE หรือโปรแกรมแก้ไขข้อความที่คุณชอบ (IntelliJ IDEA, Eclipse, VS Code…) +- ความคุ้นเคยพื้นฐานกับไวยากรณ์ Java + +หากคุณยังไม่เคยเพิ่ม dependency ของ Maven มาก่อน นี่คือตัวอย่างสั้น ๆ: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +ต่อไป เรามาเริ่มกันเลย + +--- + +## ขั้นตอนที่ 1: สร้างรูปสี่เหลี่ยมในเอกสาร Word + +สิ่งแรกที่เราต้องการคือเอกสารเปล่าและ `DocumentBuilder` คิดว่า builder เป็นเหมือนปากกาที่เขียนลงในเอกสาร เมื่อเรามีแล้ว เราสามารถ **create rectangle shape** ด้วยการเรียกเมธอดเดียว + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **ทำไมเรื่องนี้สำคัญ:** เมธอด `insertShape` ไม่เพียงสร้างรูปทรงเรขาคณิตเท่านั้น แต่ยังเพิ่มรูปลงในคอลเลกชันภายในของเอกสาร ทำให้คุณสามารถเริ่มจัดสไตล์ได้ทันที + +--- + +## ขั้นตอนที่ 2: เพิ่มเอฟเฟกต์เงาให้กับรูป + +เมื่อสี่เหลี่ยมอยู่บนหน้าแล้ว เราจะ **apply shadow effect** เงาช่วยเพิ่มความลึก ทำให้รูปดูเหมือนลอยขึ้นจากหน้า—การปรับ UI ที่ละเอียดอ่อนซึ่งสามารถเพิ่มความอ่านง่ายในรายงาน + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **เคล็ดลับ:** ค่าเบลอ `5.0` ดูเป็นธรรมชาติสำหรับเอกสารที่แสดงบนหน้าจอส่วนใหญ่ หากคุณพิมพ์อาจต้องการค่าต่ำกว่านี้เล็กน้อยเพื่อหลีกเลี่ยงลักษณะเบลอ + +--- + +## ขั้นตอนที่ 3: ตั้งค่าระยะห่างของเงา – ปรับตำแหน่งอย่างละเอียด + +เงาไม่ได้เกี่ยวกับการเบลอเท่านั้น; ยังต้องการการเลื่อนตำแหน่งที่เหมาะสม นี่คือจุดที่เราจะ **set shadow distance** ระยะ `7.0` จุดให้การเลื่อนที่พอเหมาะ สังเกตได้แต่ไม่เกินไป + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **ถ้าต้องการเลื่อนมากขึ้น?** เพิ่มค่าดังกล่าว; ลดค่าหากต้องการลุคที่กระชับ จำไว้ว่า ระยะห่างทำงานร่วมกับมุมเพื่อกำหนดตำแหน่งเงาอย่างถูกต้อง + +--- + +## ขั้นตอนที่ 4: บันทึกเอกสาร – เก็บงานของคุณ + +สุดท้าย เราจะเขียนเอกสารลงดิสก์ เปลี่ยนเส้นทางให้เป็นตำแหน่งที่คุณต้องการให้ไฟล์อยู่ + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +การรันคลาสจะสร้างไฟล์ `shadow.docx` ซึ่งเมื่อเปิดใน Microsoft Word หรือ LibreOffice จะเห็นสี่เหลี่ยมสีไซอานพร้อมเงาสีเทานุ่มที่มีมุม 45° และเลื่อนออกไป 7 จุด + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโค้ดที่พร้อมคัดลอก‑วางครบถ้วน รวมถึงการ import ทั้งหมด, คอมเมนต์, และการเรียก `save` สุดท้าย + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง:** เปิด `shadow.docx` → คุณจะเห็นสี่เหลี่ยมสีไซอานอยู่กึ่งกลางหน้าแรก, ปล่อยเงาสีเทานุ่มที่เลื่อนเล็กน้อยไปด้านล่าง‑ขวา การเบลอและความโปร่งแสงของเงาทำให้ดูเหมือนแสงธรรมชาติ + +--- + +## คำถามทั่วไป & กรณีขอบ + +### “ฉันสามารถใช้รูปแบบอื่นได้หรือไม่?” + +แน่นอน. แทนที่ `ShapeType.RECTANGLE` ด้วย `ShapeType.OVAL`, `ShapeType.LINE`, หรือ enum ที่รองรับอื่น ๆ ส่วนของโค้ดเงาจะคงเดิม + +### “ถ้าต้องการหลายเงา?” + +Aspose.Words รองรับเงาเพียงหนึ่งเงาต่อรูปเท่านั้น เพื่อจำลองหลายเงา ให้ทำสำเนารูป, เลื่อนตำแหน่งแต่ละสำเนา, และปรับความโปร่งแสง + +### “เงาแสดงผลใน LibreOffice หรือไม่?” + +ใช่—Aspose.Words เขียนเป็น OOXML มาตรฐาน ซึ่ง LibreOffice สามารถตีความได้อย่างถูกต้อง เงาอาจดูแตกต่างเล็กน้อยเนื่องจากเครื่องยนต์การเรนเดอร์ แต่เอฟเฟกต์ยังคงอยู่ + +### “ฉันจะเปลี่ยนสีเงาให้ตรงกับแบรนด์ของฉันได้อย่างไร?” + +เพียงเปลี่ยน `java.awt.Color.GRAY` เป็น `java.awt.Color` ใดก็ได้ที่คุณต้องการ เช่น `new java.awt.Color(0, 120, 215)` สำหรับสีน้ำเงินขององค์กร + +--- + +## ภาพประกอบ + +![สร้างรูปสี่เหลี่ยมในเอกสาร Word ด้วย Java](https://example.com/images/rectangle-shadow.png) + +*ข้อความแทนภาพ:* **create rectangle shape** แสดงภาพสี่เหลี่ยมสีไซอานพร้อมเงาตกสีเทาในเอกสาร Word. + +--- + +## สรุป & ขั้นตอนต่อไป + +เราได้อธิบายวิธี **create rectangle shape**, **apply shadow effect**, **add shape shadow**, และ **set shadow distance** ด้วย Aspose.Words for Java โค้ดเป็นอิสระ สามารถทำงานบน JDK สมัยใหม่ใดก็ได้ และสร้างไฟล์ `.docx` ที่เรียบหรูพร้อมสำหรับการแจกจ่าย + +ต้องการทำต่อ? ลอง: + +- เพิ่มข้อความภายในสี่เหลี่ยมด้วย `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- สร้างตารางของรูปเพื่อสร้างแผนภาพ. +- ส่งออกเอกสารเป็น PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +แต่ละข้อเหล่านี้อิงจากพื้นฐานเดียวกันที่เราได้สำรวจไว้ ทำให้คุณรู้สึกสบายใจในการขยายตัวอย่าง + +--- + +## ความคิดสุดท้าย + +การเชี่ยวชาญงาน **create word document java** เช่น การสร้างรูปและการใส่เงา จะให้คุณได้เปรียบอย่างมากเมื่อทำอัตโนมัติรายงาน, สัญญา, หรือสื่อการตลาด วิธีการที่แสดงในนี้เป็นระเบียบ, ดูแลรักษาได้ง่าย, และ—ที่สำคัญที่สุด—ปรับแต่งได้ง่ายสำหรับสไตล์ภาพใด ๆ ที่คุณต้องการ + +ลองใช้โค้ดนี้, ปรับค่าเบลอ, มุม, และระยะห่าง, แล้วดูเอกสารของคุณเปลี่ยนจากธรรมดาเป็นเรียบหรู หากคุณเจอปัญหาใด ๆ ฝากคอมเมนต์ด้านล่าง; ฉันยินดีช่วยเหลือ + +ขอให้เขียนโค้ดอย่างสนุก! + +--- + +## บทเรียนที่เกี่ยวข้อง + +- [สร้างเอกสาร Word ด้วย Java – เพิ่มรูปสี่เหลี่ยมพร้อมเอฟเฟกต์เงา](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [วิธีสร้างฟิลด์ฟอร์มและเพิ่มเนื้อหาโดยใช้ DocumentBuilder ใน Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [สร้าง PDF จาก Word พร้อมการสร้างบาร์โค้ด – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/turkish/java/document-conversion-and-export/_index.md index c0dab2e906..48b0571ccd 100644 --- a/words/turkish/java/document-conversion-and-export/_index.md +++ b/words/turkish/java/document-conversion-and-export/_index.md @@ -92,9 +92,15 @@ Aspose.Words for Java’da tabloları biçimlendirmeyi ve tablo stilleri uygulam ### [Aspose.Words for Java'da docx'i markdown'a dönüştürme – Matematik denklemlerini LaTeX'e dışa aktarma](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Aspose.Words kullanarak docx dosyasını markdown’a dönüştürün ve matematik denklemlerini LaTeX formatına dışa aktarın. +### [Aspose.Words for Java'da Word'ü markdown olarak kaydet – Matematik denklemlerini LaTeX'e dışa aktar Java ile](./save-word-as-markdown-export-math-to-latex-with-java/) +Aspose.Words for Java kullanarak Word belgelerini markdown formatına kaydedin ve matematik denklemlerini LaTeX koduna dışa aktarın. + ### [Belgeyi TXT Olarak Kaydet – Word Matematiğini Dışa Aktarma Hızlı Rehberi](./save-document-as-txt-quick-guide-to-exporting-word-math/) Aspose.Words for Java kullanarak belgeyi TXT formatına kaydedin ve Word matematik denklemlerini dışa aktarın. +### [Java ile docx'i txt olarak dışa aktarma – Tam programlama rehberi](./export-docx-to-txt-with-java-complete-programming-guide/) +Aspose.Words for Java kullanarak docx dosyasını txt formatına dönüştürün ve metni dışa aktarın. + ### [Aspose Word to PDF – Java’da DOCX'i PDF'e Dönüştürme](./aspose-word-to-pdf-convert-docx-to-pdf-in-java/) Aspose.Words for Java kullanarak DOCX dosyalarını hızlı ve doğru bir şekilde PDF formatına dönüştürün. @@ -104,6 +110,14 @@ DOCX dosyasından tam erişilebilir PDF oluşturmayı, etiket eklemeyi ve erişi ### [DOCX Dönüştürürken Markdown'a Görüntü Gömme](./how-to-embed-images-in-markdown-when-converting-docx/) DOCX dosyalarından Markdown'a dönüştürürken resimleri nasıl gömeceğinizi adım adım öğrenin. +### [DOCX'i Markdown'a Dönüştürürken Görüntüleri Base64 Olarak Gömme](./embed-images-as-base64-when-converting-docx-to-markdown/) +DOCX dosyalarındaki resimleri Base64 formatında Markdown'a gömerek sorunsuz dönüşüm sağlayın. + +### [Aspose.Words for Java'da Belgeyi PDF Olarak Kaydet – Tam Erişilebilirlik Kılavuzu](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) + +### [Aspose.Words for Java'da Erişilebilir PDF Oluşturma – Tam Etiketleme Kılavuzu](./create-accessible-pdf-in-java-full-tagging-guide/) +Aspose.Words for Java kullanarak tam etiketli, erişilebilir PDF dosyaları oluşturmayı adım adım öğrenin. + ## Sık Sorulan Sorular **S: Aspose.Words kullanarak mevcut bir PDF’e nasıl filigran eklerim?** diff --git a/words/turkish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/turkish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..8c7b4cd68e --- /dev/null +++ b/words/turkish/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-26 +description: Java'da adım adım kodla erişilebilir PDF oluşturun. PDF'yi erişilebilirlik + için nasıl etiketleyeceğinizi öğrenin ve PdfSaveOptions kullanarak PDF etiketlemeyi + etkinleştirin. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: tr +og_description: Adım adım kodla Java’da erişilebilir PDF oluşturun. PDF’yi erişilebilirlik + için nasıl etiketleyeceğinizi ve PdfSaveOptions kullanarak PDF etiketlemeyi nasıl + etkinleştireceğinizi öğrenin. +og_title: Java’da Erişilebilir PDF Oluşturma – Tam Etiketleme Rehberi +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Java'da Erişilebilir PDF Oluşturma – Tam Etiketleme Rehberi +url: /tr/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java'da Erişilebilir PDF Oluşturma – Tam Etiketleme Rehberi + +Java kodundan doğrudan **erişilebilir PDF** dosyaları oluşturmayı hiç merak ettiniz mi? Tek başınıza değilsiniz. Birçok geliştirici, ekran okuyuculara güvenen kullanıcıları desteklemek zorunda ve sade bir PDF ile erişilebilir bir PDF arasındaki fark çok büyük olabilir. Bu öğreticide **PDF'yi erişilebilirlik için nasıl etiketleyeceğinizi**, Aspose PDF for Java ile **etiketli PDF nasıl oluşturulur** konusunu adım adım gösterecek ve **PDF'ye erişilebilirlik etiketleri ekleme** adımlarını ortaya koyacağız, böylece her okuyucu aynı bilgiyi alabilir. + +Ayrıca **PDF etiketlemeyi etkinleştirme** en iyi uygulamalarını, yaygın tuzakları ve bugün projenize ekleyebileceğiniz tam, çalıştırılabilir bir örneği de ele alacağız. Belirsiz referanslar yok—sadece somut kod, açıklamalar ve etiketleri doğrulamak için Adobe Acrobat'ta açabileceğiniz bir dosya. + +## Öğrenecekleriniz + +- PDF etiketlemesinin ve erişilebilirlik uyumluluğunun nedenleri. +- Önkoşullar ve kütüphane kurulumu (Aspose PDF for Java 23.10 veya daha yeni). +- Sıfırdan **erişilebilir PDF** nasıl **oluşturulur**, adım adım. +- Temel `setTagDocumentStructure` çağrısının ötesinde **PDF'ye erişilebilirlik etiketleri ekleme** yolları. +- Çıktıyı test etme ve yaygın sorunları giderme ipuçları. + +Bu rehberin sonunda, WCAG 2.1 AA kontrollerini geçen ve aynı zamanda profesyonel görünen PDF'ler oluşturabilecek duruma geleceksiniz. + +--- + +## Önkoşullar + +Derinlemesine incelemeden önce, şunların olduğundan emin olun: + +| Requirement | Reason | +|-------------|--------| +| **Java 8+** | Modern dil özellikleri ve daha iyi Unicode işleme. | +| **Aspose PDF for Java** (v23.10 or newer) | `PdfSaveOptions` sınıfını ve etiketleme desteğini sağlar. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, vb.) | Kolay derleme ve hata ayıklama için. | +| **Write permission** to a folder where the PDF will be saved | `doc.save` çağrısının yazılabilir bir yol gerektirdiği klasöre izin. | + +Henüz projenize Aspose PDF eklemediyseniz, aşağıdaki Maven bağımlılığını `pom.xml` dosyanıza ekleyin: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Pro ipucu:** En son sürümü kullanın; daha yeni sürümler etiketleme doğruluğunu artırır ve dile‑özel erişilebilirlik özellikleri ekler. + +--- + +## Adım 1: Belge İskeletini Oluşturun + +İlk olarak yeni bir `Document` nesnesi oluşturuyoruz. Bunu, daha sonra erişilebilirlik için ihtiyaç duyacağımız etiketleri tutacak boş bir tuval olarak düşünün. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Neden önemli:** İçerik olmadan etiketlenecek bir şey yoktur. Basit bir `TextFragment` eklemek, etiketleme motoruna bir şeyler sağlar ve daha sonra yapı etiketlemeyi etkinleştirdiğimizde otomatik olarak bir `

` (paragraf) etiketi oluşturur. + +--- + +## Adım 2: PDF Kaydetme Seçeneklerini Oluşturun (Etiketlemenin Çekirdeği) + +Şimdi Aspose PDF'in dosyanın içine mantıksal bir yapı ağacı gömmesini sağlayan seçenekleri hazırlıyoruz. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +`setTagDocumentStructure(true)` çağrısı **PDF etiketlemeyi etkinleştirme** anahtarıdır. True olduğunda, kütüphane görsel düzeni yansıtan bir etiket ağacı oluşturur ve PDF'i yardımcı teknolojiler tarafından okunabilir hâle getirir. + +> **Not:** Bu, **etiketli pdf nasıl oluşturulur** sorusunun en basit yoludur. Daha ayrıntılı kontrol için (örneğin dil ayarlama veya özel etiketler), `pdfOptions.setTagLanguage("en-US")` ve `pdfOptions.setTagStructureTreeRoot(...)` yöntemlerini keşfedebilirsiniz. + +--- + +## Adım 3: Erişilebilir PDF'yi Kaydedin + +Son olarak, az önce yapılandırdığımız seçenekleri kullanarak belgeyi diske yazıyoruz. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +`doc.save` tamamlandığında, `output` klasöründe `accessible.pdf` dosyasını bulacaksınız. Adobe Acrobat'ta açın ve **File → Properties → Description → Tags** bölümüne bakın – doldurulmuş bir etiket ağacı görmelisiniz. + +--- + +## PDF'yi Erişilebilirlik İçin Etiketleme – Temel Ötesi + +Yukarıdaki üç adımlı kod parçacığı zaten **PDF'ye erişilebilirlik etiketleri ekliyor**, ancak gerçek dünyadaki belgeler genellikle biraz daha ince ayar gerektirir. İşte ekleyebileceğiniz birkaç iyileştirme: + +### 1. Belge Dilini Ayarlayın + +Ekran okuyucular, metni doğru telaffuz etmek için dil özniteliğini kullanır. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Başlık ve Konu Sağlayın + +Meta veriler, yardımcı araçların dosyayı açmadan önce bağlam sağlamasına yardımcı olur. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Görsellere Alternatif Metin Etiketi Ekleyin + +Resim ekliyorsanız, `alt` açıklamaları eklemeniz gerekir. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Tablo Başlıklarını İşaretleyin + +Tablolar, başlık satırlarını işaretlemediğiniz sürece okuyucuları karıştırmasıyla ünlüdür. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Bu ek adımlar PDF'nizin sadece *teknik* olarak etiketlenmesini değil, aynı zamanda çeşitli bir kitle için gerçekten **erişilebilir** olmasını sağlar. + +--- + +## PDF Etiketlemeyi Etkinleştirirken Yaygın Tuzaklar + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Acrobat'ta etiketler eksik | `setTagDocumentStructure` `false` bırakılmış | `pdfOptions.setTagDocumentStructure(true)` çağrısını yaptığınızdan emin olun. | +| Yanlış okuma sırası | Açık etiketler olmadan karmaşık düzen | Özel bir sıra tanımlamak için `pdfOptions.setTagStructureTreeRoot(...)` kullanın. | +| Görseller “image” olarak açıklama olmadan okunuyor | Alternatif metin ayarlanmamış | `image.getAlternativeText().setValue("...")` çağrısını yapın. | +| Dil tanınmıyor | `setTagLanguage` atlanmış veya yanlış yerel ayar | BCP‑47 dil kodu sağlayın (`en-US`, `fr-FR`). | + +Bu sorunların farkında olmak, ileride saatler süren hata ayıklamayı önler. + +--- + +## Sonucu Doğrulama – Neler Beklenir + +Programı çalıştırdıktan sonra, `output/accessible.pdf` dosyasını Adobe Acrobat Reader'da açın: + +1. **Etiketler paneli** (`View → Show/Hide → Navigation Panes → Tags`) `/Document → /Part → /Sect → /Para` gibi bir hiyerarşi listelemelidir. +2. **Okuma sırası** görsel akışı izlemelidir (önce metin, ardından görseller). +3. **Ekran okuyucu** (NVDA, VoiceOver) sadece “Page 1” yerine “Hello, accessible PDF!” okuyacaktır. + +Bu öğelerden herhangi biri eksikse, yukarıdaki adımları—özellikle `setTagDocumentStructure` çağrısını—tekrar kontrol edin. + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + + + +## İlgili Öğreticiler + +- [Word'den Erişilebilir PDF Oluştur – PDF/UA'ya Dönüştür](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [DOCX'ten Erişilebilir PDF Oluştur – Tam Kılavuz](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Aspose.Words for Java ile belgeyi PDF olarak kaydetme](/words/english/java/document-loading-and-saving/saving-documents-as-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/turkish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/turkish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..78dededca1 --- /dev/null +++ b/words/turkish/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java ile docx'i markdown'a dönüştürürken görüntüleri + base64 olarak gömün. Word'ü markdown'a dönüştürmeyi, Word'ü markdown olarak kaydetmeyi + ve görüntüleri yönetmeyi öğrenin. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: tr +og_description: Aspose.Words for Java ile docx'i markdown'a dönüştürürken görüntüleri + base64 olarak gömün. Word'ü markdown'a dönüştürmek ve Word'ü markdown olarak kaydetmek + için tam rehber. +og_title: DOCX'i Markdown'a Dönüştürürken Görselleri Base64 Olarak Göm +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: DOCX'i Markdown'a Dönüştürürken Görselleri Base64 Olarak Göm +url: /tr/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX'i Markdown'a Dönüştürürken Görselleri Base64 Olarak Gömme + +Hiç **embed images as base64** yaparken **convert docx to markdown** yapmayı merak ettiniz mi? Tek başınıza değilsiniz—geliştiriciler sürekli olarak görselleri ayrı dosyalarla uğraşmadan satır içinde tutmanın yolunu soruyor. İyi haber şu ki Aspose.Words for Java bu işi çocuk oyuncağı haline getiriyor: bir Word belgesini Markdown'a dönüştürebilir ve her resmi otomatik olarak bir Base64 dizesi olarak gömebilirsiniz. + +Bu öğreticide tüm süreci adım adım inceleyeceğiz—görseller içeren bir `.docx` dosyasını yüklemekten, işi yapan `MarkdownSaveOptions` geri çağrısını yapılandırmaya ve sonunda sonucu temiz bir `.md` dosyası olarak kaydetmeye kadar. Sonunda **convert word to markdown**, **convert images to base64**, ve **save word as markdown** nasıl yapılacağını tam olarak bileceksiniz ve gereksiz görüntü klasörleri bırakmayacaksınız. Harici araçlar yok, manuel post‑processing yok—sadece herhangi bir projeye ekleyebileceğiniz saf Java kodu. + +## İhtiyacınız Olanlar + +- **Java 17** (veya herhangi bir yeni JDK) – kod lambda sözdizimini kullanıyor, ancak daha eski sürümlere uyarlayabilirsiniz. +- **Aspose.Words for Java** kütüphanesi (2026 itibarıyla en son sürüm). Maven bağımlılığını ekleyin veya JAR'ı sınıf yolunuza ekleyin. +- En az bir görsel içeren örnek bir **DOCX** dosyası. +- Bir IDE ya da basit bir metin düzenleyici—Visual Studio Code, IntelliJ IDEA veya hatta `vim` yeterli. + +Eğer bunlara zaten sahipseniz, harika—hemen başlayalım. + +## Adım 1: Word Belgesini Yükleyin + +İlk olarak, kaynak dosyayı işaret eden bir `Document` örneği oluştururuz. Bu adım, **convert docx to markdown** yapıyor olun ya da dosyayı başka amaçlarla okuyor olun aynı kalır. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Neden önemli:** `Document` nesnesi her Aspose işleminin giriş noktasıdır. Görseller, tablolar ve stiller dahil tüm Word yapısını tutar—böylece sonraki geri çağrı her kaynağı inceleyebilir. + +## Adım 2: MarkdownSaveOptions Oluşturun ve Resource‑Saving Geri Çağrısını Kaydedin + +Sihir `MarkdownSaveOptions` içinde yaşar. Bir `IResourceSavingCallback` ekleyerek her dış kaynağın (örneğin bir görselin) nasıl yazılacağını kontrol ederiz. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Neden `setSaveToMemory(true)` Kullanılır? + +`saveToMemory` true olduğunda, Aspose görsel baytlarını bir dosya yerine bellek akışına yazar. Markdown dışa aktarıcı daha sonra bu akışı bir Base64 dizesine dönüştürür ve doğrudan Markdown görsel etiketine ekler: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Bu, **embed images as base64**'in özüdür. + +## Adım 3: Belgeyi Markdown Olarak Kaydedin + +Geri çağrı yerinde olduğuna göre, son adım sadece `save` metodunu çağırmak. İşte burada gerçekten **convert word to markdown** yapıyoruz ve geri çağrı sayesinde aynı zamanda **convert images to base64** de gerçekleştiriyoruz. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Sonuç:** `out.md` her görselin bir `data:` URI'si olarak temsil edildiği Markdown metni içerir. Diskte ekstra görsel dosyaları oluşturulmaz, böylece klasör düzenli kalır. + +## Adım 4: Çıktıyı Doğrulayın ve Yaygın Tuzaklar + +Oluşturulan `out.md` dosyasını herhangi bir Markdown görüntüleyicide (VS Code, GitHub veya statik site jeneratörü) açın. Şuna benzer bir şey görmelisiniz: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Sorun Giderme Kontrol Listesi + +| Issue | Likely Cause | Fix | +|-------|--------------|-----| +| Görsel bozuk bir bağlantı olarak görünüyor | `setSaveToMemory` atlanmış | `args.setSaveToMemory(true);`'nin geri çağrı içinde olduğundan emin olun | +| Base64 dizesi kesiliyor | Çıktı dosyası kodlaması uyuşmazlığı | Markdown'ı UTF‑8 kullanarak kaydedin (Aspose için varsayılan) | +| Beklenmeyen dosya adları | `setKeepResourceOriginalName(true)` | `false` olarak tutun, böylece özel adlandırma mantığı zorlanır | + +## Adım 5: İleri Düzey Varyasyonlar (Opsiyonel) + +### Yalnızca Seçili Görselleri Dönüştür + +Eğer sadece belirli görselleri (örneğin 100 KB'den büyük olanları) gömmek istiyorsanız, bir boyut kontrolü ekleyin: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Farklı Bir Görsel Formatı Kullanma + +`ResourceSavingArgs` size ham baytları verir, bu yüzden gömmeden önce JPEG'leri PNG'ye yeniden kodlayabilirsiniz—hedef Markdown okuyucusu PNG tercih ettiğinde faydalıdır. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Bu ince ayarlar, **embed images as base64** yaklaşımının **convert docx to markdown** yaparken ne kadar esnek olduğunu gösterir. + +## Sonuç + +Aspose.Words for Java kullanarak **embed images as base64** yaparken **convert docx to markdown** nasıl yapılacağını yeni öğrendiniz. Basit bir `IResourceSavingCallback` bağlayarak, kütüphane tüm işi üstlenir: **convert word to markdown**, **convert images to base64**, ve sonunda tek bir `save` çağrısıyla **save word as markdown** yapar. + +Denemekten çekinmeyin—farklı görsel filtreleme kuralları deneyin, HTML çıktısına geçin veya bu adımı bir statik site jeneratörüyle zincirleyin. Aynı desen diğer formatlar (HTML, EPUB) için de çalışır, böylece ihtiyacınız olan her yerde geri çağrıyı yeniden kullanabilirsiniz. + +**Sonraki adımlar:** +- HTML‑with‑Base64 görselleri için `HtmlSaveOptions` keşfedin. +- Bu adımı bir CI pipeline'ı ile birleştirerek dokümantasyon üretimini otomatikleştirin. +- Dönüştürme sürecinde daha ince kontrol gerekiyorsa Aspose’un `DocumentVisitor`'ına göz atın. + +Kodlamaktan keyif alın ve temiz, kendine yeterli Markdown dosyalarınızın tadını çıkarın! + +## İlgili Öğreticiler + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/turkish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..79dec8b26e --- /dev/null +++ b/words/turkish/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-05-26 +description: Java ve Aspose.Words kullanarak docx'i txt'ye aktarın. Docx'i metne nasıl + dönüştüreceğinizi, Unicode'u koruyacağınızı ve kelimeyi birkaç adımda txt olarak + dışa aktaracağınızı öğrenin. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: tr +og_description: Java'da docx'i txt'ye dışa aktar. Bu öğretici, docx'i metne nasıl + dönüştüreceğinizi, düz metin Unicode'u koruyarak ve kelimeyi verimli bir şekilde + txt olarak dışa aktaracağınızı gösterir. +og_title: Java ile docx'i txt'ye Dışa Aktarma – Tam Rehber +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Java ile docx'i txt'ye Dışa Aktarma – Tam Programlama Rehberi +url: /tr/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java ile docx'i txt'ye Dışa Aktarma – Tam Programlama Rehberi + +Hiç **export docx to txt** yapmanız gerekti ama özel karakterlerin kaybolmasından endişelendiniz mi? Tek başınıza değilsiniz. Word belgelerini düz‑metin dosyalarına dönüştürdüğünüzde Unicode sembolleri, tablolar ve hatta basit biçimlendirme sihir gibi yok olabilir. + +Bu rehberde, Aspose.Words for Java kullanarak **export docx to txt** işlemini güvenilir bir şekilde nasıl yapacağınızı, her Unicode karakterini koruyarak tablo düzenlerini okunabilir tutmayı adım adım göstereceğiz. Sonunda **convert docx to text**, **convert word to text** ve hatta **export word as txt** işlemlerini sorunsuz bir şekilde nasıl yapacağınızı da öğreneceksiniz. + +## Bu Eğitimde Neler Ele Alınacak + +* Java projesinde Aspose.Words kurulumunun yapılması +* DOCX dosyasının yüklenmesi ve düz‑metin çıktısı için hazırlanması +* `TxtSaveOptions` ile **plain text unicode** desteğinin yapılandırılması +* Oluşan `.txt` dosyasında tabloların okunabilir kalmasını sağlayan isteğe bağlı ipuçları +* Dosyanın kaydedilmesi ve çıktının doğrulanması + +Harici betikler, gizemli komut‑satırı araçları yok—sadece Maven ya da Gradle projenize ekleyebileceğiniz saf Java kodu. + +> **Neden Önemli?** Düz‑metin dosyaları hafiftir, sürüm‑kontrol dostudur ve arama‑indeksleme ya da sonraki işleme hatları için mükemmeldir. Bir Word dosyasını `cat` ile açıp anlamsız karakterler gördüyseniz, bu eğitim sorunu çözer. + +--- + +## Export docx to txt – Genel Bakış + +Koda geçmeden önce terminolojiyi netleştirelim. **Export docx to txt**, bir Microsoft Word `.docx` paketini alıp metinsel içeriğini basit bir `.txt` dosyasına yazmak anlamına gelir. PDF dönüşümünün aksine, metin dışa aktarımı stil bilgilerini atar ancak satır sonlarını, paragraf işaretlerini ve—doğru yapılandırırsanız—emoji, aksanlı harfler ya da Asya dilleri gibi Unicode karakterlerini koruyabilir. + +Aspose.Words bu süreci sorunsuz hâle getirir; Word dosya formatını soyutlar ve kodlama, tablo işleme vb. ayarları yapabileceğiniz bir `TxtSaveOptions` sınıfı sunar. + +### Önkoşullar + +* Java 11 veya daha yeni (API Java 8+ ile çalışır, ancak güncel bir JDK varsayacağız) +* Aspose.Words for Java JAR (Maven Central üzerinden temin edilebilir) +* Çeşitli Unicode karakterler içeren bir örnek `unicode.docx` dosyası – örneğin “こんにちは”, “😊” ve basit bir tablo + +Eğer bunlara sahipseniz, başlayalım. + +--- + +## Step 1: Load the DOCX File (Convert docx to text) + +İlk olarak kaynak belgeyi belleğe okumanız gerekir. İşte **convert docx to text** sürecinin resmi başlangıcı. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Bu neden önemli:* `Document`, Aspose.Words’ün bir Word dosyasını temsil eden sınıfıdır. Yükleyerek tüm paragraf, tablo ve hatta gizli öğelere erişim sağlarsınız. Dosya bulunamazsa Aspose net bir `FileNotFoundException` fırlatır, böylece hatayı hemen görürsünüz. + +## Step 2: Configure TxtSaveOptions for Unicode (Plain text unicode) + +Düz‑metin dosyaları sadece bayt akışıdır, bu yüzden Java’ya hangi karakter kümesinin kullanılacağını söylemelisiniz. UTF‑8, **plain text unicode** için de‑facto standarttır çünkü her Unicode kod noktasını kodlayabilir. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Pro ipucu:** `setEncoding` çağrısını atlayarsanız, Aspose platformun varsayılan karakter kümesini (çoğu Windows makinede Windows‑1252) kullanır. Bu varsayılan, “ß” ya da “—” gibi karakterleri sessizce düşürür. + +## Step 3: Preserve Table Layout (Optional, but handy for readability) + +**export word as txt** yaptığınızda tablolar genellikle tek bir satıra yığılır ve okunamaz hâle gelir. Aspose.Words, görsel yapıyı koruyacak basit bir bayrak sunar. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Ne zaman kullanılır:* Kaynak DOCX faturalar, takvimler ya da ızgara benzeri veriler içeriyorsa, `PreserveTableLayout`’u etkinleştirmek sekme ve satır sonları ekleyerek dosyanın hâlâ bir tablo gibi görünmesini sağlar. Bu özelliğe ihtiyacınız yoksa satırı atlayıp daha kompakt bir çıktı elde edebilirsiniz. + +## Step 4: Save the Document as Plain‑Text (Export word as txt) + +Artık ağır iş bitti—sadece baytları diske yazın. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Programı çalıştırdığınızda aynı klasörde `plain.txt` oluşur. Notepad++, VS Code, hatta terminalde `cat` gibi bir editörle açtığınızda şunu görürsünüz: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Japon selamı ve gülücük karakterinin korunduğuna, tablonun ise `PreserveTableLayout` sayesinde sütunlarını koruduğuna dikkat edin. İşte temiz bir **export docx to txt**’in özü bu. + +## Step 5: Verify the Output (Convert word to text sanity check) + +Hızlı bir tutarlılık kontrolü sessiz veri kaybını önler. **convert word to text** işlemini doğru yaptığınızı doğrulamanın birkaç yolu: + +1. **Checksum karşılaştırması** – `.txt` dosyasının SHA‑256 hash’ini, bir tur dönüşümden (txt → docx → txt) önce ve sonra hesaplayarak stabiliteyi kontrol edin. +2. **Unicode işaretlerini arama** – `grep` ya da IDE’nin dosya içinde bul özelliğini kullanarak “😊” gibi karakterleri bulun. +3. **Birden fazla editörde açma** – eski Windows Notepad sürümleri BOM olmadan UTF‑8’i yanlış yorumlayabilir; dosyayı VS Code’da açmak doğru kodlamayı teyit eder. + +Bu kontrollerden biri başarısız olursa, `saveOptions.setEncoding(StandardCharsets.UTF_8)` satırının mevcut olduğundan ve kaynak DOCX’in gerçekten Unicode metin içerdiğinden emin olun. + +## Common Pitfalls & How to Avoid Them + +| Sorun | Neden Oluşur | Çözüm | +|-------|--------------|------| +| **Karakter eksikliği** | Varsayılan sistem karakter kümesi (ör. Windows‑1252) ASCII dışı glifleri düşürür. | `saveOptions.setEncoding` ile açıkça UTF‑8 ayarlayın. | +| **Tablolar tek satır hâline gelir** | `PreserveTableLayout` varsayılan olarak `false`. | `saveOptions.setPreserveTableLayout(true)` çağrısını ekleyin. | +| **Dosya bulunamadı** | Yanlış yol ya da okuma izni eksikliği. | Mutlak yollar kullanın veya `Paths.get(...)` ile uygun istisna yönetimi yapın. | +| **Büyük belgelerde performans yavaşlaması** | Tüm belge belleğe yükleniyor. | Sadece belirli bölümlere ihtiyacınız varsa `DocumentBuilder` ile belgeyi parçalar halinde akıtın. | + +## Bonus: Exporting Multiple DOCX Files in a Batch + +Bir klasördeki tüm dosyalar için **convert docx to text** yapmanız gerekiyorsa, mantığı bir döngüye alın: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Bu snippet, dizindeki her dosya için **export docx to txt** gerçekleştirir ve size saatler süren manuel işi tasarruf ettirir. + +## Conclusion + +Java ile **export docx to txt** yapmayı, tüm Unicode karakterlerinin bütünlüğünü koruyarak, tabloların okunabilir kalmasını sağlayarak ve sürecin tekrarlanabilir olmasını öğrenmiş oldunuz. `TxtSaveOptions`’ı UTF‑8’e ayarlayıp isteğe bağlı olarak tablo düzenini koruyarak, **convert docx to text**, **convert word to text** ve **export word as txt** işlemlerini güvenle gerçekleştirebilirsiniz. + +Bir sonraki meydan okumaya hazır mısınız? Markdown (`.md`) ya da CSV gibi diğer düz‑metin formatlarına dışa aktarmayı deneyin ya da Aspose.Words’ün PDF dönüşüm yeteneklerini keşfedin. Aynı ilkeler—açık kodlama, düzen koruma ve kapsamlı doğrulama—tüm süreçlerde geçerlidir. + +Kodlamanız keyifli olsun, ve metin dosyalarınız her zaman Unicode‑zengin kalsın! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + +## İlgili Eğitimler + +- [Convert Docx To Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/turkish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..5be3447687 --- /dev/null +++ b/words/turkish/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words Java kullanarak belgeyi PDF olarak kaydedin ve PDF'ye erişilebilirlik + ekleyin. docx'i PDF'ye dönüştürmeyi, yatay çizgileri etiketlemeyi öğrenin ve PDF/UA‑2 + uyumluluğunu sağlayın. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: tr +og_description: Aspose.Words Java ile belgeyi PDF olarak kaydedin ve PDF'ye erişilebilirlik + ekleyin. Docx'i PDF'ye dönüştürmek ve PDF/UA‑2 uyumluluğu için yatay çizgileri etiketlemek + üzerine adım adım rehber. +og_title: Aspose.Words Java ile Belgeyi PDF Olarak Kaydedin – Erişilebilirlik Kolaylaştırıldı +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Aspose.Words Java ile Belgeyi PDF Olarak Kaydet – Tam Erişilebilirlik Rehberi +url: /tr/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words Java ile Belgeyi PDF Olarak Kaydet – Tam Erişilebilirlik Rehberi + +Ekran okuyucular için erişilebilirliği korurken **belgeyi PDF olarak kaydetmeyi** hiç merak ettiniz mi? Yalnız değilsiniz. Birçok geliştirici *convert docx to pdf* yapmalı ve PDF/UA‑2 standartlarını karşılamalı, özellikle kaynak yatay çizgiler içeriyorsa ve bunların doğru şekilde etiketlenmesi gerekiyorsa. Bu öğreticide, Aspose.Words for Java kullanarak **belgeyi PDF olarak kaydetmek**, otomatik olarak **PDF'ye erişilebilirlik eklemek** ve her yatay çizginin **artifact** olarak **etiketlenmesini** adım adım göstereceğiz. + +Temiz bir Java projesiyle başlayacağız, zaten yatay çizgiler içeren bir DOCX dosyasını yükleyeceğiz, PDF/UA‑2 uyumluluğu için PDF kaydetme seçeneklerini yapılandıracağız ve sonunda tamamen erişilebilir bir PDF oluşturacağız. Sonunda, **save document as pdf** işlemini, erişilebilirlik kontrollerini geçtiğine dair güvenle yapabileceksiniz. + +## Önkoşullar + +- Java 8 veya daha yeni bir sürüm yüklü (öğretici JDK 17 üzerinde test edilmiştir). +- Bağımlılıkları yönetmek için Maven 3.6+ (ya da tercih ederseniz Gradle). +- Geçerli bir Aspose.Words for Java lisansı (ücretsiz deneme çalışır, ancak lisans değerlendirme filigranlarını kaldırır). +- `input.docx` adlı bir DOCX dosyası, en az bir yatay çizgi içermeli—Word'de ekleyeceğiniz basit bir satır ayırıcıyı düşünün. + +> **Pro tip:** Eğer bir DOCX dosyanız yoksa, yeni bir Word belgesi oluşturun, birkaç paragraf yazın, *Insert → Horizontal Line* ekleyin, `input.docx` olarak kaydedin ve istediğiniz bir klasöre yerleştirin. + +## Adım 1: Maven Projesini Kurun + +İlk olarak, yeni bir Maven projesi oluşturun (veya mevcut bir projeye ekleyin). `pom.xml` dosyasının Aspose.Words bağımlılığını içermesi gerekir: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Neden önemli:** `aspose-words` artefaktını eklemek, *convert docx to pdf* için ilk adımdır. Olmazsa, derleyici `Document`, `PdfSaveOptions` ve diğer kritik sınıfları tanımaz. + +## Adım 2: Yatay Çizgileri İçeren Kaynak DOCX'i Yükleyin + +Şimdi DOCX'i yükleyen küçük bir Java sınıfı yazacağız. **tag horizontal rules** kısmının başladığı yer burası—Aspose.Words otomatik olarak bir yatay çizgiyi kenarlıklı bir paragraf olarak ele alır, ancak etiketlemeyi PDF/UA motoruna bırakacağız. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Dikkat edin, henüz bir şey kaydetmedik—sadece DOCX'i **yükliyoruz**, bu *convert docx to pdf* işleminin ilk yarısıdır. `Document` nesnesi artık eklediğiniz tüm Word içeriğini, yatay çizgiler dahil, tutar. + +## Adım 3: PDF/UA‑2 Uyumluluğu için PDF Kaydetme Seçeneklerini Yapılandırın + +**adding accessibility to PDF** sihrinin kaynağı `PdfSaveOptions` içinde bulunur. Uyumluluk seviyesini `PDF_UA_2` olarak ayarladığınızda, Aspose.Words şunları yapar: + +1. Yapısal öğeleri (başlıklar, tablolar vb.) etiketler. +2. Dekoratif öğeleri—yatay çizgiler gibi—*artifact* olarak işaretler, böylece ekran okuyucular bunları yok sayar. +3. Gerekli PDF/UA meta verilerini ekler. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Neden uyumluluk ayarlanmalı?** `PDF_UA_2` olmadan, ortaya çıkan PDF okunabilir olabilir ancak otomatik erişilebilirlik doğrulayıcılarını geçmez. **tag horizontal rules** gereksinimi, uyumluluk bayrağı açık olduğunda PDF/UA bunları *artifact* olarak ele aldığı için otomatik olarak karşılanır. + +## Adım 4: Belgeyi PDF Olarak Kaydedin + +Şimdi nihayet **save document as pdf** yapıyoruz. Bu tek satır, DOCX'i dönüştürme, erişilebilirlik etiketlerini uygulama ve dosyayı diske yazma işini yapar. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Sınıfı çalıştırın (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) ve bir onay mesajı göreceksiniz. Oluşan `ua_compliant.pdf` dosyasını Adobe Acrobat'ta açın ve **File → Properties → Description → PDF/A, PDF/UA** bölümünü kontrol edin—“PDF/UA‑2” yazısını görmelisiniz. + +### Beklenen Çıktı + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +PDF'i açın ve şunları fark edeceksiniz: + +- Belge metni seçilebilir ve aranabilir. +- Yatay çizgi ekran okuyucular tarafından görülmez (artifact olarak işlenir). +- PDF temel PDF/UA doğrulama araçlarını geçer (ör. PAC 3). + +## Adım 5: Erişilebilirliği Doğrulama – Hızlı Kontrol Listesi + +Aspose.Words çoğu işi yapsa da, çıktıyı doğrulamak iyi bir uygulamadır. + +| Kontrol | Nasıl Doğrulanır | +|-------|----------------| +| **Belge başlığı** | Acrobat'ı açın → File → Properties → Title alanı (`pdfOptions.setTitle` ile eşleşmelidir). | +| **Artifact etiketleme** | Acrobat'ın “Reading Order” aracını kullanın. Yatay çizgiler *Artifact* (gri) olarak görünmelidir. | +| **Mantıksal okuma sırası** | Acrobat'ta “Accessibility Checker”ı çalıştırın; yapısal hataların olmadığından emin olun. | +| **Etiketli PDF** | Acrobat'ta “Tags” paneline bakın – bir hiyerarşi (Document → Section → Paragraph, vb.) görmelisiniz. | +| **PDF/UA uyumluluğu** | Acrobat, “Standards” sekmesinde “PDF/UA‑2” gösterir. | + +Bu kontrollerden herhangi biri başarısız olursa, en son Aspose.Words sürümünü kullandığınızdan ve `setCompliance(PdfCompliance.PDF_UA_2)`'nin doğru uygulandığından emin olun. + +## Yaygın Tuzaklar ve Nasıl Kaçınılır + +1. **Missing License** – Deneme sürümü PDF/UA doğrulamasını bozabilecek bir filigran ekler. Lisansınızı `main` içinde erken uygulayın: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` dönüşümü durdurur. Mutlak yollar kullanın veya DOCX'i proje köküne koyup `new File("input.docx").getAbsolutePath()` ile referans verin. +3. **Using Older Aspose Version** – PDF/UA desteği 22.9 sürümünde eklendi. Eksik özelliklerden kaçınmak için en son sürüme yükseltin. +4. **Horizontal Rule as Image** – Çizgiyi yerel Word yatay kuralı yerine bir resim olarak eklediyseniz, Aspose bunu normal bir resim olarak ele alır, artifact değil. Doğru etiketleme için resmi Word'ün yerleşik *Horizontal Line* öğesiyle değiştirin. + +## Çözümü Genişletmek – Daha Fazla Şeye İhtiyacınız Olursa? + +- **Custom Tags**: Başka dekoratif öğeleriniz (örn. dekoratif ikonlar) varsa, `PdfSaveOptions.setArtifactTaggingEnabled(true)` kullanarak bunları manuel olarak artifact olarak işaretleyebilirsiniz. +- **Multiple Documents**: DOCX dosyalarının bulunduğu bir klasörü döngüyle işleyip toplu dönüştürün, performans için aynı `PdfSaveOptions` örneğini yeniden kullanın. +- **Adding a Language Tag**: Çok dilli PDF'ler için, yardımcı teknolojilerin doğru sesi seçmesine yardımcı olmak amacıyla `pdfOptions.setLanguage("en-US")` ayarlayın. + +## Tam Çalışan Örnek (Tüm Kod Birlikte) + +Aşağıda eksiksiz, çalıştırılabilir Java programı yer alıyor. IDE'nize kopyalayıp yapıştırın, yolları ayarlayın ve çalıştırın. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Çalıştırın, oluşturulan PDF'i açın ve dağıtıma hazır, temiz ve erişilebilir bir dosyanız olacak. + +## Sonuç + +Aspose.Words for Java ile **save document as pdf** yapmayı, otomatik olarak **add accessibility to pdf** eklemeyi ve **tag horizontal rules** öğelerini artifact olarak işaretlemeyi yeni gösterdik. Özetle: + +- `PDF_UA_2` uyumluluğu ile `PdfSaveOptions` kullanarak erişilebilirlik standartlarını karşılayın. +- Bir DOCX'i yükleyip `doc.save(..., pdfOptions)` çağırmak, **convert docx to pdf** için yeterlidir. +- Yatay çizgiler sizin için işlenir—ekstra kod gerekmez, **tag horizontal rules** gereksinimini karşılar. +- Bu yaklaşım tamamen **aspose convert docx pdf** uyumludur, en son kütüphane sürümüyle çalışır ve doğrulama‑hazır bir PDF üretir. + +Bir sonraki zorluğa hazır mısınız? Özel meta veriler eklemeyi, yazı tiplerini gömmeyi veya bir klasördeki tüm DOCX dosyalarını toplu işleme almayı deneyin. Bu uzantıların her biri burada oluşturduğumuz temele dayanır. + +PDF/UA uyumluluğu, lisanslama veya diğer Word öğeleriyle ilgili sorularınız mı var? Yorum bırakın veya Aspose'un resmi dokümantasyonuna göz atın—keşfedilecek çok sayıda örnek var. Kodlamaktan keyif alın ve erişilebilir PDF'ler oluşturmanın tadını çıkarın! + +![Aspose.Words Java kullanarak belgeyi pdf olarak kaydet – erişilebilir PDF örneği](placeholder-image.png "Aspose.Words Java kullanarak belgeyi pdf olarak kaydet – erişilebilir PDF örneği") + +## İlgili Öğreticiler + +- [Aspose.Words for Java ile belgeyi pdf olarak kaydetme](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [Aspose.Words for Java kullanarak Word'ü PDF'e Dönüştürme](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Java'da DOCX'i PDF'e Dönüştür](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/turkish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..b1485508bd --- /dev/null +++ b/words/turkish/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Word belgesini markdown olarak kaydedin ve Aspose.Words for Java kullanarak + matematik denklemlerini LaTeX'e nasıl dışa aktaracağınızı keşfedin. Word denklemlerini + sadece birkaç satırda LaTeX'e dönüştürün. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: tr +og_description: Word'ü markdown olarak kaydedin ve Aspose.Words for Java kullanarak + matematik denklemlerini LaTeX'e nasıl dışa aktaracağınızı öğrenin. Tam, çalıştırılabilir + bir rehber. +og_title: Word'ü markdown olarak kaydet – Matematiği Java ile LaTeX'e dışa aktar +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Word'ü markdown olarak kaydet – Java ile Matematiği LaTeX'e dışa aktar +url: /tr/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word'ü markdown olarak kaydet – Matematiği LaTeX'e Aktar Java ile + +Hiç **save word as markdown** yapmanız gerekti ama denklemlerinizin karışık bir karmaşaya dönüşmesinden endişe ettiniz mi? Yalnız değilsiniz. Bu rehberde, bir `.docx` dosyasından **how to export math**'i doğrudan LaTeX'e aktarırken belgenin geri kalanının temiz Markdown olmasını adım adım göstereceğiz. + +Aspose.Words kütüphanesini kurmaktan final `out.md` dosyasını doğrulamaya kadar her şeyi ele alacağız. Sonunda tek bir metod çağrısıyla **convert word equations latex** yapabilecek ve dönüşümün güvenilir olmasını sağlayan ince nüansları anlayacaksınız. + +--- + +## İhtiyacınız olanlar + +- **Java 8+** – kod herhangi bir yeni JDK'da çalışır. +- **Aspose.Words for Java** – Maven/Gradle bağımlılığı ya da manuel kurulum tercih ediyorsanız JAR. +- En az bir Office Math denklemi içeren bir Word belgesi (`math.docx`). +- Bir IDE ya da düz `javac`/`java` komut satırı – size uygun olan. + +Eğer zaten bunlara sahipseniz, harika. Yoksa, bir sonraki bölüm kütüphaneyi projenize nasıl ekleyeceğinizi tam olarak gösteriyor. + +--- + +## Word'ü markdown olarak kaydet – Adım 1: Aspose.Words'u Projeye Ekleyin + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Pro tip:** Aspose, test için ücretsiz geçici bir lisans sunar. `license.xml` dosyasını kaynak klasörünüze koyun ve herhangi bir belgeyi yüklemeden önce `License license = new License(); license.setLicense("license.xml");` kodunu çağırın. + +Bağımlılık çözüldükten sonra, dönüşüm kodunu yazmaya hazırsınız. + +--- + +## Matematik denklemlerini LaTeX'e nasıl dışa aktarılır + +Ağır işi `MarkdownSaveOptions` yapar. `OfficeMathExportMode`'u `LATEX` olarak ayarlayarak, her Office Math nesnesi Markdown çıktısında bir LaTeX parçası olarak işlenir. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Neden bu çalışır + +- **`Document`** Aspose'un giriş noktasıdır; `.docx` dosyasını soyutlar ve denklemler dahil her düğüme erişim sağlar. +- **`MarkdownSaveOptions`** kütüphaneye çıktının *nasıl* olacağını söyler. Varsayılan davranış denklemleri resim olarak render etmektir, bu da metin‑tabanlı formatın amacını bozar. +- **`OfficeMathExportMode.LATEX`** motoru her `OfficeMath` düğümünü LaTeX eşdeğerine çevirmeye zorlar; bu sayede Markdown ayrıştırıcıları (GitHub veya Jekyll gibi) bir MathJax eklentisiyle birleştirildiğinde render edebilir. + +--- + +## Word denklemlerini LaTeX'e dönüştür – Adım 2: Markdown Çıktısını Doğrula + +Programı çalıştırdıktan sonra `out.md` dosyasını açın. Şuna benzer bir şey görmelisiniz: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Note:** LaTeX parçacıkları satır içi matematik için `$…$`, blok matematik için `$$…$$` içinde sarılır. Bu, MathJax etkin olduğunda çoğu statik site jeneratörünün anlayacağı standart sözdizimidir. + +Eğer denklemlerin sadece satır içinde kalmasını istiyorsanız, `MarkdownSaveOptions`'ı daha da ayarlayabilirsiniz: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +--- + +## Docx'ten markdown latex'e – Adım 3: Kenar Durumları ve Yaygın Tuzaklar + +| Durum | Dikkat edilmesi gereken | Çözüm | +|-----------|-------------------|-----| +| **Karmaşık iç içe denklemler** | Aspose, bazı ayrıştırıcıların kelimenin tam anlamıyla yorumladığı ekstra `{}` parantezleri üretebilir. | `Markdown`'ı basit bir regex ile `{{` → `{` şeklinde daraltarak sonradan işleyin. | +| **Hedef sitede MathJax eksik** | Denklemler ham LaTeX kodu olarak görünür. | HTML şablonunuza `` ekleyin. | +| **Büyük belgeler** | Tüm belge bir anda yüklendiği için bellek tüketimi artar. | `LoadOptions.setLoadFormat(LoadFormat.DOCX)` kullanın ve `OutOfMemoryError` alırsanız sayfaları partiler halinde işlemeyi düşünün. | +| **Lisans ayarlanmamış** | Uyarı alırsınız ve çıktı su işareti (watermark) içerebilir. | Yukarıdaki Maven ipucunda gösterildiği gibi lisansı `main` içinde erken yükleyin. | + +--- + +## Word'ü markdown olarak kaydet – Tam Çalışan Örnek + +Aşağıda, herhangi bir Java projesine kopyalayıp yapıştırabileceğiniz bağımsız bir sınıf bulunmaktadır. `YOUR_DIRECTORY`'yi dosyalarınızın yolu ile değiştirmeniz yeterlidir. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Programı çalıştırın (`java MathToLatexMarkdown`) ve başarı mesajını konsolda göreceksiniz. `out.md` dosyasını herhangi bir editörde açın – denklemler render için hazır, temiz LaTeX parçacıkları olmalı. + +--- + +## Beklenen Çıktı Görüntüsü + +![LaTeX denklemleriyle markdown çıktısı](https://example.com/images/markdown-latex-output.png "LaTeX denklemleriyle markdown çıktısı") + +*Görüntü, `\int_{a}^{b} f(x)\,dx` denkleminin `$$` içinde sarıldığı oluşturulan Markdown parçacığını gösterir.* + +--- + +## Sonuç + +Az önce **save word as markdown** yaparken her Office Math denklemini yerel LaTeX olarak korumanın nasıl yapılacağını gösterdik. Ana adım, `MarkdownSaveOptions`'ı `OfficeMathExportMode.LATEX` ile yapılandırmaktı; bu, tipik bir Word‑to‑Markdown işlem hattını tam bir matematik‑duyarlı dönüşüm aracına dönüştürür. + +Şimdi şunları yapabilirsiniz: + +1. **How to export math** herhangi bir `.docx`'ten doğruluk kaybı olmadan dışa aktarın. +2. **Convert word equations latex** statik site jeneratörleri, dokümantasyon veya akademik bloglar için. +3. Yaklaşımı çok sayıda dosyayı toplu işleme, CI boru hatlarına entegre etme veya hatta küçük bir web servisi oluşturma için genişletin. + +Bir sonraki sınır hakkında meraklıysanız, bu yöntemi **docx to markdown latex** ile görsel‑ağır belgeler için birleştirmeyi deneyin veya Aspose'un `HtmlSaveOptions`'ını web‑hazır HTML sürümü için keşfedin. Olanaklar sonsuzdur—deney yapın, hatalar bulun ve ardından bulgularınızı toplulukla paylaşın. + +Sorularınız veya beklenildiği gibi render olmayan karmaşık bir denkleminiz mi var? Aşağıya yorum bırakın, iyi kodlamalar! + +## İlgili Eğitimler + +- [Word'den LaTeX Dışa Aktarma: DOCX'i Markdown'a Dönüştür & PDF Olarak Kaydet](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [docx'i markdown'a dönüştür – Aspose.Words ile Matematik Denklemlerini LaTeX'e Aktar](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Aspose.Words for Java Kullanarak Word'ü PDF'e Dönüştürme](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/turkish/java/document-loading-and-saving/_index.md index cea0c8bf34..8710487c4f 100644 --- a/words/turkish/java/document-loading-and-saving/_index.md +++ b/words/turkish/java/document-loading-and-saving/_index.md @@ -133,7 +133,8 @@ Aspose.Words for Java ile Java’da belge formatlarını nasıl tespit edeceğin ### [Bozuk docx dosyasını kurtarma – Belgeleri Düzeltme ve İşleme Tam Kılavuzu](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) ### [Java’da Font Değiştirme Uyarılarını Yakalama – Aspose.Words ile Tam Kılavuz](./capture-font-substitution-warnings-in-java-with-aspose-words/) -Java’da Aspose.Words kullanarak font değiştirme uyarılarını nasıl yakalayacağınızı ve işleyebileceğinizi öğrenin. + +### [Bozuk Word Belgesini Aç – Java’da Kurtarma Modunu Ayarlama](./open-corrupted-word-document-set-recovery-mode-in-java/) ## Sıkça Sorulan Sorular diff --git a/words/turkish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/turkish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..b081468c76 --- /dev/null +++ b/words/turkish/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,193 @@ +--- +category: general +date: 2026-05-26 +description: Java'da Aspose.Words ile bozuk Word belgesini açın. Kurtarma modunu nasıl + ayarlayacağınızı ve bozuk Word dosyalarını güvenilir bir şekilde nasıl kurtaracağınızı + öğrenin. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: tr +og_description: Aspose.Words kullanarak Java'da bozuk Word belgesini açın. Bu kılavuz, + kurtarma modunu nasıl ayarlayacağınızı ve bozuk Word dosyalarını verimli bir şekilde + nasıl kurtaracağınızı gösterir. +og_title: Bozuk Word Belgesini Aç – Java'da Kurtarma Modunu Ayarla +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Bozuk Word Belgesini Aç – Java’da Kurtarma Modunu Ayarla +url: /tr/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bozuk Word Belgesini Aç – Java’da Kurtarma Modunu Ayarlama + +Hiç bozuk bir Word belgesini açmaya çalışıp programın bir istisna ile takıldığını gördünüz mü? Yalnız değilsiniz—bu kırık .docx dosyaları gerçekten can sıkıcı olabilir. İyi haber şu ki Aspose.Words for Java, **bozuk word belgesini aç**manız için ince ayar kontrolü sunar; uygulama çökmeden, uyarı ister, sessiz kurtarma ister ya da kesin reddetme tercih edebilirsiniz. + +Bu öğreticide, doğru `LoadOptions` oluşturulmasından, uygun **set recovery mode** değerinin seçilmesine ve belgenin gerçekten yüklendiğinin doğrulanmasına kadar tüm süreci adım adım göstereceğiz. Sonunda, **bozuk word dosyasını nasıl kurtarılır** sorusunun programatik cevabını, manuel kopyala‑yapıştıra gerek kalmadan bileceksiniz. + +> **Gereksinimler** +> * Java 8 veya daha yeni (API Java 11 ile de çalışır) +> * Aspose.Words for Java 23.9 (veya en son sürüm) +> * Örnek bir bozuk .docx dosyası—elinizde yoksa geçerli bir dosyanın adını değiştirerek bozulmuş gibi taklit edebilirsiniz + +Haydi başlayalım. + +## Bozuk Word Belgesini Aç – Adım‑Adım Genel Bakış + +Aşağıda uygulayacağımız yüksek seviyeli akış yer alıyor: + +1. **`LoadOptions` oluştur** – bu nesne Aspose.Words’e sorunla karşılaştığında nasıl davranacağını söyler. +2. **Kurtarma modunu ayarla** – `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS` veya `REJECT_CORRUPTED` seçeneklerinden birini seç. +3. **Belgeyi yükle** – yapılandırılmış seçenekleri kullan. +4. **Yüklemenin başarılı olduğunu doğrula** (ör. sayfa sayısını yazdır). + +Her adım ayrıntılı olarak açıklanacak ve IDE’nize doğrudan kopyalayıp yapıştırabileceğiniz kod parçacıkları sunulacak. + +## Farklı Senaryolar İçin Kurtarma Modunu Ayarlama + +Aspose.Words, `LoadOptions.RecoveryMode` içinde üç kurtarma stratejisi tanımlar: + +| Mod | Davranış | Ne zaman kullanılmalı | +|------|-----------|------------------------| +| `RECOVER_WITH_WARNINGS` | Belgeyi yüklemeye çalışır, ancak ortaya çıkan sorunları konsolda uyarı olarak gösterir. | Hangi hataların oluştuğunu görmek, ancak işlemi durdurmak istemediğiniz durumlar. | +| `RECOVER_WITHOUT_WARNINGS` | Yapabildiği kadar sessizce düzeltir ve uyarıları bastırır. | Logların temiz kalması gereken üretim ortamları. | +| `REJECT_CORRUPTED` | Bozukluk tespit edildiği anda bir istisna fırlatır. | Hızlı başarısız olması gereken katı doğrulama hatları. | + +Doğru modu seçmek, **set recovery mode** işlemini doğru yapmanın özüdür. Çoğu hata ayıklama oturumunda `RECOVER_WITH_WARNINGS` en uygun seçimdir çünkü hangi bölümlerin onarıldığını net bir şekilde gösterir. + +## Aspose.Words Kullanarak Bozuk Word Dosyasını Nasıl Kurtarılır + +Aşağıda **tam, çalıştırılabilir bir Java programı** yer alıyor; tüm süreci gösteriyor. `RecoveryModeDemo.java` dosyasına yapıştırın, yolu ayarlayın ve çalıştırın. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Her satırın önemi + +* **`LoadOptions loadOptions = new LoadOptions();`** – bu nesne olmadan Aspose.Words varsayılan kurtarmayı kullanır ve bozuk dosyaları *reddeder*. Oluşturmak, davranışı değiştirme kancasını sağlar. +* **`setRecoveryMode(...)`** – bu, **set recovery mode** çağrısıdır; uyarıların gösterilip gösterilmeyeceğini veya bir istisna oluşturulup oluşturulmayacağını belirler. +* **`new Document(path, loadOptions);`** – kurduğumuz `LoadOptions` nesnesini kabul eden yapıcı, kütüphanenin bozuk dosyayla nasıl başa çıkacağını baştan bilir. +* **`doc.getPageCount()`** – hızlı bir bütünlük kontrolü. Belge yüklendi ve sayfa sayısı döndürdüyse, **bozuk word dosyasını nasıl kurtarılır** sorusunun cevabını almışsınız demektir. +* **`doc.save(...)`** – isteğe bağlı ama kullanışlı; onarılmış sürümü daha sonra kullanmak üzere diske yazabilirsiniz. + +## Yaygın Kenar Durumlarını Ele Alma + +### 1. Dosya Bulunamadı + +Yol hatalıysa, `Document` bir `FileNotFoundException` fırlatır. Yüklemeyi try‑catch bloğuna alın ve dostça bir mesaj kaydedin: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Geri Döndürülemez Bozukluk + +`RECOVER_WITH_WARNINGS` kullanılsa bile bazı yapılar tamir edilemez. Bu durumda Aspose.Words mümkün olanı yükler, ancak “Cannot read paragraph properties” gibi uyarılar görürsünüz. Konsol çıktısına dikkat edin; bu uyarılar genellikle manuel olarak yeniden oluşturmanız gereken eksik bölümleri işaret eder. + +### 3. Büyük Dosyalar ve Performans + +Kurtarma, kütüphanenin dosyayı iki kez ayrıştırması gerektiği için küçük bir ek yük getirir—ilk seferde sorunları tespit eder, ikinci seferde yeniden oluşturur. Çok‑gigabaytlık belgeler için dosyayı akış olarak işlemek ya da JVM yığınını (`-Xmx2g`) artırmak (`OutOfMemoryError` önlemek) akıllıca olur. + +## Pro İpuçları – Kurtarmayı Sağlamlaştırma + +* **Uyarıları bir dosyaya kaydet** – `System.err` çıktısını bir logger’a yönlendirerek neyin düzeltildiğine dair bir denetim izi oluşturun. +* **Kurtarmadan sonra doğrula** – `doc.updatePageLayout();` çalıştırıp ardından sayfa sayısını tekrar kontrol edin; bazı durumlarda bozuk bölümler düzeltildikten sonra düzen değişebilir. +* **Toplu kurtarma otomasyonu** – demoyu bir döngü içinde, aynı `LoadOptions` ile bir klasördeki tüm bozuk dosyaları işleyebilecek şekilde paketleyin. + +## Sonuç + +Artık Aspose.Words for Java kullanarak **bozuk word dosyasını nasıl kurtarılır** sorusunun tam cevabını biliyorsunuz. Bir `LoadOptions` örneği oluşturup, senaryonuza uygun **set recovery mode** değerini ayarlayarak ve belgeyi bu seçeneklerle yükleyerek, uygulamanızın çökmeden **bozuk word belgesini aç**masını sağlayabilirsiniz. Yukarıdaki örnek kod, sayfa sayısını yazdıran ve temizlenmiş bir kopyayı kaydeden eksiksiz, çalıştırılabilir bir çözümdür. + +Sırada ne? Kurtarma modunu `RECOVER_WITHOUT_WARNINGS` olarak değiştirip konsol çıktısını karşılaştırın ya da şifreli belgeleri yüklemeyi deneyin (parola sağlamak için ek bir adım gerekir). + + +## İlgili Öğreticiler + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/turkish/java/document-styling/_index.md index 39f51c34ed..a57787f785 100644 --- a/words/turkish/java/document-styling/_index.md +++ b/words/turkish/java/document-styling/_index.md @@ -43,6 +43,8 @@ Java için Aspose.Words kullanarak belge temalarını nasıl özelleştireceğin Aspose.Words for Java ile filigranların nasıl uygulanacağını ve sayfa yapılandırmalarının nasıl ayarlanacağını öğrenin. Kaynak kodlu kapsamlı bir kılavuz. ### [Belge Başlığı ve Alt Bilgi Biçimlendirmesi](./document-header-footer-styling/) Bu ayrıntılı kılavuzda Aspose.Words for Java kullanarak belge başlıklarını ve altbilgilerini nasıl biçimlendireceğinizi öğrenin. Adım adım talimatlar ve kaynak kodu dahildir. +### [Aspose.Words for Java’da Varsayılan Yazı Tipi Ayarlarını Belirleme – Tam Kılavuz](./set-default-font-settings-in-aspose-words-for-java-complete/) +Aspose.Words for Java’da varsayılan yazı tipi ayarlarını nasıl belirleyeceğinizi ve belge oluştururken otomatik olarak uygulayacağınızı öğrenin. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/turkish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..bd125631c9 --- /dev/null +++ b/words/turkish/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,234 @@ +--- +category: general +date: 2026-05-26 +description: Aspose.Words for Java'da varsayılan yazı tipi ayarlarını belirleyin ve + sadece birkaç satır kodla yazı tipi ayarlarını nasıl yapılandıracağınızı ve eksik + yazı tiplerini nasıl tespit edeceğinizi öğrenin. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: tr +og_description: Aspose.Words for Java'da varsayılan yazı tipi ayarlarını belirleyin, + yazı tipi ayarlarını nasıl ayarlayacağınızı öğrenin ve eksik yazı tiplerini hızlı + ve güvenilir bir şekilde tespit edin. +og_title: Aspose.Words for Java'da Varsayılan Yazı Tipi Ayarlarını Belirle +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Aspose.Words for Java'da Varsayılan Yazı Tipi Ayarlarını Belirleme – Tam Kılavuz +url: /tr/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.Words for Java’da Varsayılan Yazı Tipi Ayarlarını Belirleme – Tam Kılavuz + +Aspose.Words for Java ile bir Word belgesi yüklerken **varsayılan yazı tipi ayarlarını** nasıl belirleyeceğinizi hiç merak ettiniz mi? Tek başınıza değilsiniz. Eksik glifler, cilalı bir raporu karışık bir karmaşaya dönüştürebilir ve bu yazı tipi‑değiştirme uyarılarını erken yakalamak saatler süren hata ayıklamayı önler. + +Bu öğreticide, **varsayılan yazı tipi ayarlarını** belirleyen, programlı olarak **yazı tipi ayarlarını** nasıl ayarlayacağınızı gösteren ve düzeninizi bozmasından önce **eksik yazı tiplerini** tespit etmenin güvenilir bir yolunu gösteren kısa, uçtan uca bir örnek üzerinden ilerleyeceğiz. + +--- + +## Öğrenecekleriniz + +- Yeni bir `FontSettings` örneğiyle `LoadOptions` nesnesi nasıl oluşturulur. +- `WarningInfo` dinleyicisini ekleyerek belge yüklenirken **eksik yazı tiplerini** nasıl tespit edebileceğiniz. +- Dinleyicinin herhangi bir değişikliği sessizce rapor ettiği bir DOCX dosyasının nasıl yükleneceği. +- Üretim ortamında geri dönüş yazı tiplerini özelleştirme ve uç durumları yönetme ipuçları. + +Ek kütüphaneler, gizli yapılandırma dosyaları yok—sadece saf Java ve Aspose.Words. + +--- + +## Önkoşullar + +1. **Aspose.Words for Java** (versiyon 23.10 veya daha yeni) sınıf yolunuzda. +2. Java 17 (veya daha yeni) geliştirme kiti – herhangi bir modern JDK yeterli. +3. Yüklü olmayan bir yazı tipini kasıtlı olarak kullanan bir DOCX dosyası (ör. *“MissingFont.ttf”*). + +Aspose JAR dosyanız yoksa, resmi Maven deposundan edinin: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Hepsi bu kadar—bu demo için ek bir yazı tipi kurmanıza gerek yok. + +--- + +## Adım 1: LoadOptions Oluşturma ve **Varsayılan Yazı Tipi Ayarlarını Belirleme** + +İlk olarak, Aspose'un bilinmeyen yazı tipleriyle karşılaştığında nasıl davranacağını belirten temiz bir `LoadOptions` nesnesine ihtiyacımız var. `setFontSettings(new FontSettings())` çağrısıyla, boş bir geri dönüş listesiyle başlayan **varsayılan yazı tipi ayarlarını** belirleriz. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Neden önemli:** +> Yazı tiplerini açıkça yapılandırmadığınızda, Aspose sistemin varsayılan koleksiyonuna geri döner; bu da eksik yazı tipi sorunlarını gizleyebilir. Yeni bir `FontSettings` örneğiyle başlayarak, geçerli kabul edilen yazı tipleri üzerinde tam kontrol elde edersiniz. + +--- + +## Adım 2: **Eksik Yazı Tiplerini** Tespit Etmek İçin Uyarı Dinleyicisi Ekleme + +Aspose, gerçekleştirdiği her değişiklik için bir `WarningInfo` nesnesi oluşturur. `WarningType.FONT_SUBSTITUTION` dinlenerek, belge ayrıştırıldığında **eksik yazı tiplerini** tespit edebiliriz. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Pro ipucu:** Dinleyici, belgeyi yükleyen aynı iş parçacığında çalışır, bu yüzden neredeyse hiç performans kaybı yoktur. Uyarıları daha sonra analiz için toplamanız gerekiyorsa, doğrudan yazdırmak yerine bir `List` içine itebilirsiniz. + +--- + +## Adım 3: Yapılandırılmış Seçeneklerle Belgeyi Yükleme + +Artık **yazı tipi ayarlarını** belirlediğimize ve bir dinleyici hazırladığımıza göre, dosyayı basitçe yüklüyoruz. Eksik bir yazı tipi anında geri çağrımızı tetikler. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Kaynak dosya yüklü olmayan bir yazı tipine başvuruyorsa, aşağıdaki gibi bir çıktı göreceksiniz: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Bu satır, hangi yazı tipinin eksik olduğunu ve hangi geri dönüşün kullanıldığını tam olarak gösterir—günlükleme veya kullanıcı geri bildirimi için mükemmeldir. + +--- + +## Adım 4: Normal İşleme Devam Etme (İsteğe Bağlı) + +Bu noktada belge tamamen yüklendi ve istediğiniz herhangi bir işlemi gerçekleştirebilirsiniz—düzenleme, PDF’ye dönüştürme veya metin çıkarma. Uyarı dinleyicisi işini zaten yaptı, bu yüzden ekstra kontrole gerek yok. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Özel bir geri dönüş isteseniz ne olur?** +> `FontSettings` boş bırakmak yerine, belirli yazı tipleri ekleyebilirsiniz: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Artık eksik herhangi bir yazı tipi *Times New Roman* ile değiştirilecek—çoğu Batı belgesi için güvenilir bir seçim. + +--- + +## Görsel Genel Bakış + +![Aspose.Words for Java’da varsayılan yazı tipi ayarlarının nasıl belirleneceğini gösteren diyagram](image.png "Varsayılan yazı tipi ayarları akış diyagramı") + +*Alt metin: Aspose.Words for Java’da varsayılan yazı tipi ayarları akış şeması.* + +Diyagram, `LoadOptions` başlatılmasından (**varsayılan yazı tipi ayarlarını** belirlediğimiz) uyarı dinleyicisinin eklenmesine (**eksik yazı tiplerini** tespit etmek için) ve nihayet belgeyi yüklemeye kadar olan akışı gösterir. + +--- + +## Yaygın Tuzaklar ve Nasıl Kaçınılır + +| Tuzak | Neden Olur | Çözüm | +|------|------------|------| +| **`setFontSettings` çağrısını unutmak** | Aspose sistem varsayılanlarını kullanır, eksik yazı tiplerini gizler. | Her zaman yeni bir `FontSettings` örneği oluşturup `LoadOptions`'a atayın. | +| **Dinleyicinin tetiklenmemesi** | Dinleyici, belge yüklendikten sonra eklenmiş. | Uyarı dinleyicisini `new Document(...)` çağrısından *önce* ekleyin. | +| **Yol yazım hatası `FileNotFoundException` hatasına yol açar** | Sabit kodlanmış yol, işletim sisteminin büyük/küçük harf duyarlılığıyla uyuşmaz. | `Paths.get("...").toAbsolutePath()` kullanın veya proje kökünden göreceli bir yol yapılandırın. | +| **Birden fazla eksik yazı tipi günlükleri boğar** | Büyük belgeler onlarca uyarı üretebilir. | Yazdırmadan önce tekrarları filtreleyin veya mesajları bir `Set` içinde toplayın. | + +--- + +## Çözümü Genişletme + +Tüm bir uygulama için **yazı tipi ayarlarını** belirlemeniz gerekiyorsa, bir singleton `FontSettings` oluşturup tüm `LoadOptions` içinde yeniden kullanmayı düşünün. Böylece tutarlı bir geri dönüş stratejisi sağlarsınız ve nesne oluşturmayı tekrarlamaktan kaçınırsınız. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Artık kod tabanınızın herhangi bir bölümü sadece `FontConfig.getLoadOptions()` çağırarak aynı **varsayılan yazı tipi ayarlarını belirleme** mantığından anında faydalanabilir. + +--- + +## Sonuç + +Aspose.Words for Java’da **varsayılan yazı tipi ayarlarını** belirleme, programlı olarak **yazı tipi ayarlarını** ayarlama ve çıktınızı bozmadan önce **eksik yazı tiplerini** tespit etme konusunda ihtiyacınız olan her şeyi ele aldık. Tam, çalıştırılabilir örnek yukarıdaki kod parçacıklarında yer alıyor ve uyarıları görmek için doğrudan IDE’nize yapıştırabilirsiniz. + +Sonraki adımlar? Geri dönüş yazı tipini değiştirin, farklı belge formatlarıyla (DOC, RTF, HTML) deney yapın veya uyarı toplayıcıyı bir izleme panosuna entegre edin. `FontSettings` ile ne kadar çok oynarsanız, oluşturduğunuz belgelerin tam istediğiniz gibi görüneceğinden o kadar emin olursunuz—sürpriz yok, kırık glif yok. + +Sorularınız veya zor bir yazı tipi‑değiştirme senaryonuz mu var? Aşağıya yorum bırakın, iyi kodlamalar! + +## İlgili Öğreticiler + +- [Yazı Tipi Geri Dönüş Ayarlarını Belirleme](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Yazı Tipi Geri Dönüş Ayarlarını Belirleme](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Yazı Tipi Geri Dönüş Ayarlarını Belirleme](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/java/images-shapes/_index.md b/words/turkish/java/images-shapes/_index.md index dd2be77c2d..11d5c067f2 100644 --- a/words/turkish/java/images-shapes/_index.md +++ b/words/turkish/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Aspose.Words for Java ile Word belgelerinin yüksek kaliteli küçük resimlerin ### [Java ile Word Belgesi Oluştur – Gölge Efektiyle Dikdörtgen Şekil Ekle](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Java kullanarak Word belgesine gölge efektiyle dikdörtgen şekil eklemeyi öğrenin. +### [Java Word Belgesine Dikdörtgen Şekil Ekle – Tam Adım‑Adım Rehber](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Java kullanarak Word belgesine dikdörtgen şekil eklemeyi adım adım öğrenin. + ## Ek Kaynaklar - [Java Belgeleri için Aspose.Words](https://reference.aspose.com/words/java/) diff --git a/words/turkish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/turkish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..9981fc5119 --- /dev/null +++ b/words/turkish/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-05-26 +description: Java Word belgesinde dikdörtgen şekli oluşturun ve gölge efekti uygulayın. + Şekil gölgesi eklemeyi, gölge mesafesini ayarlamayı ve dosyayı kaydetmeyi öğrenin. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: tr +og_description: Java Word belgesinde dikdörtgen şekil oluşturun, gölge etkisi uygulayın, + şekil gölgesi ekleyin ve gölge mesafesini Aspose.Words ile ayarlayın. +og_title: Java Word Belgesinde Dikdörtgen Şekil Oluşturma – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Java Word Belgesinde Dikdörtgen Şekli Oluşturma – Tam Adım Adım Rehber +url: /tr/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Java Word Belgesinde Dikdörtgen Şekil Oluşturma – Tam Adım‑Adım Kılavuz + +Java Word belgesinde **create rectangle shape** oluşturmanız gerektiğinde ama nereden başlayacağınızı bilemediğiniz oldu mu? Yalnız değilsiniz—birçok geliştirici raporlar veya faturalar oluştururken bu sorunu yaşıyor. Bu öğreticide tam olarak nasıl **create rectangle shape** oluşturacağınızı, şık bir gölge uygulayacağınızı ve gölge mesafesini ince ayar yaparak sonucun profesyonel görünmesini sağlayacağımızı adım adım göstereceğiz. + +Aspose.Words for Java'ı kullanacağız; Microsoft Office yüklü olmadan Word dosyalarını manipüle etmenizi sağlayan güçlü bir kütüphane. Bu rehberin sonunda sadece birkaç satır kodla **create word document java** projeleri oluşturabilecek, **add shape shadow**, **apply shadow effect** ve **set shadow distance** yapabileceksiniz. + +--- + +## Oluşturacağınız Şeyler + +- Cyan bir dikdörtgen içeren yeni bir `.docx` dosyası. +- Bulanik, açıyla ve kısmen şeffaf bir gerçekçi gölge. +- Gölgenin şekilden uzaklığı üzerinde tam kontrol. +- Herhangi bir Maven veya Gradle projesine ekleyebileceğiniz, çalıştırmaya hazır bir Java sınıfı. + +Harici araçlar yok, manuel UI adımları yok—sadece saf kod. + +## Önkoşullar + +- Java 8 veya daha yeni (kod Java 11, Java 17 vb. sürümlerde çalışır). +- Aspose.Words for Java kütüphanesi (Maven Central üzerinden temin edilebilir). +- Sevdiğiniz bir IDE veya metin düzenleyici (IntelliJ IDEA, Eclipse, VS Code…). +- Java sözdizimi hakkında temel bilgi. + +Daha önce Maven bağımlılığı eklemediyseniz, işte hızlı bir snippet: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Şimdi, derinlemesine inceleyelim. + +## Adım 1: Word Belgesinde Dikdörtgen Şekil Oluşturma + +İlk olarak boş bir belge ve bir `DocumentBuilder`'a ihtiyacımız var. Builder'ı belgeye yazan bir kalem gibi düşünün. Bunu elde ettiğimizde, tek bir metod çağrısıyla **create rectangle shape** yapabiliriz. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Neden önemli:** `insertShape` metodu yalnızca geometriyi oluşturmakla kalmaz, aynı zamanda şekli belgenin iç koleksiyonuna ekler, böylece hemen stil vermeye başlayabilirsiniz. + +## Adım 2: Şekle Gölge Efekti Uygulama + +Dikdörtgen sayfada yer aldığından, **apply shadow effect** yapacağız. Gölge derinlik katar, şeklin sayfadan yükselmiş gibi hissetmesini sağlar—raporlarda okunabilirliği artırabilecek ince bir UI iyileştirmesi. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Pro ipucu:** `5.0` bulanıklık çoğu ekranda görüntülenen belge için doğaldır. Yazdırıyorsanız, bulanık bir görünümden kaçınmak için biraz daha düşük bir değer tercih edebilirsiniz. + +## Adım 3: Gölge Mesafesini Ayarlama – Yerleşimi İnce Ayarlama + +Gölge sadece bulanıklıkla ilgili değildir; doğru ofset de gerekir. İşte **set shadow distance** burada devreye girer. `7.0` puanlık bir mesafe, fark edilir ama abartılı olmayan bir ofset oluşturur. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Daha büyük bir ofsete mi ihtiyacınız var?** Değeri artırın; daha sıkı bir görünüm için azaltın. Unutmayın, mesafe gölgenin doğru konumlandırılması için açıyla birlikte çalışır. + +## Adım 4: Belgeyi Kaydet – Çalışmanızı Saklayın + +Son olarak belgeyi diske yazıyoruz. Dosyanın konumunu istediğiniz yere göre değiştirin. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Sınıfı çalıştırmak, `shadow.docx` dosyasını oluşturur; bu dosya Microsoft Word veya LibreOffice'te açıldığında, 45° açıyla ve 7 puan ofsetle yumuşak gri bir gölgeye sahip cyan bir dikdörtgen gösterir. + +## Tam Çalışan Örnek + +Aşağıda tam, kopyala‑yapıştır‑hazır kod bulunmaktadır. Tüm importları, yorumları ve son `save` çağrısını içerir. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Beklenen çıktı:** `shadow.docx` dosyasını açın → ilk sayfanın ortasında cyan bir dikdörtgen göreceksiniz, hafifçe sağ‑alt köşeye kaymış ince bir gri gölge oluşturur. Gölgenin bulanıklığı ve şeffaflığı, doğal bir aydınlatma gibi görünmesini sağlar. + +## Yaygın Sorular & Özel Durumlar + +### “Farklı bir şekil kullanabilir miyim?” + +Kesinlikle. `ShapeType.RECTANGLE` yerine `ShapeType.OVAL`, `ShapeType.LINE` veya desteklenen başka bir enum kullanın. Gölge kodunun geri kalanı aynı kalır. + +### “Birden fazla gölgeye ihtiyacım olsaydı?” + +Aspose.Words bir şekil başına yalnızca tek bir gölgeyi destekler. Birden fazla gölgeyi taklit etmek için şekli çoğaltın, her kopyayı ofsetleyin ve şeffaflığı ayarlayın. + +### “Gölge LibreOffice'te görünüyor mu?” + +Evet—Aspose.Words standart OOXML yazar, LibreOffice bunu doğru yorumlar. Render motorları nedeniyle gölge biraz farklı görünebilir, ancak efekt korunur. + +### “Gölge rengini markama uygun nasıl değiştiririm?” + +`java.awt.Color.GRAY` yerine istediğiniz herhangi bir `java.awt.Color` değerini koyun; örneğin kurumsal mavi için `new java.awt.Color(0, 120, 215)`. + +## Görsel Açıklama + +![Java Word belgesinde dikdörtgen şekil oluşturma](https://example.com/images/rectangle-shadow.png) + +*Alt metin:* **create rectangle shape** illüstrasyonu, Word belgesinde gri bir gölgeye sahip cyan bir dikdörtgeni gösterir. + +## Özet & Sonraki Adımlar + +Aspose.Words for Java kullanarak **create rectangle shape**, **apply shadow effect**, **add shape shadow** ve **set shadow distance** nasıl yapılacağını ele aldık. Kod bağımsızdır, herhangi bir modern JDK'da çalışır ve dağıtıma hazır şık bir `.docx` dosyası üretir. + +Daha ileri gitmek ister misiniz? Şunları deneyin: + +- `builder.moveTo(rectangleShape.getAbsolutePosition())` ile dikdörtgenin içine metin ekleme. +- Bir diyagram oluşturmak için şekillerden bir tablo yaratma. +- Belgeyi PDF olarak dışa aktarma (`doc.save("output.pdf", SaveFormat.PDF);`). + +Bunların her biri, az önce incelediğimiz aynı temeller üzerine kurulu olduğundan, örneği genişletirken rahat hissedeceksiniz. + +## Son Düşünceler + +**create word document java** gibi şekil oluşturma ve gölgelendirme görevlerinde uzmanlaşmak, raporları, sözleşmeleri veya pazarlama materyallerini otomatikleştirirken size büyük bir avantaj sağlar. Burada gösterilen yaklaşım temiz, sürdürülebilir ve—en önemlisi—herhangi bir görsel stil için kolayca ayarlanabilir. + +Kodu çalıştırın, bulanıklığı, açıyı ve mesafeyi ayarlayın ve belgelerinizin sade bir halden şık bir hale dönüşümünü izleyin. Bir sorunla karşılaşırsanız, aşağıya yorum bırakın; yardımcı olmaktan memnuniyet duyarım. + +Kodlamanın keyfini çıkar! + +## İlgili Öğreticiler + +- [Word Belgesi Java Oluştur – Dikdörtgen Şekil ve Gölge Efekti Ekle](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Aspose.Words for Java'da DocumentBuilder kullanarak form alanları oluşturma ve içerik ekleme](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Word'den PDF Oluşturma ve Barkod Üretimi – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/_index.md b/words/vietnamese/java/document-conversion-and-export/_index.md index 393aabefc8..4045aa6554 100644 --- a/words/vietnamese/java/document-conversion-and-export/_index.md +++ b/words/vietnamese/java/document-conversion-and-export/_index.md @@ -41,7 +41,7 @@ A watermark là một hình ảnh hoặc văn bản mờ được đặt phía s - Thư viện Aspose.Words for Java (tải về từ trang chính thức). - Giấy phép Aspose hợp lệ cho việc sử dụng trong môi trường sản xuất (có bản dùng thử miễn phí). -## Bắt đầu với Aspose.Words for Java +## Bắt đầu với Aspose.Words cho Java Bạn mới bắt đầu với Aspose.Words for Java? Đừng lo! Hướng dẫn này sẽ chỉ cho bạn cách thiết lập ban đầu và cung cấp nền tảng vững chắc để làm việc với API này. Bạn sẽ nhanh chóng sẵn sàng sử dụng. ## Chuyển đổi tài liệu sang các định dạng khác nhau @@ -94,15 +94,30 @@ Hướng dẫn chi tiết cách chuyển tài liệu DOCX sang PDF bằng Aspose ### [Chuyển đổi docx sang markdown – Xuất công thức toán sang LaTeX với Aspose.Words](./convert-docx-to-markdown-export-math-equations-to-latex-with/) Chuyển đổi tài liệu DOCX sang Markdown và xuất các công thức toán học dưới dạng LaTeX bằng Aspose.Words. +### [Lưu Word dưới dạng Markdown – Xuất công thức toán sang LaTeX với Java](./save-word-as-markdown-export-math-to-latex-with-java/) +Lưu tài liệu Word thành Markdown và xuất các công thức toán học dưới dạng LaTeX bằng Aspose.Words cho Java. + ### [Lưu Tài Liệu dưới dạng TXT – Hướng Dẫn Nhanh về Xuất Công Thức Toán Word](./save-document-as-txt-quick-guide-to-exporting-word-math/) Hướng dẫn cách lưu tài liệu Word thành tệp TXT và xuất công thức toán học một cách nhanh chóng. +### [Xuất docx sang txt với Java – Hướng Dẫn Lập Trình Toàn Diện](./export-docx-to-txt-with-java-complete-programming-guide/) +Hướng dẫn chi tiết cách xuất tài liệu DOCX thành tệp TXT bằng Java sử dụng Aspose.Words, bao gồm mã nguồn mẫu. + ### [Cách Nhúng Hình Ảnh vào Markdown Khi Chuyển Đổi DOCX](./how-to-embed-images-in-markdown-when-converting-docx/) Hướng dẫn nhúng hình ảnh vào tài liệu Markdown trong quá trình chuyển đổi từ DOCX, bao gồm các tùy chọn và ví dụ mã nguồn. -### [Tạo PDF Truy cập được từ DOCX – Hướng Dẫn Toàn Diện](./create-accessible-pdf-from-docx-complete-guide/) +### [Nhúng Hình Ảnh dưới dạng Base64 Khi Chuyển Đổi DOCX sang Markdown](./embed-images-as-base64-when-converting-docx-to-markdown/) +Nhúng hình ảnh dưới dạng Base64 trong quá trình chuyển đổi tài liệu DOCX sang Markdown bằng Aspose.Words for Java. + +### [Tạo PDF Truy cập được từ DOCX – Hướng Dẫn Toàn Diện](./create-accessible-pdf-from-docx/) Hướng dẫn chi tiết cách chuyển đổi tài liệu DOCX sang PDF có khả năng truy cập, đáp ứng tiêu chuẩn WCAG và hỗ trợ công cụ đọc màn hình. +### [Lưu Tài Liệu dưới dạng PDF với Aspose.Words Java – Hướng Dẫn Toàn Diện về Khả năng Truy cập](./save-document-as-pdf-with-aspose-words-java-full-accessibili/) +Hướng dẫn chi tiết cách lưu tài liệu Word thành PDF có khả năng truy cập, đáp ứng tiêu chuẩn WCAG, sử dụng Aspose.Words for Java. + +### [Create Accessible PDF in Java – Full Tagging Guide](./create-accessible-pdf-in-java-full-tagging-guide/) +Hướng dẫn chi tiết cách tạo PDF có khả năng truy cập, thêm thẻ đầy đủ bằng Aspose.Words for Java. + ## Câu hỏi thường gặp **Q: Làm thế nào để thêm watermark vào PDF hiện có bằng Aspose.Words?** diff --git a/words/vietnamese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md b/words/vietnamese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md new file mode 100644 index 0000000000..75e3e15cf3 --- /dev/null +++ b/words/vietnamese/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-05-26 +description: Tạo PDF có khả năng truy cập trong Java với mã từng bước. Tìm hiểu cách + gắn thẻ PDF để hỗ trợ khả năng truy cập và bật tính năng gắn thẻ PDF bằng PdfSaveOptions. +draft: false +keywords: +- create accessible pdf +- how to tag pdf for accessibility +- how to create tagged pdf +- add accessibility tags to pdf +- enable pdf tagging +language: vi +og_description: Tạo PDF có khả năng truy cập trong Java với mã từng bước. Tìm hiểu + cách gắn thẻ PDF để hỗ trợ truy cập và kích hoạt gắn thẻ PDF bằng PdfSaveOptions. +og_title: Tạo PDF truy cập được trong Java – Hướng dẫn gắn thẻ đầy đủ +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + headline: Create Accessible PDF in Java – Full Tagging Guide + type: TechArticle +- description: Create accessible PDF in Java with step‑by‑step code. Learn how to + tag PDF for accessibility and enable PDF tagging using PdfSaveOptions. + name: Create Accessible PDF in Java – Full Tagging Guide + steps: + - name: 1. Set Document Language + text: Screen readers use the language attribute to pronounce text correctly. + - name: 2. Provide a Title and Subject + text: Metadata helps assistive tools give context before the user even opens the + file. + - name: 3. Tag Images with Alternative Text + text: If you embed pictures, they need `alt` descriptions. + - name: 4. Mark Table Headers + text: Tables are notorious for confusing readers unless you flag header rows. + type: HowTo +tags: +- PDF +- Java +- Accessibility +title: Tạo PDF Truy cập được trong Java – Hướng dẫn Đánh dấu đầy đủ +url: /vi/java/document-conversion-and-export/create-accessible-pdf-in-java-full-tagging-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo PDF Truy cập được trong Java – Hướng dẫn Gắn thẻ đầy đủ + +Bạn có bao giờ tự hỏi làm thế nào để **tạo PDF truy cập được** trực tiếp từ mã Java không? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần phục vụ người dùng dựa vào trình đọc màn hình, và sự khác biệt giữa một PDF thông thường và một PDF truy cập được có thể rất lớn. Trong hướng dẫn này, chúng tôi sẽ hướng dẫn **cách gắn thẻ PDF để hỗ trợ truy cập**, cho bạn thấy **cách tạo PDF có thẻ** với Aspose PDF for Java, và tiết lộ các bước chính xác để **thêm thẻ truy cập vào PDF** để mọi người đọc đều nhận được cùng một thông tin. + +Chúng tôi cũng sẽ đề cập đến các thực hành tốt nhất để **bật gắn thẻ PDF**, những khó khăn thường gặp, và một ví dụ hoàn chỉnh, có thể chạy được mà bạn có thể đưa vào dự án ngay hôm nay. Không có tham chiếu mơ hồ—chỉ có mã cụ thể, giải thích, và một tệp cuối cùng bạn có thể mở trong Adobe Acrobat để kiểm tra các thẻ. + +## Những gì bạn sẽ học + +- Lý do tại sao cần gắn thẻ PDF và tuân thủ khả năng truy cập. +- Các yêu cầu trước và cài đặt thư viện (Aspose PDF for Java 23.10 hoặc mới hơn). +- Cách **tạo PDF truy cập được** từ đầu, từng bước. +- Các cách để **thêm thẻ truy cập vào PDF** ngoài lời gọi cơ bản `setTagDocumentStructure`. +- Mẹo kiểm tra kết quả và khắc phục các vấn đề thường gặp. + +Khi kết thúc hướng dẫn này, bạn sẽ có khả năng tạo ra các tệp PDF đáp ứng kiểm tra WCAG 2.1 AA và đồng thời trông chuyên nghiệp. + +--- + +## Yêu cầu trước + +Trước khi chúng ta bắt đầu, hãy chắc chắn rằng bạn đã có: + +| Yêu cầu | Lý do | +|-------------|--------| +| **Java 8+** | Các tính năng ngôn ngữ hiện đại và xử lý Unicode tốt hơn. | +| **Aspose PDF for Java** (v23.10 hoặc mới hơn) | Cung cấp lớp `PdfSaveOptions` và hỗ trợ gắn thẻ. | +| **IDE** (IntelliJ IDEA, Eclipse, VS Code, v.v.) | Để biên dịch và gỡ lỗi dễ dàng. | +| **Write permission** to a folder where the PDF will be saved | Lệnh `doc.save` cần một đường dẫn có thể ghi. | + +Nếu bạn chưa thêm Aspose PDF vào dự án, hãy chèn phụ thuộc Maven sau vào tệp `pom.xml` của bạn: + +```xml + + com.aspose + aspose-pdf + 23.10 + jdk17 + +``` + +> **Mẹo chuyên nghiệp:** Sử dụng phiên bản mới nhất; các bản phát hành mới cải thiện độ chính xác của việc gắn thẻ và thêm các tính năng truy cập đặc thù cho ngôn ngữ. + +--- + +## Bước 1: Thiết lập khung tài liệu + +Đầu tiên, chúng ta tạo một đối tượng `Document` mới. Hãy nghĩ nó như một bảng trắng sẽ sau này chứa các thẻ chúng ta cần cho khả năng truy cập. + +```java +import com.aspose.pdf.*; + +public class AccessiblePdfDemo { + public static void main(String[] args) throws Exception { + // Initialize a new PDF document – the foundation for create accessible pdf + Document doc = new Document(); + + // Add a single page – you can add more later if needed + Page page = doc.getPages().add(); + + // Insert some readable content + TextFragment fragment = new TextFragment("Hello, accessible PDF!"); + page.getParagraphs().add(fragment); +``` + +**Tại sao điều này quan trọng:** Nếu không có nội dung, sẽ không có gì để gắn thẻ. Thêm ngay cả một `TextFragment` đơn giản cũng cung cấp cho công cụ gắn thẻ một đối tượng để làm việc, và nó sẽ tự động tạo thẻ `

` (đoạn văn) khi chúng ta bật gắn thẻ cấu trúc sau này. + +## Bước 2: Tạo tùy chọn lưu PDF (cốt lõi của việc gắn thẻ) + +Bây giờ chúng ta chuẩn bị các tùy chọn để chỉ cho Aspose PDF nhúng cây cấu trúc logic vào trong tệp. + +```java + // Step 1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 2: Enable document structure tagging for accessibility + pdfOptions.setTagDocumentStructure(true); +``` + +Lệnh gọi `setTagDocumentStructure(true)` là công tắc **bật gắn thẻ PDF**. Khi đặt thành true, thư viện sẽ xây dựng một cây thẻ phản ánh bố cục trực quan, giúp PDF có thể đọc được bởi các công nghệ hỗ trợ. + +> **Lưu ý:** Đây là cách đơn giản nhất để **cách tạo PDF có thẻ**. Để kiểm soát chi tiết hơn (ví dụ: đặt ngôn ngữ hoặc thẻ tùy chỉnh), bạn có thể khám phá `pdfOptions.setTagLanguage("en-US")` và `pdfOptions.setTagStructureTreeRoot(...)`. + +## Bước 3: Lưu PDF truy cập được + +Cuối cùng, chúng ta ghi tài liệu ra đĩa bằng các tùy chọn vừa cấu hình. + +```java + // Step 3: Save the document as an accessible PDF + doc.save("output/accessible.pdf", pdfOptions); + } +} +``` + +Khi lệnh `doc.save` hoàn thành, bạn sẽ thấy tệp `accessible.pdf` trong thư mục `output`. Mở nó trong Adobe Acrobat và xem **File → Properties → Description → Tags** – bạn sẽ thấy một cây thẻ đã được điền đầy. + +## Cách gắn thẻ PDF để hỗ trợ truy cập – Ngoài những điều cơ bản + +Đoạn mã ba bước ở trên đã **thêm thẻ truy cập vào PDF**, nhưng các tài liệu thực tế thường cần một chút tinh chỉnh hơn. Dưới đây là một vài cải tiến bạn có thể thêm vào: + +### 1. Đặt ngôn ngữ tài liệu + +Trình đọc màn hình sử dụng thuộc tính ngôn ngữ để phát âm văn bản một cách chính xác. + +```java +pdfOptions.setTagLanguage("en-US"); +``` + +### 2. Cung cấp Tiêu đề và Chủ đề + +Siêu dữ liệu giúp các công cụ hỗ trợ cung cấp ngữ cảnh trước khi người dùng mở tệp. + +```java +doc.setTitle("Welcome Letter"); +doc.setSubject("Accessible PDF example"); +``` + +### 3. Gắn thẻ hình ảnh với Văn bản thay thế + +Nếu bạn chèn hình ảnh, chúng cần mô tả `alt`. + +```java +Image image = new Image(); +image.setFile("logo.png"); +image.getAlternativeText().setValue("Company logo"); +page.getParagraphs().add(image); +``` + +### 4. Đánh dấu tiêu đề bảng + +Bảng thường gây nhầm lẫn cho người đọc trừ khi bạn đánh dấu các hàng tiêu đề. + +```java +Table table = new Table(); +table.setColumnWidths("100 100"); +Row header = table.getRows().add(); +header.getCells().add("Name"); +header.getCells().add("Score"); +header.getCells().get_Item(0).setIsHeader(true); +header.getCells().get_Item(1).setIsHeader(true); +``` + +Những bước bổ sung này không chỉ làm cho PDF *có thẻ* về mặt kỹ thuật, mà còn thực sự **truy cập được** cho một đối tượng đa dạng. + +## Những khó khăn thường gặp khi bạn bật gắn thẻ PDF + +| Triệu chứng | Nguyên nhân có thể | Cách khắc phục | +|-------------|--------------------|----------------| +| Thẻ bị thiếu trong Acrobat | `setTagDocumentStructure` để là `false` | Đảm bảo bạn gọi `pdfOptions.setTagDocumentStructure(true)`. | +| Thứ tự đọc sai | Bố cục phức tạp mà không có thẻ rõ ràng | Sử dụng `pdfOptions.setTagStructureTreeRoot(...)` để định nghĩa thứ tự tùy chỉnh. | +| Hình ảnh được đọc là “image” mà không có mô tả | Chưa đặt văn bản thay thế | Gọi `image.getAlternativeText().setValue("...")`. | +| Ngôn ngữ không được nhận dạng | `setTagLanguage` bị bỏ qua hoặc locale không đúng | Cung cấp mã ngôn ngữ BCP‑47 (`en-US`, `fr-FR`). | + +Nhận thức được những vấn đề này sẽ giúp bạn tiết kiệm hàng giờ gỡ lỗi sau này. + +## Xác minh Kết quả – Những gì mong đợi + +Sau khi chạy chương trình, mở `output/accessible.pdf` trong Adobe Acrobat Reader: + +1. **Bảng thẻ** (`View → Show/Hide → Navigation Panes → Tags`) nên hiển thị một cây phân cấp như `/Document → /Part → /Sect → /Para`. +2. **Thứ tự đọc** nên theo luồng trực quan (đầu tiên là văn bản, sau đó là hình ảnh). +3. **Trình đọc màn hình** (NVDA, VoiceOver) sẽ đọc “Hello, accessible PDF!” thay vì chỉ “Page 1”. + +Nếu bất kỳ mục nào trong số này bị thiếu, hãy kiểm tra lại các bước trên—đặc biệt là lời gọi `setTagDocumentStructure`. + +## Ví dụ Hoàn chỉnh (Sẵn sàng Sao chép‑Dán) + + + +## Các hướng dẫn liên quan + +- [Tạo PDF Truy cập được từ Word – Chuyển đổi sang PDF/UA](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-word-convert-to-pdf-ua/) +- [Tạo PDF Truy cập được từ DOCX – Hướng dẫn đầy đủ](/words/english/java/document-conversion-and-export/create-accessible-pdf-from-docx-complete-guide/) +- [Cách lưu tài liệu dưới dạng PDF với Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-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/vietnamese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md b/words/vietnamese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md new file mode 100644 index 0000000000..927a6324fb --- /dev/null +++ b/words/vietnamese/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-05-26 +description: Nhúng hình ảnh dưới dạng base64 khi bạn chuyển đổi docx sang markdown + với Aspose.Words cho Java. Tìm hiểu cách chuyển đổi Word sang markdown, lưu Word + dưới dạng markdown và xử lý hình ảnh. +draft: false +keywords: +- embed images as base64 +- convert docx to markdown +- convert word to markdown +- convert images to base64 +- save word as markdown +language: vi +og_description: Nhúng hình ảnh dưới dạng base64 khi chuyển đổi docx sang markdown + với Aspose.Words cho Java. Hướng dẫn đầy đủ để chuyển đổi Word sang markdown và + lưu Word dưới dạng markdown. +og_title: Nhúng hình ảnh dưới dạng Base64 khi chuyển DOCX sang Markdown +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + headline: Embed Images as Base64 When Converting DOCX to Markdown + type: TechArticle +- description: Embed images as base64 while you convert docx to markdown with Aspose.Words + for Java. Learn to convert word to markdown, save word as markdown, and handle + images. + name: Embed Images as Base64 When Converting DOCX to Markdown + steps: + - name: 'H3: Why Use `setSaveToMemory(true)`?' + text: 'When `saveToMemory` is true, Aspose writes the image bytes to a memory + stream instead of a file. The Markdown exporter then converts that stream to + a Base64 string and inserts it directly into the Markdown image tag:' + - name: Troubleshooting Checklist + text: '| Issue | Likely Cause | Fix | |-------|--------------|-----| | Image appears + as a broken link | `setSaveToMemory` was omitted | Ensure `args.setSaveToMemory(true);` + is inside the callback | | Base64 string is truncated | Output file encoding + mismatch | Save the Markdown using UTF‑8 (default for Asp' + - name: Convert Only Selected Images + text: 'If you only want to embed certain images (e.g., those larger than 100 KB), + add a size check:' + - name: Use a Different Image Format + text: The `ResourceSavingArgs` gives you the raw bytes, so you could re‑encode + JPEGs as PNGs before embedding—useful when the target Markdown consumer prefers + PNG. + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- Base64 +title: Nhúng hình ảnh dưới dạng Base64 khi chuyển DOCX sang Markdown +url: /vi/java/document-conversion-and-export/embed-images-as-base64-when-converting-docx-to-markdown/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nhúng Hình Ảnh Dưới Dạng Base64 Khi Chuyển DOCX Sang Markdown + +Bạn đã bao giờ tự hỏi làm thế nào để **nhúng hình ảnh dưới dạng base64** khi **chuyển docx sang markdown**? Bạn không phải là người duy nhất—các nhà phát triển luôn hỏi làm sao giữ hình ảnh trong dòng mà không phải quản lý các tệp riêng biệt. Tin tốt là Aspose.Words for Java làm cho việc này trở nên dễ dàng: bạn có thể chuyển tài liệu Word sang Markdown và tự động nhúng mọi hình ảnh dưới dạng chuỗi Base64. + +Trong tutorial này, chúng ta sẽ đi qua toàn bộ quy trình—từ việc tải một tệp `.docx` có chứa hình ảnh, đến việc cấu hình callback `MarkdownSaveOptions` thực hiện công việc nặng, và cuối cùng lưu kết quả thành một tệp `.md` sạch sẽ. Khi kết thúc, bạn sẽ biết chính xác cách **convert word to markdown**, **convert images to base64**, và **save word as markdown** mà không để lại các thư mục hình ảnh rải rác. Không cần công cụ bên ngoài, không cần xử lý thủ công—chỉ cần đoạn mã Java thuần túy mà bạn có thể đưa vào bất kỳ dự án nào. + +## Những Gì Bạn Cần Chuẩn Bị + +- **Java 17** (hoặc bất kỳ JDK mới nào) – mã sử dụng cú pháp lambda, nhưng bạn có thể điều chỉnh cho các phiên bản cũ hơn. +- Thư viện **Aspose.Words for Java** (phiên bản mới nhất tính đến năm 2026). Thêm dependency Maven hoặc JAR vào classpath. +- Một tệp **DOCX** mẫu chứa ít nhất một hình ảnh. +- Một IDE hoặc trình soạn thảo văn bản đơn giản—Visual Studio Code, IntelliJ IDEA, hoặc thậm chí `vim` cũng đủ. + +Nếu bạn đã có những thứ trên, tuyệt vời—hãy bắt đầu ngay. + +## Bước 1: Tải Tài Liệu Word + +Đầu tiên chúng ta tạo một thể hiện `Document` trỏ tới tệp nguồn. Đây là bước giống nhau dù bạn **convert docx to markdown** hay chỉ đọc tệp cho mục đích khác. + +```java +import com.aspose.words.*; + +public class MarkdownResourceCallback { + public static void main(String[] args) throws Exception { + // Load the source DOCX that contains images + Document doc = new Document("YOUR_DIRECTORY/doc-with-images.docx"); +``` + +> **Tại sao lại quan trọng:** Đối tượng `Document` là điểm vào cho mọi thao tác Aspose. Nó chứa toàn bộ cấu trúc Word—bao gồm hình ảnh, bảng và kiểu—để callback sau này có thể kiểm tra từng tài nguyên. + +## Bước 2: Tạo MarkdownSaveOptions và Đăng Ký Callback Lưu Tài Nguyên + +Phép màu nằm trong `MarkdownSaveOptions`. Bằng cách gắn một `IResourceSavingCallback` chúng ta có thể kiểm soát cách mỗi tài nguyên bên ngoài (như hình ảnh) được ghi. + +```java + // Configure Markdown save options + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions(); + + // Register the callback that will embed images as Base64 + mdOptions.setResourceSavingCallback(new IResourceSavingCallback() { + @Override + public void resourceSaving(ResourceSavingArgs args) { + // The callback fires for every resource Aspose wants to write + if (args.getResourceType() == ResourceType.IMAGE) { + // Tell Aspose we don’t want a separate image file + args.setKeepResourceOriginalName(false); + // Give the image a predictable name (optional) + args.setResourceFileName("image_" + args.getResourceFileName()); + // Force in‑memory saving – this triggers Base64 embedding + args.setSaveToMemory(true); + } + } + }); +``` + +### H3: Tại Sao Dùng `setSaveToMemory(true)`? + +Khi `saveToMemory` được bật, Aspose sẽ ghi byte của hình ảnh vào một luồng bộ nhớ thay vì ghi ra tệp. Bộ xuất Markdown sau đó chuyển luồng này thành chuỗi Base64 và chèn trực tiếp vào thẻ ảnh Markdown: + +```markdown +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +Đó là cốt lõi của **embed images as base64**. + +## Bước 3: Lưu Tài Liệu Dưới Dạng Markdown + +Khi callback đã được thiết lập, bước cuối cùng chỉ cần gọi `save`. Đây là lúc chúng ta thực sự **convert word to markdown** và, nhờ callback, cũng **convert images to base64**. + +```java + // Save the document as Markdown – this triggers the callback + doc.save("YOUR_DIRECTORY/out.md", mdOptions); + } +} +``` + +> **Kết quả:** `out.md` chứa văn bản Markdown với mỗi hình ảnh được biểu diễn dưới dạng URI `data:`. Không có tệp hình ảnh phụ được tạo trên đĩa, vì vậy thư mục vẫn gọn gàng. + +## Bước 4: Kiểm Tra Kết Quả và Những Cạm Bẫy Thường Gặp + +Mở `out.md` đã tạo trong bất kỳ trình xem Markdown nào (VS Code, GitHub, hoặc một trình tạo site tĩnh). Bạn sẽ thấy thứ gì đó giống như: + +```markdown +# Sample Document + +Here is an inline image: + +![image_image1.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...) +``` + +### Danh Sách Kiểm Tra Khắc Phục Sự Cố + +| Vấn đề | Nguyên Nhân Có Thể | Cách Khắc Phục | +|-------|-------------------|----------------| +| Hình ảnh hiển thị dưới dạng liên kết hỏng | `setSaveToMemory` bị bỏ qua | Đảm bảo `args.setSaveToMemory(true);` nằm trong callback | +| Chuỗi Base64 bị cắt ngắn | Mã hoá tệp đầu ra không khớp | Lưu Markdown bằng UTF‑8 (mặc định của Aspose) | +| Tên tệp không mong muốn | `setKeepResourceOriginalName(true)` | Đặt thành `false` để buộc logic đặt tên tùy chỉnh | + +## Bước 5: Các Biến Thể Nâng Cao (Tùy Chọn) + +### Chỉ Nhúng Các Hình Ảnh Được Chọn Lọc + +Nếu bạn chỉ muốn nhúng một số hình ảnh nhất định (ví dụ: những hình lớn hơn 100 KB), hãy thêm kiểm tra kích thước: + +```java +if (args.getResourceType() == ResourceType.IMAGE) { + if (args.getResourceData().length > 100_000) { + args.setSaveToMemory(true); + } +} +``` + +### Sử Dụng Định Dạng Hình Ảnh Khác + +`ResourceSavingArgs` cung cấp byte thô, vì vậy bạn có thể mã hoá lại JPEG thành PNG trước khi nhúng—hữu ích khi trình tiêu thụ Markdown mục tiêu ưu tiên PNG. + +```java +if (args.getResourceFileName().endsWith(".jpg")) { + // Convert JPEG bytes to PNG bytes (requires an image library) + byte[] pngBytes = convertJpegToPng(args.getResourceData()); + args.setResourceData(pngBytes); + args.setResourceFileName(args.getResourceFileName().replace(".jpg", ".png")); + args.setSaveToMemory(true); +} +``` + +Những tùy chỉnh này minh họa độ linh hoạt của cách **embed images as base64** khi bạn **convert docx to markdown**. + +## Kết Luận + +Bạn vừa học cách **embed images as base64** khi **convert docx to markdown** bằng Aspose.Words for Java. Bằng cách gắn một `IResourceSavingCallback` đơn giản, thư viện thực hiện mọi công việc nặng: nó **convert word to markdown**, **convert images to base64**, và cuối cùng **save word as markdown** chỉ với một lời gọi `save`. + +Hãy thoải mái thử nghiệm—áp dụng các quy tắc lọc hình ảnh khác nhau, chuyển sang xuất HTML, hoặc kết hợp bước này với một trình tạo site tĩnh. Mẫu tương tự cũng hoạt động cho các định dạng khác (HTML, EPUB), vì vậy bạn có thể tái sử dụng callback ở bất kỳ nơi nào cần tài nguyên nội tuyến. + +**Bước tiếp theo:** +- Khám phá `HtmlSaveOptions` để tạo HTML‑với‑hình‑Base64. +- Kết hợp với pipeline CI để tự động hoá việc tạo tài liệu. +- Tìm hiểu `DocumentVisitor` của Aspose nếu bạn cần kiểm soát chi tiết hơn quá trình chuyển đổi. + +Chúc bạn lập trình vui vẻ và tận hưởng các tệp Markdown tự chứa sạch sẽ! + +## Các Tutorial Liên Quan + +- [How to Embed Images in Markdown When Converting DOCX](/words/english/java/document-conversion-and-export/how-to-embed-images-in-markdown-when-converting-docx/) +- [Convert docx to markdown – Export Math Equations to LaTeX with Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Save Images from Word – Aspose.Words for Java Guide](/words/english/java/document-loading-and-saving/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md b/words/vietnamese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md new file mode 100644 index 0000000000..57526e7d3b --- /dev/null +++ b/words/vietnamese/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-05-26 +description: Xuất file docx sang txt bằng Java và Aspose.Words. Tìm hiểu cách chuyển + đổi docx sang văn bản, bảo toàn Unicode và xuất Word thành txt trong vài bước. +draft: false +keywords: +- export docx to txt +- convert docx to text +- convert word to text +- plain text unicode +- export word as txt +language: vi +og_description: Xuất file docx sang txt trong Java. Hướng dẫn này chỉ cách chuyển + đổi docx sang văn bản, giữ nguyên Unicode dạng văn bản thuần, và xuất Word thành + txt một cách hiệu quả. +og_title: Xuất docx sang txt bằng Java – Hướng dẫn chi tiết +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + headline: Export docx to txt with Java – Complete Programming Guide + type: TechArticle +- description: Export docx to txt using Java and Aspose.Words. Learn how to convert + docx to text, preserve Unicode, and export word as txt in a few steps. + name: Export docx to txt with Java – Complete Programming Guide + steps: + - name: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + text: '**Checksum comparison** – compute a SHA‑256 hash of the `.txt` file before + and after a round‑trip conversion (txt → docx → txt) to ensure stability.' + - name: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + text: "**Search for Unicode markers** – use `grep` or IDE find‑in‑file to locate + characters like “\U0001F60A”." + - name: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + text: '**Open in multiple editors** – some old Windows Notepad versions still + misinterpret UTF‑8 without BOM; opening the file in VS Code confirms proper + encoding.' + type: HowTo +tags: +- Java +- Aspose.Words +- File Conversion +title: Xuất docx sang txt bằng Java – Hướng dẫn lập trình toàn diện +url: /vi/java/document-conversion-and-export/export-docx-to-txt-with-java-complete-programming-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Xuất docx sang txt bằng Java – Hướng dẫn lập trình đầy đủ + +Bạn đã bao giờ cần **export docx to txt** nhưng lo lắng về việc mất các ký tự đặc biệt? Bạn không phải là người duy nhất. Khi bạn chuyển đổi tài liệu Word sang các tệp plain‑text, các ký hiệu Unicode, bảng và thậm chí định dạng đơn giản có thể biến mất như ma thuật. + +Trong hướng dẫn này, chúng ta sẽ đi qua một cách đáng tin cậy để **export docx to txt** bằng cách sử dụng Aspose.Words for Java, bảo toàn mọi glyph Unicode và giữ cho bố cục bảng có thể đọc được. Khi kết thúc, bạn cũng sẽ biết cách **convert docx to text**, **convert word to text**, và thậm chí **export word as txt** một cách suôn sẻ. + +## Những gì hướng dẫn này bao gồm + +* Cài đặt Aspose.Words trong dự án Java +* Tải tệp DOCX và chuẩn bị nó cho đầu ra plain‑text +* Cấu hình hỗ trợ **plain text unicode** thông qua `TxtSaveOptions` +* Các mẹo tùy chọn để giữ bảng đọc được trong tệp `.txt` kết quả +* Lưu tệp và xác minh đầu ra + +Không có script bên ngoài, không có công cụ dòng lệnh bí ẩn—chỉ là mã Java thuần túy mà bạn có thể chèn vào bất kỳ dự án Maven hoặc Gradle nào. + +> **Tại sao lại quan tâm?** Các tệp plain‑text nhẹ, thân thiện với hệ thống kiểm soát phiên bản, và hoàn hảo cho việc lập chỉ mục tìm kiếm hoặc các pipeline xử lý downstream. Nếu bạn từng cố gắng `cat` một tệp Word và nhận được nội dung rác, hướng dẫn này sẽ giải quyết vấn đề đó. + +--- + +## Xuất docx sang txt – Tổng quan + +Trước khi chúng ta đi vào mã, hãy làm rõ thuật ngữ. **Export docx to txt** có nghĩa là lấy một gói Microsoft Word `.docx` và ghi nội dung văn bản của nó vào một tệp `.txt` đơn giản. Khác với chuyển đổi PDF, việc xuất văn bản sẽ loại bỏ kiểu dáng nhưng có thể giữ các ngắt dòng, dấu đoạn và—nếu bạn cấu hình đúng—các ký tự Unicode như biểu tượng cảm xúc, chữ có dấu, hoặc các script châu Á. + +Aspose.Words làm cho việc này trở nên dễ dàng vì nó trừu tượng hoá định dạng tệp Word và cung cấp một lớp `TxtSaveOptions` nơi bạn có thể chỉ định mã hoá, cách xử lý bảng, và hơn thế nữa. + +### Yêu cầu trước + +* Java 11 hoặc mới hơn (API hoạt động với Java 8+, nhưng chúng ta sẽ giả sử một JDK mới) +* Aspose.Words for Java JAR (có sẵn từ Maven Central) +* Một tệp mẫu `unicode.docx` chứa các ký tự Unicode đa dạng—ví dụ “こんにちは”, “😊”, và một bảng đơn giản + +Nếu bạn đã có những thứ này, hãy bắt đầu. + +--- + +## Bước 1: Tải tệp DOCX (Convert docx to text) + +Điều đầu tiên bạn cần làm là đọc tài liệu nguồn vào bộ nhớ. Đây là nơi quá trình **convert docx to text** chính thức bắt đầu. + +```java +import com.aspose.words.*; + +public class ExportDocxToTxt { + public static void main(String[] args) throws Exception { + // Load the source DOCX. Replace the path with your actual file location. + Document doc = new Document("YOUR_DIRECTORY/unicode.docx"); +``` + +*Tiêu đề quan trọng:* `Document` là đại diện của Aspose.Words cho một tệp Word. Khi tải nó, bạn sẽ truy cập được tất cả các đoạn, bảng và thậm chí các phần tử ẩn. Nếu tệp không được tìm thấy, Aspose sẽ ném ra một `FileNotFoundException` rõ ràng, vì vậy bạn sẽ ngay lập tức biết lỗi gì đã xảy ra. + +--- + +## Bước 2: Cấu hình TxtSaveOptions cho Unicode (Plain text unicode) + +Các tệp plain‑text chỉ là luồng byte, vì vậy bạn phải cho Java biết bộ ký tự nào sẽ dùng. UTF‑8 là tiêu chuẩn de‑facto cho **plain text unicode** vì nó có thể mã hoá mọi mã điểm Unicode. + +```java + // Create TXT save options and enforce UTF‑8 encoding. + TxtSaveOptions saveOptions = new TxtSaveOptions(); + // This guarantees that every Unicode character survives the conversion. + saveOptions.setEncoding(java.nio.charset.StandardCharsets.UTF_8); +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn bỏ qua lời gọi `setEncoding`, Aspose sẽ mặc định sử dụng charset mặc định của nền tảng, trên nhiều máy Windows là Windows‑1252. Mặc định này sẽ lặng lẽ loại bỏ các ký tự như “ß” hoặc “—”. + +--- + +## Bước 3: Bảo tồn bố cục bảng (Tùy chọn, nhưng hữu ích cho khả năng đọc) + +Khi bạn **export word as txt**, các bảng thường bị làm phẳng thành một dòng văn bản duy nhất, khiến chúng không đọc được. Aspose.Words cung cấp một cờ đơn giản để giữ cấu trúc trực quan. + +```java + // Keep simple tables readable in the plain‑text output. + saveOptions.setPreserveTableLayout(true); +``` + +*Khi nào nên dùng:* Nếu DOCX nguồn của bạn chứa hoá đơn, lịch trình, hoặc bất kỳ dữ liệu dạng lưới nào, việc bật `PreserveTableLayout` sẽ chèn các tab và ngắt dòng để tệp kết quả vẫn giống một bảng. Nếu bạn không cần, có thể bỏ qua dòng này và nhận được đầu ra gọn hơn. + +--- + +## Bước 4: Lưu tài liệu dưới dạng Plain‑Text (Export word as txt) + +Bây giờ công việc nặng đã hoàn thành—chỉ cần ghi các byte ra đĩa. + +```java + // Save the document as a UTF‑8 encoded .txt file. + doc.save("YOUR_DIRECTORY/plain.txt", saveOptions); + } +} +``` + +Chạy chương trình sẽ tạo ra `plain.txt` trong cùng thư mục. Mở nó bằng bất kỳ trình soạn thảo văn bản nào (Notepad++, VS Code, thậm chí `cat` trong terminal) và bạn sẽ thấy: + +``` +Hello, world! こんにちは 😊 +------------------------------- +| Item | Qty | Price | +|------|-----|-------| +| Apple| 2 | $1.00 | +| Banana| 5 | $0.50 | +``` + +Chú ý cách lời chào tiếng Nhật và biểu tượng cảm xúc vẫn còn, và bảng giữ được các cột nhờ `PreserveTableLayout`. Đó là bản chất của một **export docx to txt** sạch sẽ. + +--- + +## Bước 5: Xác minh đầu ra (Kiểm tra hợp lý khi Convert word to text) + +Một kiểm tra nhanh ngăn ngừa mất dữ liệu im lặng. Dưới đây là một vài cách để xác nhận bạn thực sự **convert word to text** đúng cách: + +1. **Checksum comparison** – tính toán hàm băm SHA‑256 của tệp `.txt` trước và sau một vòng chuyển đổi (txt → docx → txt) để đảm bảo tính ổn định. +2. **Search for Unicode markers** – sử dụng `grep` hoặc tính năng tìm‑trong‑tệp của IDE để tìm các ký tự như “😊”. +3. **Open in multiple editors** – một số phiên bản Notepad cũ trên Windows vẫn diễn giải sai UTF‑8 nếu không có BOM; mở tệp trong VS Code xác nhận mã hoá đúng. + +Nếu bất kỳ kiểm tra nào này thất bại, hãy kiểm tra lại rằng `saveOptions.setEncoding(StandardCharsets.UTF_8)` đã được đặt và tệp DOCX nguồn thực sự chứa văn bản Unicode. + +--- + +## Những khó khăn thường gặp & Cách tránh chúng + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|----------------|-----| +| **Missing characters** | Charset hệ thống mặc định (ví dụ Windows‑1252) loại bỏ các glyph không phải ASCII. | Đặt rõ UTF‑8 bằng `saveOptions.setEncoding`. | +| **Tables become a single line** | `PreserveTableLayout` để mặc định `false`. | Gọi `saveOptions.setPreserveTableLayout(true)`. | +| **File not found** | Đường dẫn sai hoặc thiếu quyền đọc. | Sử dụng đường dẫn tuyệt đối hoặc `Paths.get(...)` với xử lý ngoại lệ phù hợp. | +| **Performance slowdown on huge docs** | Tải toàn bộ tài liệu vào bộ nhớ. | Dòng dữ liệu tài liệu theo khối bằng `DocumentBuilder` nếu chỉ cần các phần cụ thể. | + +--- + +## Bonus: Xuất nhiều tệp DOCX trong một lô + +Nếu bạn cần **convert docx to text** cho toàn bộ thư mục, hãy bao bọc logic trong một vòng lặp: + +```java +import java.nio.file.*; + +public class BatchExport { + public static void main(String[] args) throws Exception { + Path sourceDir = Paths.get("YOUR_DIRECTORY"); + TxtSaveOptions opts = new TxtSaveOptions(); + opts.setEncoding(StandardCharsets.UTF_8); + opts.setPreserveTableLayout(true); + + try (DirectoryStream stream = Files.newDirectoryStream(sourceDir, "*.docx")) { + for (Path docxPath : stream) { + Document doc = new Document(docxPath.toString()); + String txtPath = docxPath.toString().replaceAll("\\.docx$", ".txt"); + doc.save(txtPath, opts); + System.out.println("Exported: " + txtPath); + } + } + } +} +``` + +Đoạn mã này **export docx to txt** cho mọi tệp trong thư mục, giúp bạn tiết kiệm hàng giờ công việc thủ công. + +--- + +## Kết luận + +Bạn vừa học cách **export docx to txt** bằng Java, đảm bảo mọi ký tự Unicode vẫn nguyên vẹn, các bảng vẫn đọc được, và toàn bộ quy trình có thể lặp lại. Bằng cách cấu hình `TxtSaveOptions` cho UTF‑8 và tùy chọn bảo tồn bố cục bảng, bạn có thể tin cậy **convert docx to text**, **convert word to text**, và **export word as txt** cho bất kỳ quy trình downstream nào. + +Sẵn sàng cho thử thách tiếp theo? Hãy thử xuất sang các định dạng plain‑text khác như markdown (`.md`) hoặc CSV, hoặc khám phá khả năng chuyển đổi PDF của Aspose.Words. Các nguyên tắc giống nhau—mã hoá rõ ràng, bảo tồn bố cục, và kiểm tra kỹ lưỡng—đều áp dụng cho mọi trường hợp. + +Chúc lập trình vui vẻ, và mong các tệp văn bản của bạn luôn giữ được độ phong phú Unicode! + +--- + +![Diagram showing the export docx to txt pipeline](/images/export-docx-to-txt-pipeline.png){alt="export docx to txt pipeline diagram"} + +## Các hướng dẫn liên quan + +- [Chuyển đổi Docx sang Txt](/words/english/net/basic-conversions/docx-to-txt/) +- [aspose word to pdf – Chuyển đổi DOCX sang PDF trong Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) +- [Chuyển đổi docx sang markdown – Xuất phương trình toán học sang LaTeX với Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md b/words/vietnamese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md new file mode 100644 index 0000000000..c53ba6966e --- /dev/null +++ b/words/vietnamese/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-05-26 +description: Lưu tài liệu dưới dạng PDF bằng Aspose.Words Java và thêm khả năng truy + cập cho PDF. Học cách chuyển đổi docx sang PDF, gắn thẻ các đường kẻ ngang và đảm + bảo tuân thủ PDF/UA‑2. +draft: false +keywords: +- save document as pdf +- convert docx to pdf +- add accessibility to pdf +- tag horizontal rules +- aspose convert docx pdf +language: vi +og_description: Lưu tài liệu dưới dạng PDF với Aspose.Words Java đồng thời thêm khả + năng truy cập cho PDF. Hướng dẫn chi tiết từng bước để chuyển đổi docx sang PDF + và gắn thẻ các đường kẻ ngang để tuân thủ PDF/UA‑2. +og_title: Lưu tài liệu dưới dạng PDF với Aspose.Words Java – Khả năng truy cập trở + nên dễ dàng +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + headline: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + type: TechArticle +- description: Save document as PDF using Aspose.Words Java and add accessibility + to PDF. Learn to convert docx to PDF, tag horizontal rules, and ensure PDF/UA‑2 + compliance. + name: Save Document as PDF with Aspose.Words Java – Full Accessibility Guide + steps: + - name: Tag structural elements (headings, tables, etc.). + text: Tag structural elements (headings, tables, etc.). + - name: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + text: Mark decorative elements—like horizontal rules—as *artifacts*, so screen + readers ignore them. + - name: Insert the necessary PDF/UA metadata. + text: Insert the necessary PDF/UA metadata. + - name: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + text: '**Missing License** – The trial version adds a watermark that can break + PDF/UA validation. Apply your license early in `main`:' + - name: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + text: '**Incorrect Input Path** – A `FileNotFoundException` will stop the conversion. + Use absolute paths or place the DOCX in the project root and reference it with + `new File("input.docx").getAbsolutePath()`.' + - name: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + text: '**Using Older Aspose Version** – PDF/UA support was added in version 22.9. + Upgrade to the latest release to avoid missing features.' + - name: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + text: '**Horizontal Rule as Image** – If you inserted the line as an image instead + of a native Word horizontal rule, Aspose treats it as a regular image, not an + artifact. Replace the image with Word’s built‑in *Horizontal Line* for proper + tagging.' + type: HowTo +tags: +- Aspose.Words +- Java +- PDF/UA +- Accessibility +title: Lưu tài liệu dưới dạng PDF với Aspose.Words Java – Hướng dẫn đầy đủ về khả + năng truy cập +url: /vi/java/document-conversion-and-export/save-document-as-pdf-with-aspose-words-java-full-accessibili/ +--- + +{{< 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 Java – Hướng dẫn đầy đủ về khả năng truy cập + +Bạn đã bao giờ tự hỏi làm thế nào để **save document as PDF** mà vẫn giữ được khả năng truy cập cho các trình đọc màn hình chưa? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần *convert docx to pdf* và vẫn đáp ứng tiêu chuẩn PDF/UA‑2, đặc biệt khi nguồn tài liệu chứa các đường kẻ ngang phải được gắn thẻ đúng cách. Trong hướng dẫn này, chúng tôi sẽ đi qua các bước chính xác để **save document as PDF** bằng Aspose.Words cho Java, tự động **add accessibility to PDF**, và đảm bảo mọi đường kẻ ngang đều **tagged** như một artifact. + +Chúng ta sẽ bắt đầu với một dự án Java sạch, tải một DOCX đã có các đường kẻ ngang, cấu hình các tùy chọn lưu PDF để tuân thủ PDF/UA‑2, và cuối cùng ghi ra một PDF hoàn toàn có khả năng truy cập. Khi hoàn thành, bạn sẽ có thể **save document as pdf** một cách tự tin rằng nó vượt qua các kiểm tra khả năng truy cập. + +## Prerequisites + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +- Java 8 hoặc mới hơn đã được cài đặt (hướng dẫn đã được kiểm tra trên JDK 17). +- Maven 3.6+ (hoặc Gradle nếu bạn thích) để quản lý các phụ thuộc. +- Giấy phép hợp lệ của Aspose.Words cho Java (bản dùng thử miễn phí vẫn hoạt động, nhưng giấy phép sẽ loại bỏ watermark đánh giá). +- Một file DOCX (`input.docx`) chứa ít nhất một đường kẻ ngang — nghĩ đến một đường phân cách đơn giản bạn có thể chèn trong Word. + +> **Pro tip:** Nếu bạn chưa có file DOCX, chỉ cần tạo một tài liệu Word mới, gõ vài đoạn văn, chèn *Insert → Horizontal Line*, lưu dưới tên `input.docx`, và đặt nó vào thư mục bạn muốn. + +## Step 1: Set Up the Maven Project + +Đầu tiên, tạo một dự án Maven mới (hoặc thêm vào dự án hiện có). `pom.xml` cần có phụ thuộc Aspose.Words: + +```xml + + + 4.0.0 + com.example + aspose-pdf-ua-demo + 1.0.0 + + + + + com.aspose + aspose-words + 24.9 + + + +``` + +> **Why this matters:** Thêm artifact `aspose-words` là bước đầu tiên để *convert docx to pdf*. Nếu không có, trình biên dịch sẽ không nhận ra `Document`, `PdfSaveOptions`, và các lớp quan trọng khác. + +## Step 2: Load the Source DOCX Containing Horizontal Rules + +Bây giờ chúng ta sẽ viết một lớp Java nhỏ để tải DOCX. Đây là nơi phần **tag horizontal rules** bắt đầu — Aspose.Words tự động xử lý một đường kẻ ngang như một đoạn văn có viền, nhưng chúng ta sẽ để engine PDF/UA thực hiện việc gắn thẻ. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // Step 2.1: Define the input and output locations + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // Step 2.2: Load the source DOCX that contains horizontal rules + Document doc = new Document(inputPath); +``` + +Lưu ý chúng ta chưa lưu gì cả — chỉ **loading** DOCX, đây là nửa đầu của *convert docx to pdf*. Đối tượng `Document` hiện đã chứa toàn bộ nội dung Word, bao gồm bất kỳ đường kẻ ngang nào bạn đã chèn. + +## Step 3: Configure PDF Save Options for PDF/UA‑2 Compliance + +Phép màu của **adding accessibility to PDF** nằm trong `PdfSaveOptions`. Bằng cách đặt mức tuân thủ thành `PDF_UA_2`, Aspose.Words sẽ: + +1. Gắn thẻ các yếu tố cấu trúc (heading, table, v.v.). +2. Đánh dấu các yếu tố trang trí — như các đường kẻ ngang — như *artifacts*, để trình đọc màn hình bỏ qua chúng. +3. Chèn các siêu dữ liệu cần thiết cho PDF/UA. + +```java + // Step 3.1: Create PDF save options + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + + // Step 3.2: Enable PDF/UA‑2 compliance (adds accessibility to PDF) + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + + // Optional: Set a custom PDF title for better accessibility + pdfOptions.setTitle("Accessible PDF generated from DOCX"); +``` + +> **Why set compliance?** Nếu không có `PDF_UA_2`, PDF tạo ra có thể vẫn đọc được nhưng sẽ không vượt qua các công cụ kiểm tra tự động về khả năng truy cập. Yêu cầu **tag horizontal rules** được đáp ứng tự động vì PDF/UA sẽ coi chúng là *artifacts* khi bật cờ tuân thủ. + +## Step 4: Save the Document as a PDF + +Bây giờ chúng ta cuối cùng **save document as pdf**. Dòng lệnh duy nhất này thực hiện toàn bộ công việc — chuyển đổi DOCX, áp dụng các thẻ khả năng truy cập, và ghi file ra đĩa. + +```java + // Step 4: Save the document as a PDF using the configured options + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Chạy lớp (`mvn compile exec:java -Dexec.mainClass=com.example.PdfUaHorizontalRule`) và bạn sẽ thấy thông báo xác nhận. Mở file `ua_compliant.pdf` vừa tạo trong Adobe Acrobat và kiểm tra **File → Properties → Description → PDF/A, PDF/UA** — bạn sẽ thấy “PDF/UA‑2” được liệt kê. + +### Expected Output + +``` +PDF saved successfully at: YOUR_DIRECTORY/ua_compliant.pdf +``` + +Mở PDF, bạn sẽ nhận thấy: + +- Văn bản tài liệu có thể chọn và tìm kiếm. +- Đường kẻ ngang không hiển thị với trình đọc màn hình (được xử lý như một artifact). +- PDF vượt qua các công cụ kiểm tra PDF/UA cơ bản (ví dụ: PAC 3). + +## Step 5: Verify Accessibility – Quick Checklist + +Mặc dù Aspose.Words thực hiện hầu hết công việc, nhưng việc kiểm tra đầu ra vẫn là thực hành tốt. + +| Check | How to Verify | +|-------|----------------| +| **Document title** | Mở Acrobat → File → Properties → trường Title (phải khớp với `pdfOptions.setTitle`). | +| **Artifact tagging** | Sử dụng công cụ “Reading Order” của Acrobat. Các đường kẻ ngang phải xuất hiện dưới dạng *Artifact* (màu xám). | +| **Logical reading order** | Chạy “Accessibility Checker” trong Acrobat; đảm bảo không có lỗi cấu trúc. | +| **Tagged PDF** | Trong Acrobat, mở bảng “Tags” – bạn sẽ thấy một cây phân cấp (Document → Section → Paragraph, v.v.). | +| **PDF/UA compliance** | Acrobat sẽ hiển thị “PDF/UA‑2” trong tab “Standards”. | + +Nếu bất kỳ mục nào không đạt, hãy kiểm tra lại rằng bạn đang dùng phiên bản Aspose.Words mới nhất và `setCompliance(PdfCompliance.PDF_UA_2)` đã được áp dụng đúng. + +## Common Pitfalls & How to Avoid Them + +1. **Missing License** – Phiên bản dùng thử sẽ thêm watermark có thể phá vỡ việc xác thực PDF/UA. Áp dụng giấy phép ngay trong `main`: + ```java + License license = new License(); + license.setLicense("Aspose.Words.Java.lic"); + ``` +2. **Incorrect Input Path** – `FileNotFoundException` sẽ dừng quá trình chuyển đổi. Sử dụng đường dẫn tuyệt đối hoặc đặt DOCX ở thư mục gốc dự án và tham chiếu bằng `new File("input.docx").getAbsolutePath()`. +3. **Using Older Aspose Version** – Hỗ trợ PDF/UA được thêm vào từ phiên bản 22.9. Nâng cấp lên bản mới nhất để tránh thiếu tính năng. +4. **Horizontal Rule as Image** – Nếu bạn chèn đường kẻ dưới dạng hình ảnh thay vì đường kẻ ngang gốc của Word, Aspose sẽ coi nó là hình ảnh bình thường, không phải artifact. Thay thế hình ảnh bằng *Horizontal Line* tích hợp của Word để gắn thẻ đúng. + +## Extending the Solution – What If You Need More? + +- **Custom Tags**: Nếu bạn có các yếu tố trang trí khác (ví dụ: biểu tượng trang trí), bạn có thể tự đánh dấu chúng là artifacts bằng `PdfSaveOptions.setArtifactTaggingEnabled(true)`. +- **Multiple Documents**: Lặp qua một thư mục chứa nhiều file DOCX và chuyển đổi hàng loạt, tái sử dụng cùng một instance của `PdfSaveOptions` để tăng hiệu suất. +- **Adding a Language Tag**: Đối với PDF đa ngôn ngữ, đặt `pdfOptions.setLanguage("en-US")` để hỗ trợ công nghệ trợ năng chọn giọng đọc phù hợp. + +## Full Working Example (All Code Together) + +Dưới đây là chương trình Java hoàn chỉnh, có thể chạy ngay. Sao chép‑dán vào IDE, điều chỉnh đường dẫn, và chạy. + +```java +package com.example; + +import com.aspose.words.*; + +public class PdfUaHorizontalRule { + public static void main(String[] args) throws Exception { + // ----- License (optional but recommended) ----- + // License license = new License(); + // license.setLicense("Aspose.Words.Java.lic"); + + // ----- Define file locations ----- + String inputPath = "YOUR_DIRECTORY/input.docx"; + String outputPath = "YOUR_DIRECTORY/ua_compliant.pdf"; + + // ----- Load the DOCX that contains horizontal rules ----- + Document doc = new Document(inputPath); + + // ----- Configure PDF save options for PDF/UA‑2 compliance ----- + PdfSaveOptions pdfOptions = new PdfSaveOptions(); + pdfOptions.setCompliance(PdfSaveOptions.PdfCompliance.PDF_UA_2); + pdfOptions.setTitle("Accessible PDF generated from DOCX"); + + // ----- Save the document as PDF (this is where we actually save document as pdf) ----- + doc.save(outputPath, pdfOptions); + + System.out.println("PDF saved successfully at: " + outputPath); + } +} +``` + +Chạy nó, mở PDF đã tạo, và bạn sẽ có một file sạch, có khả năng truy cập, sẵn sàng phân phối. + +## Conclusion + +Chúng ta vừa chứng minh cách **save document as pdf** với Aspose.Words cho Java đồng thời tự động **add accessibility to pdf** và **tag horizontal rules** như artifacts. Những điểm quan trọng cần nhớ: + +- Sử dụng `PdfSaveOptions` với mức tuân thủ `PDF_UA_2` để đáp ứng tiêu chuẩn khả năng truy cập. +- Tải DOCX và gọi `doc.save(..., pdfOptions)` là tất cả những gì bạn cần để **convert docx to pdf**. +- Các đường kẻ ngang được xử lý tự động — không cần code thêm, đáp ứng yêu cầu **tag horizontal rules**. +- Cách tiếp cận này hoàn toàn **aspose convert docx pdf** tương thích, hoạt động với phiên bản thư viện mới nhất, và tạo ra PDF sẵn sàng kiểm định. + +Sẵn sàng cho thử thách tiếp theo? Hãy thử thêm siêu dữ liệu tùy chỉnh, nhúng phông chữ, hoặc xử lý hàng loạt một thư mục đầy các file DOCX. Mỗi mở rộng đều dựa trên nền tảng chúng ta đã xây dựng. + +Có câu hỏi về tuân thủ PDF/UA, giấy phép, hoặc cách xử lý các yếu tố Word khác? Để lại bình luận hoặc tham khảo tài liệu chính thức của Aspose — có rất nhiều ví dụ để khám phá. Chúc lập trình vui vẻ và tận hưởng việc tạo PDF có khả năng truy cập! + +![lưu tài liệu dưới dạng pdf bằng Aspose.Words Java – ví dụ PDF có khả năng truy cập](placeholder-image.png "lưu tài liệu dưới dạng pdf bằng Aspose.Words Java") + +## Related Tutorials + +- [How to save document as pdf with Aspose.Words for Java](/words/english/java/document-loading-and-saving/saving-documents-as-pdf/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [aspose word to pdf – Convert DOCX to PDF in Java](/words/english/java/document-conversion-and-export/aspose-word-to-pdf-convert-docx-to-pdf-in-java/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md b/words/vietnamese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md new file mode 100644 index 0000000000..999b8095d0 --- /dev/null +++ b/words/vietnamese/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-26 +description: Lưu Word dưới dạng markdown và khám phá cách xuất các công thức toán + học sang LaTeX bằng Aspose.Words cho Java. Chuyển đổi các công thức Word sang LaTeX + chỉ trong vài dòng. +draft: false +keywords: +- save word as markdown +- how to export math +- convert word equations latex +- docx to markdown latex +language: vi +og_description: Lưu Word dưới dạng markdown và tìm hiểu cách xuất các phương trình + toán học sang LaTeX bằng Aspose.Words cho Java. Một hướng dẫn đầy đủ, có thể chạy + được. +og_title: Lưu Word dưới dạng markdown – Xuất công thức sang LaTeX bằng Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + headline: Save word as markdown – Export Math to LaTeX with Java + type: TechArticle +- description: Save word as markdown and discover how to export math equations to + LaTeX using Aspose.Words for Java. Convert Word equations LaTeX in just a few + lines. + name: Save word as markdown – Export Math to LaTeX with Java + steps: + - name: Maven + text: '```xml com.aspose aspose-words + 24.9 + ```' + - name: Gradle + text: '```gradle implementation ''com.aspose:aspose-words:24.9'' ```' + - name: Why this works + text: '- **`Document`** is Aspose’s entry point; it abstracts the `.docx` file + and gives you access to every node, including equations. - **`MarkdownSaveOptions`** + tells the library *how* you want the output. The default behavior is to render + equations as images, which defeats the purpose of a text‑based f' + type: HowTo +tags: +- Aspose.Words +- Java +- Markdown +- LaTeX +- Office Math +title: Lưu Word dưới dạng Markdown – Xuất công thức sang LaTeX bằng Java +url: /vi/java/document-conversion-and-export/save-word-as-markdown-export-math-to-latex-with-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lưu Word thành markdown – Xuất công thức toán học sang LaTeX với Java + +Bạn đã bao giờ cần **save word as markdown** nhưng lo lắng các công thức của mình sẽ biến thành một mớ hỗn độn? Bạn không phải là người duy nhất. Trong hướng dẫn này, chúng tôi sẽ hướng dẫn **how to export math** từ tệp `.docx` trực tiếp sang LaTeX trong khi phần còn lại của tài liệu trở thành Markdown sạch sẽ. + +Chúng tôi sẽ bao phủ mọi thứ từ việc thiết lập thư viện Aspose.Words đến việc xác minh tệp `out.md` cuối cùng. Khi kết thúc, bạn sẽ có thể **convert word equations latex** trong một lời gọi phương thức duy nhất, và bạn sẽ hiểu những chi tiết nhỏ giúp quá trình chuyển đổi đáng tin cậy. + +--- + +## Những gì bạn cần + +- **Java 8+** – mã chạy trên bất kỳ JDK hiện đại nào. +- **Aspose.Words for Java** – hoặc là phụ thuộc Maven/Gradle hoặc file JAR nếu bạn thích cài đặt thủ công. +- Một tài liệu Word (`math.docx`) chứa ít nhất một công thức Office Math. +- Một IDE hoặc dòng lệnh `javac`/`java` thuần – bất kỳ gì bạn cảm thấy thoải mái. + +Nếu bạn đã có chúng, tuyệt vời. Nếu chưa, phần tiếp theo sẽ chỉ cho bạn cách đưa thư viện vào dự án. + +## Lưu Word thành markdown – Bước 1: Thêm Aspose.Words vào Dự án của bạn + +### Maven + +```xml + + com.aspose + aspose-words + 24.9 + +``` + +### Gradle + +```gradle +implementation 'com.aspose:aspose-words:24.9' +``` + +> **Mẹo:** Aspose cung cấp giấy phép tạm thời miễn phí để thử nghiệm. Đặt file `license.xml` vào thư mục resources và gọi `License license = new License(); license.setLicense("license.xml");` trước khi tải bất kỳ tài liệu nào. + +Khi phụ thuộc đã được giải quyết, bạn đã sẵn sàng viết mã chuyển đổi. + +## Cách xuất công thức toán học sang LaTeX + +Công việc nặng nhọc được thực hiện bởi `MarkdownSaveOptions`. Bằng cách chuyển `OfficeMathExportMode` của nó sang `LATEX`, mọi đối tượng Office Math sẽ được render thành một đoạn LaTeX trong đầu ra Markdown. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Load the Word document containing Office Math equations + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // Create Markdown save options + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + + // Configure the options to export Office Math as LaTeX + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // Save the document as a Markdown file with LaTeX equations + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + } +} +``` + +### Tại sao cách này hoạt động + +- **`Document`** là điểm vào của Aspose; nó trừu tượng hoá tệp `.docx` và cung cấp cho bạn quyền truy cập vào mọi node, bao gồm các công thức. +- **`MarkdownSaveOptions`** cho thư viện biết *cách* bạn muốn đầu ra. Hành vi mặc định là render công thức dưới dạng hình ảnh, điều này làm mất mục đích của định dạng dựa trên văn bản. +- **`OfficeMathExportMode.LATEX`** buộc engine chuyển đổi mỗi node `OfficeMath` thành tương đương LaTeX, cho phép các trình phân tích Markdown (như GitHub hoặc Jekyll) render khi kết hợp với plugin MathJax. + +## Chuyển đổi công thức Word sang LaTeX – Bước 2: Xác minh Đầu ra Markdown + +Sau khi chạy chương trình, mở `out.md`. Bạn sẽ thấy một thứ gì đó như sau: + +```markdown +# Sample Document + +This paragraph contains an inline equation $E = mc^2$ and a displayed equation: + +$$ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +$$ + +Regular text continues here. +``` + +> **Lưu ý:** Các đoạn LaTeX được bao quanh bởi `$…$` cho toán học nội dòng và `$$…$$` cho toán học khối. Đây là cú pháp chuẩn mà hầu hết các trình tạo site tĩnh hiểu khi MathJax được bật. + +Nếu bạn muốn các công thức chỉ ở dạng nội dòng, bạn có thể tinh chỉnh `MarkdownSaveOptions` thêm: + +```java +saveOptions.setExportMathAsText(true); // forces inline $…$ only +``` + +## Docx sang markdown latex – Bước 3: Trường hợp góc cạnh & Những cạm bẫy thường gặp + +| Tình huống | Điều cần chú ý | Cách khắc phục | +|-----------|-------------------|-----| +| **Phương trình lồng nhau phức tạp** | Aspose có thể xuất ra các dấu ngoặc nhọn `{}` thừa mà một số trình phân tích xử lý một cách nguyên văn. | Xử lý hậu kỳ Markdown bằng một regex đơn giản để gộp `{{` → `{`. | +| **Thiếu MathJax trên trang đích** | Các công thức hiển thị dưới dạng mã LaTeX thô. | Thêm `` vào mẫu HTML của bạn. | +| **Tài liệu lớn** | Tiêu thụ bộ nhớ tăng đột biến vì toàn bộ tài liệu được tải vào một lần. | Sử dụng `LoadOptions.setLoadFormat(LoadFormat.DOCX)` và cân nhắc xử lý các trang theo lô nếu gặp `OutOfMemoryError`. | +| **Chưa thiết lập giấy phép** | Bạn sẽ nhận được cảnh báo và đầu ra có thể có watermark. | Tải giấy phép sớm trong `main` như đã minh họa trong mẹo Maven ở trên. | + +## Lưu Word thành markdown – Ví dụ Hoạt động Đầy đủ + +Dưới đây là một lớp tự chứa mà bạn có thể sao chép‑dán vào bất kỳ dự án Java nào. Chỉ cần thay thế `YOUR_DIRECTORY` bằng đường dẫn tới các tệp của bạn. + +```java +import com.aspose.words.*; + +public class MathToLatexMarkdown { + public static void main(String[] args) throws Exception { + // Optional: Apply a temporary license if you have one + // License license = new License(); + // license.setLicense("license.xml"); + + // 1️⃣ Load the source .docx + Document doc = new Document("YOUR_DIRECTORY/math.docx"); + + // 2️⃣ Prepare Markdown options with LaTeX export + MarkdownSaveOptions saveOptions = new MarkdownSaveOptions(); + saveOptions.setOfficeMathExportMode( + MarkdownSaveOptions.OfficeMathExportMode.LATEX); + + // 3️⃣ Save as .md – this is the moment we **save word as markdown** + doc.save("YOUR_DIRECTORY/out.md", saveOptions); + + System.out.println("Conversion complete! Check out.md for LaTeX equations."); + } +} +``` + +Chạy chương trình (`java MathToLatexMarkdown`) và bạn sẽ thấy thông báo trên console xác nhận thành công. Mở `out.md` trong bất kỳ trình soạn thảo nào – các công thức sẽ là các đoạn LaTeX sạch sẽ, sẵn sàng để render. + +## Ảnh chụp Đầu ra Dự kiến + +![đầu ra lưu word as markdown với các công thức LaTeX](https://example.com/images/markdown-latex-output.png "đầu ra lưu word as markdown với các công thức LaTeX") + +*Hình ảnh hiển thị một đoạn của Markdown được tạo ra, trong đó công thức `\int_{a}^{b} f(x)\,dx` được bao quanh bởi `$$`.* + +## Kết luận + +Chúng tôi vừa trình diễn cách **save word as markdown** trong khi giữ nguyên mọi công thức Office Math dưới dạng LaTeX gốc. Bước quan trọng là cấu hình `MarkdownSaveOptions` với `OfficeMathExportMode.LATEX`, giúp biến quy trình chuyển đổi Word‑to‑Markdown thông thường thành một công cụ chuyển đổi có khả năng hiểu toán học đầy đủ. + +Bây giờ bạn có thể: + +1. **How to export math** từ bất kỳ tệp `.docx` nào mà không mất độ chính xác. +2. **Convert word equations latex** cho các trình tạo site tĩnh, tài liệu, hoặc blog học thuật. +3. Mở rộng cách tiếp cận để xử lý hàng loạt nhiều tệp, tích hợp vào pipeline CI, hoặc thậm chí xây dựng một dịch vụ web nhỏ. + +Nếu bạn tò mò về bước tiếp theo, hãy thử kết hợp điều này với **docx to markdown latex** cho các tài liệu chứa nhiều hình ảnh, hoặc khám phá `HtmlSaveOptions` của Aspose để có phiên bản HTML sẵn sàng cho web. Các khả năng là vô hạn—hãy thử nghiệm, phá vỡ, và sau đó chia sẻ phát hiện của bạn với cộng đồng. + +Có câu hỏi hoặc công thức khó khăn nào không hiển thị như mong đợi? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +## Các Hướng Dẫn Liên Quan + +- [Cách Xuất LaTeX từ Word: Chuyển DOCX sang Markdown & Lưu dưới dạng PDF](/words/english/java/document-conversion-and-export/how-to-export-latex-from-word-convert-docx-to-markdown-save/) +- [Chuyển docx sang markdown – Xuất Công thức Toán học sang LaTeX với Aspose.Words](/words/english/java/document-conversion-and-export/convert-docx-to-markdown-export-math-equations-to-latex-with/) +- [Cách Chuyển Word sang PDF Sử dụng Aspose.Words cho Java](/words/english/java/document-converting/using-document-converting/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-loading-and-saving/_index.md b/words/vietnamese/java/document-loading-and-saving/_index.md index 77aa00482e..2d75d68eea 100644 --- a/words/vietnamese/java/document-loading-and-saving/_index.md +++ b/words/vietnamese/java/document-loading-and-saving/_index.md @@ -135,6 +135,9 @@ Học cách phát hiện định dạng tài liệu trong Java với Aspose.Word ### [Khôi phục docx bị hỏng – Hướng dẫn toàn diện để sửa và xử lý tài liệu](./recover-corrupted-docx-complete-guide-to-fix-and-process-doc/) +### [Mở Tài Liệu Word Bị Hỏng – Thiết Lập Chế Độ Phục Hồi trong Java](./open-corrupted-word-document-set-recovery-mode-in-java/) +Học cách mở tài liệu Word bị hỏng và thiết lập chế độ phục hồi trong Java bằng Aspose.Words. + ## Câu Hỏi Thường Gặp **Hỏi:** Làm thế nào để **lưu hình ảnh từ Word** một cách lập trình? diff --git a/words/vietnamese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md b/words/vietnamese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md new file mode 100644 index 0000000000..cb972c2ae0 --- /dev/null +++ b/words/vietnamese/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/_index.md @@ -0,0 +1,191 @@ +--- +category: general +date: 2026-05-26 +description: Mở tài liệu Word bị hỏng trong Java bằng Aspose.Words. Tìm hiểu cách + thiết lập chế độ khôi phục và phục hồi các tệp Word bị hỏng một cách đáng tin cậy. +draft: false +keywords: +- open corrupted word document +- set recovery mode +- how to recover corrupted word file +- Aspose.Words Java +- document recovery Java +language: vi +og_description: Mở tài liệu Word bị hỏng trong Java bằng Aspose.Words. Hướng dẫn này + chỉ cách thiết lập chế độ khôi phục và phục hồi các tệp Word bị hỏng một cách hiệu + quả. +og_title: Mở tài liệu Word bị hỏng – Đặt chế độ khôi phục trong Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + headline: Open Corrupted Word Document – Set Recovery Mode in Java + type: TechArticle +- description: Open corrupted word document in Java with Aspose.Words. Learn how to + set recovery mode and recover corrupted Word files reliably. + name: Open Corrupted Word Document – Set Recovery Mode in Java + steps: + - name: Why each line matters + text: '* **`LoadOptions loadOptions = new LoadOptions();`** – without this object + Aspose.Words uses default recovery, which *rejects* corrupted files. Creating + it gives you the hook to change that behavior. * **`setRecoveryMode(...)`** + – this is the **set recovery mode** call that decides whether warnings ' + - name: 1. File Not Found + text: 'If the path is wrong, `Document` throws a `FileNotFoundException`. Wrap + the load in a try‑catch block and log a friendly message:' + - name: 2. Irrecoverable Corruption + text: Even with `RECOVER_WITH_WARNINGS`, some structures are beyond repair. In + that case Aspose.Words still loads what it can, but you’ll see warnings like + “Cannot read paragraph properties”. Pay attention to the console output; those + warnings often point to missing sections that you may need to reconstru + - name: 3. Large Files and Performance + text: Recovery adds a small overhead because the library parses the file twice—once + to detect issues, again to rebuild. For multi‑gigabyte documents, consider streaming + the file or increasing the JVM heap (`-Xmx2g`) to avoid `OutOfMemoryError`. + type: HowTo +tags: +- Aspose.Words +- Java +- Word +title: Mở tài liệu Word bị hỏng – Đặt chế độ khôi phục trong Java +url: /vi/java/document-loading-and-saving/open-corrupted-word-document-set-recovery-mode-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mở Tài Liệu Word Bị Hỏng – Đặt Chế Độ Phục Hồi trong Java + +Bạn đã bao giờ cố gắng mở một tài liệu Word bị hỏng và thấy chương trình gặp lỗi ngoại lệ chưa? Bạn không phải là người duy nhất—những tệp .docx hỏng có thể gây đau đầu thực sự. Tin tốt là Aspose.Words for Java cung cấp cho bạn khả năng kiểm soát chi tiết để bạn có thể **open corrupted word document** mà không làm ứng dụng bị sập, và thậm chí quyết định bạn muốn nhận cảnh báo, phục hồi im lặng, hay từ chối hoàn toàn. + +Trong hướng dẫn này, chúng ta sẽ đi qua toàn bộ quy trình: từ việc tạo `LoadOptions` phù hợp, đến việc chọn giá trị **set recovery mode** thích hợp, và cuối cùng xác nhận tài liệu đã được tải thành công. Khi kết thúc, bạn sẽ biết **how to recover corrupted word file** một cách lập trình, không cần sao chép‑dán thủ công. + +> **Bạn sẽ cần** +> * Java 8 hoặc mới hơn (API cũng hoạt động với Java 11) +> * Aspose.Words for Java 23.9 (hoặc phiên bản mới nhất) +> * Một tệp .docx bị hỏng mẫu — chỉ cần đổi tên bất kỳ tệp hợp lệ nào để mô phỏng hỏng nếu bạn không có sẵn + +Hãy bắt đầu. + +## Open Corrupted Word Document – Tổng Quan Các Bước + +Dưới đây là luồng công việc cấp cao mà chúng ta sẽ thực hiện: + +1. **Create `LoadOptions`** – đối tượng này cho Aspose.Words biết cách hành xử khi gặp sự cố. +2. **Set recovery mode** – chọn `RECOVER_WITH_WARNINGS`, `RECOVER_WITHOUT_WARNINGS`, hoặc `REJECT_CORRUPTED`. +3. **Load the document** bằng các tùy chọn đã cấu hình. +4. **Verify** việc tải thành công (ví dụ, in số trang). + +Mỗi bước sẽ được giải thích chi tiết, kèm theo các đoạn mã bạn có thể sao chép‑dán trực tiếp vào IDE. + +## Set Recovery Mode cho Các Kịch Bản Khác Nhau + +Aspose.Words định nghĩa ba chiến lược phục hồi trong `LoadOptions.RecoveryMode`: + +| Mode | Behaviour | When to use | +|------|-----------|-------------| +| `RECOVER_WITH_WARNINGS` | Cố gắng tải tài liệu, nhưng đưa ra bất kỳ vấn đề nào dưới dạng cảnh báo trong console. | Bạn muốn xem *điều gì* đã sai mà không dừng quá trình. | +| `RECOVER_WITHOUT_WARNINGS` | Im lặng sửa những gì có thể và ẩn các cảnh báo. | Môi trường production nơi log cần sạch sẽ. | +| `REJECT_CORRUPTED` | Ném ngoại lệ ngay khi phát hiện hỏng. | Các pipeline kiểm tra nghiêm ngặt cần thất bại nhanh. | + +Việc chọn chế độ phù hợp là cốt lõi của **set recovery mode** đúng cách. Trong hầu hết các buổi debug, `RECOVER_WITH_WARNINGS` là lựa chọn tốt nhất vì nó cho bạn biết chính xác phần nào đã được sửa. + +## Cách Phục Hồi Tệp Word Bị Hỏng Sử Dụng Aspose.Words + +Dưới đây là một **chương trình Java đầy đủ, có thể chạy** minh họa toàn bộ quy trình. Bạn chỉ cần đặt nó vào tệp `RecoveryModeDemo.java`, điều chỉnh đường dẫn, và chạy. + +```java +import com.aspose.words.*; + +public class RecoveryModeDemo { + public static void main(String[] args) throws Exception { + // ------------------------------------------------- + // Step 1: Prepare LoadOptions – this controls recovery + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions(); + + // ------------------------------------------------- + // Step 2: Choose the recovery behavior + // ------------------------------------------------- + // Option A – show warnings (great for debugging) + loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITH_WARNINGS); + + // Uncomment ONE of the alternatives below if you need a different behavior: + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.RECOVER_WITHOUT_WARNINGS); + // loadOptions.setRecoveryMode(LoadOptions.RecoveryMode.REJECT_CORRUPTED); + + // ------------------------------------------------- + // Step 3: Load the potentially corrupted document + // ------------------------------------------------- + // Replace the placeholder with the actual path to your .docx file + String corruptedPath = "C:/temp/corrupted.docx"; + Document doc = new Document(corruptedPath, loadOptions); + + // ------------------------------------------------- + // Step 4: Verify that the document is usable + // ------------------------------------------------- + System.out.println("Document loaded successfully!"); + System.out.println("Page count = " + doc.getPageCount()); + + // Bonus: you can now save the repaired file if you wish + doc.save("C:/temp/recovered.docx"); + System.out.println("Recovered file saved as recovered.docx"); + } +} +``` + +### Tại sao mỗi dòng lại quan trọng + +* **`LoadOptions loadOptions = new LoadOptions();`** – nếu không có đối tượng này, Aspose.Words sẽ dùng chế độ phục hồi mặc định, tức là *từ chối* các tệp bị hỏng. Tạo nó cho phép bạn thay đổi hành vi đó. +* **`setRecoveryMode(...)`** – đây là lời gọi **set recovery mode** quyết định liệu cảnh báo có xuất hiện, ẩn đi, hay gây ra ngoại lệ. +* **`new Document(path, loadOptions);`** – hàm khởi tạo nhận `LoadOptions` mà chúng ta vừa cấu hình, vì vậy thư viện biết cách xử lý tệp hỏng ngay từ đầu. +* **`doc.getPageCount()`** – kiểm tra nhanh tính hợp lệ. Nếu tài liệu tải và trả về số trang, bạn đã **how to recover corrupted word file** thành công. +* **`doc.save(...)`** – tùy chọn nhưng hữu ích; bạn có thể ghi lại phiên bản đã được sửa lại lên đĩa để dùng sau. + +## Xử Lý Các Trường Hợp Đặc Biệt Thường Gặp + +### 1. File Not Found + +Nếu đường dẫn sai, `Document` sẽ ném `FileNotFoundException`. Bao bọc việc tải trong khối try‑catch và ghi lại thông báo thân thiện: + +```java +try { + Document doc = new Document(corruptedPath, loadOptions); + // proceed... +} catch (FileNotFoundException e) { + System.err.println("The file was not found: " + corruptedPath); +} +``` + +### 2. Corruption Không Thể Phục Hồi + +Ngay cả khi dùng `RECOVER_WITH_WARNINGS`, một số cấu trúc vẫn có thể vượt quá khả năng sửa chữa. Trong trường hợp đó Aspose.Words vẫn sẽ tải những phần có thể, nhưng bạn sẽ thấy các cảnh báo như “Cannot read paragraph properties”. Hãy chú ý tới output console; những cảnh báo này thường chỉ ra các phần thiếu mà bạn có thể cần tái tạo thủ công. + +### 3. Tệp Lớn và Hiệu Suất + +Quá trình phục hồi thêm một chút overhead vì thư viện phải phân tích tệp hai lần — một lần để phát hiện vấn đề, lần nữa để tái xây dựng. Đối với các tài liệu đa gigabyte, hãy cân nhắc streaming tệp hoặc tăng heap JVM (`-Xmx2g`) để tránh `OutOfMemoryError`. + +## Pro Tips – Tăng Cường Độ Bền Khi Phục Hồi + +* **Log warnings vào file** – chuyển hướng `System.err` tới một logger để bạn có bản ghi audit về những gì đã được sửa. +* **Validate sau khi phục hồi** – chạy `doc.updatePageLayout();` rồi kiểm tra lại số trang; đôi khi bố cục thay đổi sau khi sửa các phần bị hỏng. +* **Tự động phục hồi hàng loạt** – bao bọc demo trong một vòng lặp xử lý một thư mục các tệp bị hỏng, sử dụng cùng một `LoadOptions` mỗi lần. + +## Kết Luận + +Bây giờ bạn đã biết chính xác **how to recover corrupted word file** bằng Aspose.Words for Java. Bằng cách tạo một thể hiện `LoadOptions`, **set recovery mode** theo chiến lược phù hợp với kịch bản của bạn, và tải tài liệu với các tùy chọn đó, bạn có thể an toàn **open corrupted word document** mà không làm ứng dụng của mình bị sập. Mã mẫu ở trên là một giải pháp hoàn chỉnh, sẵn sàng chạy, in ra số trang và thậm chí lưu một bản sao đã được làm sạch. + +Tiếp theo bạn muốn làm gì? Hãy thử chuyển chế độ phục hồi sang `RECOVER_WITHOUT_WARNINGS` và so sánh output console, hoặc thử tải các tài liệu được mã hoá (bạn sẽ cần cung cấp mật khẩu qua + +## Related Tutorials + +- [Aspose.Words Java: Comprehensive Guide to Word Document Processing](/words/english/java/document-operations/aspose-words-java-master-word-processing/) +- [How to Convert Word to PDF Using Aspose.Words for Java](/words/english/java/document-converting/using-document-converting/) +- [How to Compare Two Word Files with Aspose.Words for Java](/words/english/java/document-manipulation/comparing-documents/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/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/java/document-styling/_index.md b/words/vietnamese/java/document-styling/_index.md index e77531e3e0..d7293731f9 100644 --- a/words/vietnamese/java/document-styling/_index.md +++ b/words/vietnamese/java/document-styling/_index.md @@ -42,7 +42,9 @@ Tìm hiểu cách tùy chỉnh chủ đề tài liệu bằng Aspose.Words for J ### [Đóng dấu bản quyền tài liệu và thiết lập trang](./document-watermarking-page-setup/) Tìm hiểu cách áp dụng hình mờ và thiết lập cấu hình trang bằng Aspose.Words cho Java. Hướng dẫn toàn diện với mã nguồn. ### [Kiểu dáng của Đầu trang và Chân trang Tài liệu](./document-header-footer-styling/) -Tìm hiểu cách định dạng tiêu đề và chân trang tài liệu bằng Aspose.Words for Java trong hướng dẫn chi tiết này. Bao gồm hướng dẫn từng bước và mã nguồn. +Tìm hiểu cách định dạng tiêu đề và chân trang tài liệu bằng Aspose.Words cho Java trong hướng dẫn chi tiết này. Bao gồm hướng dẫn từng bước và mã nguồn. +### [Cài đặt Phông chữ Mặc định trong Aspose.Words cho Java – Hướng dẫn đầy đủ](./set-default-font-settings-in-aspose-words-for-java-complete/) +Tìm hiểu cách thiết lập phông chữ mặc định cho tài liệu bằng Aspose.Words cho Java. Hướng dẫn chi tiết kèm ví dụ mã nguồn. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md b/words/vietnamese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md new file mode 100644 index 0000000000..a855ed02c0 --- /dev/null +++ b/words/vietnamese/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/_index.md @@ -0,0 +1,236 @@ +--- +category: general +date: 2026-05-26 +description: Đặt cài đặt phông chữ mặc định trong Aspose.Words cho Java và tìm hiểu + cách thiết lập cài đặt phông chữ cũng như phát hiện các phông chữ thiếu chỉ trong + vài dòng mã. +draft: false +keywords: +- set default font settings +- set font settings +- detect missing fonts +language: vi +og_description: Đặt cài đặt phông chữ mặc định trong Aspose.Words cho Java, học cách + thiết lập cài đặt phông chữ và phát hiện phông chữ thiếu nhanh chóng và đáng tin + cậy. +og_title: Đặt Cài Đặt Phông Chữ Mặc Định trong Aspose.Words cho Java +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + headline: Set Default Font Settings in Aspose.Words for Java – Complete Guide + type: TechArticle +- description: Set default font settings in Aspose.Words for Java and learn how to + set font settings and detect missing fonts in just a few lines of code. + name: Set Default Font Settings in Aspose.Words for Java – Complete Guide + steps: + - name: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + text: '**Aspose.Words for Java** (version 23.10 or newer) on your classpath.' + - name: A Java 17 (or later) development kit – any modern JDK works. + text: A Java 17 (or later) development kit – any modern JDK works. + - name: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + text: A DOCX file that intentionally uses a font you don't have installed (e.g., + *“MissingFont.ttf”*). + type: HowTo +tags: +- Aspose.Words +- Java +- Font Management +title: Cài đặt phông chữ mặc định trong Aspose.Words cho Java – Hướng dẫn đầy đủ +url: /vi/java/document-styling/set-default-font-settings-in-aspose-words-for-java-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Đặt Cài Đặt Phông Mặc Định trong Aspose.Words cho Java – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi cách **đặt cài đặt phông mặc định** khi tải một tài liệu Word bằng Aspose.Words cho Java chưa? Bạn không phải là người duy nhất. Các glyph bị thiếu có thể biến một báo cáo hoàn hảo thành một mớ hỗn độn, và việc bắt các cảnh báo thay thế phông sớm sẽ tiết kiệm hàng giờ gỡ lỗi. + +Trong hướng dẫn này, chúng tôi sẽ đi qua một ví dụ ngắn gọn, toàn diện mà **đặt cài đặt phông mặc định**, chỉ cho bạn cách **đặt cài đặt phông** một cách lập trình, và trình bày một cách đáng tin cậy để **phát hiện phông bị thiếu** trước khi chúng làm hỏng bố cục của bạn. + +--- + +## Những Điều Bạn Sẽ Học + +- Cách tạo một đối tượng `LoadOptions` với một thể hiện `FontSettings` mới. +- Cách gắn một listener cảnh báo sẽ **phát hiện phông bị thiếu** trong quá trình tải tài liệu. +- Cách tải một tệp DOCX trong khi listener âm thầm báo cáo mọi sự thay thế. +- Mẹo tùy chỉnh phông dự phòng và xử lý các trường hợp đặc biệt trong môi trường sản xuất. + +Không cần thư viện bổ sung, không có tệp cấu hình khó hiểu—chỉ cần Java thuần và Aspose.Words. + +--- + +## Yêu Cầu Trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +1. **Aspose.Words cho Java** (phiên bản 23.10 trở lên) trên classpath của bạn. +2. Bộ công cụ phát triển Java 17 (hoặc mới hơn) – bất kỳ JDK hiện đại nào cũng hoạt động. +3. Một tệp DOCX cố ý sử dụng một phông chữ mà bạn chưa cài đặt (ví dụ, *“MissingFont.ttf”*). + +Nếu bạn thiếu JAR Aspose, hãy tải nó từ kho Maven chính thức: + +```xml + + com.aspose + aspose-words + 23.10 + +``` + +Xong—không cần cài đặt phông bổ sung nào cho bản demo này. + +--- + +## Bước 1: Tạo LoadOptions và **Đặt Cài Đặt Phông Mặc Định** + +Điều đầu tiên chúng ta cần là một đối tượng `LoadOptions` sạch sẽ, cho Aspose biết cách hành xử khi gặp các kiểu chữ không xác định. Bằng cách gọi `setFontSettings(new FontSettings())` chúng ta **đặt cài đặt phông mặc định** với danh sách dự phòng rỗng. + +```java +import com.aspose.words.*; + +public class FontSubstitutionDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create load options with default font settings. + LoadOptions loadOptions = new LoadOptions(); + // This line **sets default font settings** – a blank slate for us. + loadOptions.setFontSettings(new FontSettings()); +``` + +> **Tại sao điều này quan trọng:** +> Khi bạn không cấu hình phông một cách rõ ràng, Aspose sẽ dựa vào bộ sưu tập phông mặc định của hệ thống, điều này có thể che giấu các vấn đề phông bị thiếu. Bằng cách bắt đầu từ một thể hiện `FontSettings` mới, bạn có toàn quyền kiểm soát các phông được coi là hợp lệ. + +--- + +## Bước 2: Gắn Listener Cảnh Báo để **Phát Hiện Phông Bị Thiếu** + +Aspose tạo ra một đối tượng `WarningInfo` cho mỗi lần thay thế nó thực hiện. Bằng cách lắng nghe `WarningType.FONT_SUBSTITUTION` chúng ta có thể **phát hiện phông bị thiếu** ngay khi tài liệu được phân tích. + +```java + // Step 2: Attach a warning listener to capture font‑substitution warnings. + loadOptions.getWarnings().addWarningListener(warningInfo -> { + if (warningInfo.getWarningType() == WarningType.FONT_SUBSTITUTION) { + System.out.println("Font substitution: " + warningInfo.getDescription()); + } + }); +``` + +> **Mẹo chuyên nghiệp:** Listener chạy trên cùng một luồng tải tài liệu, vì vậy gần như không gây ảnh hưởng đến hiệu năng. Nếu bạn cần thu thập các cảnh báo để phân tích sau, hãy đưa chúng vào một `List` thay vì in trực tiếp. + +--- + +## Bước 3: Tải Tài Liệu Sử Dụng Các Tùy Chọn Đã Cấu Hình + +Bây giờ chúng ta đã **đặt cài đặt phông** và chuẩn bị listener, chúng ta chỉ cần tải tệp. Bất kỳ phông nào bị thiếu sẽ kích hoạt callback ngay lập tức. + +```java + // Step 3: Load the document using the configured load options. + Document doc = new Document("YOUR_DIRECTORY/doc-with-missing-font.docx", loadOptions); +``` + +Nếu tệp nguồn tham chiếu một phông không được cài đặt, bạn sẽ thấy đầu ra tương tự như: + +``` +Font substitution: Font 'Comic Sans MS' was not found. Substituted with 'Arial'. +``` + +Dòng đó cho bạn biết chính xác phông nào bị thiếu và phông dự phòng nào đã được sử dụng—hoàn hảo cho việc ghi log hoặc phản hồi người dùng. + +--- + +## Bước 4: Tiếp Tục Xử Lý Bình Thường (Tùy Chọn) + +Ở thời điểm này tài liệu đã được tải đầy đủ, và bạn có thể tiếp tục bất kỳ thao tác nào bạn muốn—chỉnh sửa, chuyển đổi sang PDF, hoặc trích xuất văn bản. Listener cảnh báo đã hoàn thành nhiệm vụ, vì vậy bạn không cần kiểm tra thêm. + +```java + // Normal processing can continue here; the listener already reported any substitutions. + // Example: save as PDF + doc.save("output.pdf"); + } +} +``` + +> **Nếu bạn muốn một phông dự phòng tùy chỉnh?** +> Thay vì để `FontSettings` trống, bạn có thể thêm các phông cụ thể: + +```java +FontSettings fs = new FontSettings(); +fs.setSubstitutionSettings(new FontSubstitutionSettings()); +fs.getSubstitutionSettings().getDefaultFontSubstitution().setDefaultFontName("Times New Roman"); +loadOptions.setFontSettings(fs); +``` + +Bây giờ bất kỳ kiểu chữ nào bị thiếu sẽ được thay thế bằng *Times New Roman*—một lựa chọn đáng tin cậy cho hầu hết các tài liệu phương Tây. + +--- + +## Tổng Quan Trực Quan + +![Sơ đồ cho thấy cách đặt cài đặt phông mặc định trong Aspose.Words cho Java](image.png "Sơ đồ luồng đặt cài đặt phông mặc định") + +*Văn bản thay thế: sơ đồ luồng đặt cài đặt phông mặc định trong Aspose.Words cho Java.* + +Sơ đồ minh họa luồng từ việc khởi tạo `LoadOptions` (nơi chúng ta **đặt cài đặt phông mặc định**) đến việc gắn listener cảnh báo (để **phát hiện phông bị thiếu**) và cuối cùng là tải tài liệu. + +--- + +## Những Sai Lầm Thường Gặp & Cách Tránh + +| Pitfall | Why It Happens | Fix | +|---------|----------------|-----| +| **Forgot to call `setFontSettings`** | Aspose sử dụng các mặc định của hệ thống, làm ẩn các phông bị thiếu. | Luôn tạo một thể hiện `FontSettings` mới và gán nó cho `LoadOptions`. | +| **Listener not triggered** | Listener được thêm sau khi tài liệu đã được tải. | Thêm listener cảnh báo *trước* khi gọi `new Document(...)`. | +| **Path typo leads to `FileNotFoundException`** | Đường dẫn được mã hóa cứng không khớp với độ nhạy chữ hoa/thường của hệ điều hành. | Sử dụng `Paths.get("...").toAbsolutePath()` hoặc cấu hình đường dẫn tương đối từ thư mục gốc của dự án. | +| **Multiple missing fonts overwhelm logs** | Các tài liệu lớn có thể tạo ra hàng chục cảnh báo. | Lọc các bản sao hoặc tổng hợp các thông điệp trong một `Set` trước khi in. | + +--- + +## Mở Rộng Giải Pháp + +Nếu bạn cần **đặt cài đặt phông** cho toàn bộ ứng dụng, hãy xem xét tạo một `FontSettings` singleton và tái sử dụng nó cho mọi `LoadOptions`. Như vậy bạn duy trì một chiến lược dự phòng nhất quán và tránh việc tạo đối tượng lặp lại. + +```java +public class FontConfig { + private static final FontSettings sharedSettings = createSettings(); + + private static FontSettings createSettings() { + FontSettings fs = new FontSettings(); + // Add custom fallback fonts here + return fs; + } + + public static LoadOptions getLoadOptions() { + LoadOptions lo = new LoadOptions(); + lo.setFontSettings(sharedSettings); + return lo; + } +} +``` + +Bây giờ bất kỳ phần nào trong codebase của bạn cũng có thể gọi đơn giản `FontConfig.getLoadOptions()` và ngay lập tức hưởng lợi từ logic **đặt cài đặt phông mặc định** giống nhau. + +--- + +## Kết Luận + +Chúng tôi vừa trình bày mọi thứ bạn cần để **đặt cài đặt phông mặc định** trong Aspose.Words cho Java, **đặt cài đặt phông** một cách lập trình, và **phát hiện phông bị thiếu** trước khi chúng làm hỏng kết quả của bạn. Ví dụ đầy đủ, có thể chạy được nằm trong các đoạn mã phía trên, và bạn có thể dán trực tiếp vào IDE để thấy các cảnh báo hoạt động. + +Bước tiếp theo? Hãy thử thay đổi phông dự phòng, thử nghiệm với các định dạng tài liệu khác nhau (DOC, RTF, HTML), hoặc tích hợp bộ thu thập cảnh báo vào bảng điều khiển giám sát. Bạn càng làm quen với `FontSettings`, bạn càng tự tin rằng các tài liệu được tạo ra sẽ hiển thị chính xác như mong muốn—không có bất ngờ, không có glyph bị hỏng. + +Có câu hỏi hoặc tình huống thay thế phông khó khăn? Hãy để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +## Các Bài Hướng Dẫn Liên Quan + +- [Cài Đặt Phông Dự Phòng](/words/english/net/working-with-fonts/set-font-fallback-settings/) +- [Cài Đặt Phông Dự Phòng](/words/chinese/net/working-with-fonts/set-font-fallback-settings/) +- [Cài Đặt Phông Dự Phòng](/words/arabic/net/working-with-fonts/set-font-fallback-settings/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/java/images-shapes/_index.md b/words/vietnamese/java/images-shapes/_index.md index dda81d5c1a..802dbd48a0 100644 --- a/words/vietnamese/java/images-shapes/_index.md +++ b/words/vietnamese/java/images-shapes/_index.md @@ -37,6 +37,9 @@ Tìm hiểu cách tạo hình thu nhỏ chất lượng cao và bitmap tùy ch ### [Tạo tài liệu Word bằng Java – Thêm hình chữ nhật với hiệu ứng bóng](./create-word-document-java-add-rectangle-shape-with-shadow-ef/) Hướng dẫn cách chèn hình chữ nhật có bóng vào tài liệu Word bằng Aspose.Words cho Java. +### [Tạo hình chữ nhật trong tài liệu Word Java – Hướng dẫn chi tiết từng bước](./create-rectangle-shape-in-java-word-document-full-step-by-st/) +Hướng dẫn chi tiết cách tạo hình chữ nhật trong tài liệu Word bằng Aspose.Words cho Java. + ## Tài nguyên bổ sung - [Tài liệu Aspose.Words cho Java](https://reference.aspose.com/words/java/) diff --git a/words/vietnamese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md b/words/vietnamese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md new file mode 100644 index 0000000000..9f08ce01d3 --- /dev/null +++ b/words/vietnamese/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/_index.md @@ -0,0 +1,259 @@ +--- +category: general +date: 2026-05-26 +description: Tạo hình chữ nhật trong tài liệu Word bằng Java và áp dụng hiệu ứng đổ + bóng. Tìm hiểu cách thêm bóng cho hình, đặt khoảng cách bóng và lưu tệp. +draft: false +keywords: +- create rectangle shape +- apply shadow effect +- create word document java +- add shape shadow +- set shadow distance +language: vi +og_description: Tạo hình chữ nhật trong tài liệu Word bằng Java, áp dụng hiệu ứng + bóng, thêm bóng cho hình và đặt khoảng cách bóng bằng Aspose.Words. +og_title: Tạo hình chữ nhật trong tài liệu Word bằng Java – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-05-26' + description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + headline: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + type: TechArticle +- description: Create rectangle shape in a Java Word document and apply shadow effect. + Learn how to add shape shadow, set shadow distance, and save the file. + name: Create Rectangle Shape in Java Word Document – Full Step‑by‑Step Guide + steps: + - name: “Can I use a different shape?” + text: Absolutely. Replace `ShapeType.RECTANGLE` with `ShapeType.OVAL`, `ShapeType.LINE`, + or any other supported enum. The rest of the shadow code stays the same. + - name: “What if I need multiple shadows?” + text: Aspose.Words only supports a single shadow per shape. To simulate multiple + shadows, duplicate the shape, offset each copy, and adjust the transparency. + - name: “Is the shadow visible in LibreOffice?” + text: Yes—Aspose.Words writes standard OOXML, which LibreOffice interprets correctly. + The shadow may look slightly different due to rendering engines, but the effect + persists. + - name: “How do I change the shadow color to match my brand?” + text: Just swap `java.awt.Color.GRAY` with any `java.awt.Color` you prefer, such + as `new java.awt.Color(0, 120, 215)` for a corporate blue. + type: HowTo +tags: +- Java +- Aspose.Words +- Word Automation +title: Tạo hình chữ nhật trong tài liệu Word bằng Java – Hướng dẫn chi tiết từng bước +url: /vi/java/images-shapes/create-rectangle-shape-in-java-word-document-full-step-by-st/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo hình chữ nhật trong tài liệu Word Java – Hướng dẫn chi tiết từng bước + +Bạn đã bao giờ cần **create rectangle shape** trong một tài liệu Word Java nhưng không biết bắt đầu từ đâu? Bạn không phải là người duy nhất—nhiều nhà phát triển gặp khó khăn này khi tạo báo cáo hoặc hoá đơn một cách tự động. Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách **create rectangle shape**, áp dụng một bóng đổ mịn, và tinh chỉnh khoảng cách bóng sao cho kết quả trông chuyên nghiệp. + +Chúng ta sẽ sử dụng Aspose.Words for Java, một thư viện mạnh mẽ cho phép bạn thao tác các tệp Word mà không cần cài đặt Microsoft Office. Khi kết thúc hướng dẫn này, bạn sẽ có thể tạo các dự án **create word document java** có khả năng **add shape shadow**, **apply shadow effect**, và **set shadow distance** chỉ với vài dòng mã. + +--- + +## Những gì bạn sẽ xây dựng + +- Một tệp `.docx` mới chứa một hình chữ nhật màu xanh lơ. +- Một bóng đổ thực tế, mờ, có góc và bán trong suốt. +- Kiểm soát đầy đủ khoảng cách bóng so với hình. +- Một lớp Java sẵn sàng chạy mà bạn có thể đưa vào bất kỳ dự án Maven hoặc Gradle nào. + +Không cần công cụ bên ngoài, không có bước UI thủ công—chỉ cần mã thuần. + +--- + +## Yêu cầu trước + +- Java 8 hoặc mới hơn (mã hoạt động trên Java 11, Java 17, v.v.). +- Thư viện Aspose.Words for Java (có sẵn qua Maven Central). +- Một IDE hoặc trình soạn thảo văn bản bạn thích (IntelliJ IDEA, Eclipse, VS Code…). +- Kiến thức cơ bản về cú pháp Java. + +Nếu bạn chưa từng thêm phụ thuộc Maven, đây là đoạn mã nhanh: + +```xml + + com.aspose + aspose-words + 24.10 + +``` + +Bây giờ, chúng ta cùng bắt đầu. + +--- + +## Bước 1: Tạo hình chữ nhật trong tài liệu Word + +Điều đầu tiên chúng ta cần là một tài liệu trống và một `DocumentBuilder`. Hãy nghĩ về builder như một cây bút viết vào tài liệu. Khi đã có, chúng ta có thể **create rectangle shape** chỉ bằng một lời gọi phương thức. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Initialize a new empty document. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Insert a rectangle shape of 150x80 points. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Make the shape visible by filling it with cyan. + rectangleShape.setFillColor(java.awt.Color.CYAN); +``` + +> **Tại sao điều này quan trọng:** Phương thức `insertShape` không chỉ tạo hình học mà còn thêm hình vào bộ sưu tập nội bộ của tài liệu, vì vậy bạn có thể ngay lập tức bắt đầu định dạng nó. + +--- + +## Bước 2: Áp dụng hiệu ứng bóng cho hình + +Bây giờ hình chữ nhật đã có trên trang, chúng ta sẽ **apply shadow effect**. Bóng đổ tạo độ sâu, khiến hình cảm giác như được nâng lên khỏi trang—một cải tiến UI tinh tế có thể tăng khả năng đọc trong báo cáo. + +```java + // Retrieve the shadow format object. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + + // Enable the shadow and configure its appearance. + shadowFormat.setVisible(true); // Turn the shadow on. + shadowFormat.setBlur(5.0); // Soft blur radius. + shadowFormat.setAngle(45.0); // Direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Shadow color. + shadowFormat.setTransparency(0.3); // 30% transparent. +``` + +> **Mẹo chuyên nghiệp:** Độ mờ `5.0` trông tự nhiên cho hầu hết các tài liệu hiển thị trên màn hình. Nếu bạn in, có thể muốn giảm giá trị một chút để tránh hiện tượng mờ nhạt. + +--- + +## Bước 3: Đặt khoảng cách bóng – Tinh chỉnh vị trí + +Bóng không chỉ liên quan đến độ mờ; chúng còn cần độ dịch chuyển phù hợp. Đây là nơi chúng ta **set shadow distance**. Khoảng cách `7.0` điểm tạo ra một độ dịch chuyển vừa phải, đủ để nhận thấy nhưng không quá mạnh. + +```java + // Define how far the shadow sits from the shape. + shadowFormat.setDistance(7.0); // Distance in points. +``` + +> **Nếu bạn cần độ dịch chuyển lớn hơn?** Tăng giá trị; giảm nó để có vẻ gọn hơn. Hãy nhớ, khoảng cách hoạt động cùng với góc để định vị bóng đúng cách. + +--- + +## Bước 4: Lưu tài liệu – Lưu lại công việc của bạn + +Cuối cùng, chúng ta ghi tài liệu ra đĩa. Thay đổi đường dẫn tới vị trí bạn muốn lưu tệp. + +```java + // Save the document with the rectangle and its shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +Chạy lớp sẽ tạo ra một tệp `shadow.docx` mà khi mở trong Microsoft Word hoặc LibreOffice, sẽ hiển thị một hình chữ nhật màu xanh lơ với bóng xám mềm, góc 45° và dịch chuyển 7 điểm. + +--- + +## Ví dụ làm việc đầy đủ + +Dưới đây là mã hoàn chỉnh, sẵn sàng sao chép‑dán. Nó bao gồm tất cả các import, chú thích và lời gọi `save` cuối cùng. + +```java +import com.aspose.words.*; + +public class ShadowEffectDemo { + public static void main(String[] args) throws Exception { + // Step 1: Create a new blank document and a DocumentBuilder. + Document doc = new Document(); + DocumentBuilder builder = new DocumentBuilder(doc); + + // Step 2: Insert a rectangle shape of the desired size. + Shape rectangleShape = builder.insertShape(ShapeType.RECTANGLE, 150, 80); + // Step 3: Apply a fill color to make the shape visible. + rectangleShape.setFillColor(java.awt.Color.CYAN); + + // Step 4: Configure the shape's shadow effect. + ShadowFormat shadowFormat = rectangleShape.getShadowFormat(); + shadowFormat.setVisible(true); // Enable the shadow. + shadowFormat.setBlur(5.0); // Set the blur radius. + shadowFormat.setDistance(7.0); // Define how far the shadow is from the shape. + shadowFormat.setAngle(45.0); // Set the direction of the shadow. + shadowFormat.setColor(java.awt.Color.GRAY); // Choose the shadow color. + shadowFormat.setTransparency(0.3); // Make the shadow partially transparent. + + // Step 5: Save the document with the shaped shadow. + doc.save("YOUR_DIRECTORY/shadow.docx"); + } +} +``` + +**Kết quả mong đợi:** Mở `shadow.docx` → bạn sẽ thấy một hình chữ nhật màu xanh lơ nằm ở trung tâm trang đầu, tạo ra một bóng xám nhẹ nhàng hơi dịch chuyển về phía dưới‑phải. Độ mờ và độ trong suốt của bóng làm cho nó trông như ánh sáng tự nhiên. + +--- + +## Câu hỏi thường gặp & Các trường hợp đặc biệt + +### “Tôi có thể dùng hình dạng khác không?” + +Chắc chắn. Thay `ShapeType.RECTANGLE` bằng `ShapeType.OVAL`, `ShapeType.LINE`, hoặc bất kỳ enum nào khác được hỗ trợ. Phần còn lại của mã bóng vẫn giữ nguyên. + +### “Nếu tôi cần nhiều bóng?” + +Aspose.Words chỉ hỗ trợ một bóng cho mỗi hình. Để mô phỏng nhiều bóng, sao chép hình, dịch chuyển mỗi bản sao và điều chỉnh độ trong suốt. + +### “Bóng có hiển thị trong LibreOffice không?” + +Có—Aspose.Words ghi chuẩn OOXML, LibreOffice sẽ diễn giải đúng. Bóng có thể trông hơi khác do các engine render, nhưng hiệu ứng vẫn tồn tại. + +### “Làm sao thay đổi màu bóng để phù hợp với thương hiệu của tôi?” + +Chỉ cần thay `java.awt.Color.GRAY` bằng bất kỳ `java.awt.Color` nào bạn muốn, chẳng hạn `new java.awt.Color(0, 120, 215)` cho màu xanh doanh nghiệp. + +--- + +## Minh hoạ hình ảnh + +![tạo hình chữ nhật trong tài liệu Word Java](https://example.com/images/rectangle-shadow.png) + +*Alt text:* **create rectangle shape** minh họa cho một hình chữ nhật màu xanh lơ với bóng đổ màu xám trong tài liệu Word. + +--- + +## Tóm tắt & Các bước tiếp theo + +Chúng tôi đã trình bày cách **create rectangle shape**, **apply shadow effect**, **add shape shadow**, và **set shadow distance** bằng Aspose.Words for Java. Mã độc lập, chạy trên bất kỳ JDK hiện đại nào, và tạo ra một tệp `.docx` được hoàn thiện, sẵn sàng phân phối. + +Muốn tiến xa hơn? Hãy thử: + +- Thêm văn bản vào bên trong hình chữ nhật bằng `builder.moveTo(rectangleShape.getAbsolutePosition())`. +- Tạo một bảng các hình để xây dựng sơ đồ. +- Xuất tài liệu ra PDF (`doc.save("output.pdf", SaveFormat.PDF);`). + +--- + +## Suy nghĩ cuối cùng + +Việc thành thạo các nhiệm vụ **create word document java** như tạo hình và tạo bóng giúp bạn có lợi thế lớn khi tự động hoá báo cáo, hợp đồng, hoặc tài liệu marketing. Cách tiếp cận ở đây sạch sẽ, dễ bảo trì, và—quan trọng nhất—dễ điều chỉnh cho bất kỳ phong cách trực quan nào bạn cần. + +Hãy chạy thử mã, điều chỉnh độ mờ, góc và khoảng cách, và xem tài liệu của bạn biến đổi từ nhàm chán thành tinh tế. Nếu gặp khó khăn, hãy để lại bình luận bên dưới; tôi sẵn sàng giúp đỡ. + +Chúc lập trình vui vẻ! + +## Các hướng dẫn liên quan + +- [Tạo tài liệu Word Java – Thêm hình chữ nhật với hiệu ứng bóng](/words/english/java/images-shapes/create-word-document-java-add-rectangle-shape-with-shadow-ef/) +- [Cách tạo trường biểu mẫu và thêm nội dung bằng DocumentBuilder trong Aspose.Words for Java](/words/english/java/document-manipulation/adding-content-using-documentbuilder/) +- [Tạo PDF từ Word với tạo mã vạch – Aspose.Words for Java](/words/english/java/document-conversion-and-export/using-barcode-generation/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file