From 635c33ebcda85f759988b2121321e11f85e37da4 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Mon, 6 Apr 2026 01:55:13 +0000 Subject: [PATCH] Add 5 words net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: basic-conversions, programming-with-markdownsaveoptions, programming-with-txtsaveoptions, working-with-fonts Source: AI Search API Tutorials: - save docx as txt – Export Word equations to LaTeX with C# - Aspose Font Substitution – Detect Missing Fonts in Word Documents - Convert DOCX to Markdown – Extract Images from DOCX with Aspose.Words - Convert Word to PDF in C# – Full Guide with Aspose.Words - Convert Word to Markdown – Full Guide with PDF/UA Export Auto-generated by Professionalize.Tutorials Agent --- words/arabic/net/basic-conversions/_index.md | 1 + .../_index.md | 198 +++++++++++ .../_index.md | 4 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 212 ++++++++++++ words/arabic/net/working-with-fonts/_index.md | 1 + .../_index.md | 215 ++++++++++++ words/chinese/net/basic-conversions/_index.md | 1 + .../_index.md | 194 +++++++++++ .../_index.md | 5 + .../_index.md | 313 +++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 211 ++++++++++++ .../chinese/net/working-with-fonts/_index.md | 2 +- .../_index.md | 213 ++++++++++++ words/czech/net/basic-conversions/_index.md | 5 +- .../_index.md | 198 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/czech/net/working-with-fonts/_index.md | 3 +- .../_index.md | 217 ++++++++++++ words/dutch/net/basic-conversions/_index.md | 1 + .../_index.md | 207 ++++++++++++ .../_index.md | 8 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/dutch/net/working-with-fonts/_index.md | 2 +- .../_index.md | 217 ++++++++++++ words/english/net/basic-conversions/_index.md | 1 + .../_index.md | 206 ++++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 3 +- .../_index.md | 212 ++++++++++++ .../english/net/working-with-fonts/_index.md | 3 +- .../_index.md | 215 ++++++++++++ words/french/net/basic-conversions/_index.md | 1 + .../_index.md | 195 +++++++++++ .../_index.md | 6 + .../_index.md | 314 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/french/net/working-with-fonts/_index.md | 3 +- .../_index.md | 219 ++++++++++++ words/german/net/basic-conversions/_index.md | 3 +- .../_index.md | 194 +++++++++++ .../_index.md | 8 +- .../_index.md | 315 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/german/net/working-with-fonts/_index.md | 2 +- .../_index.md | 219 ++++++++++++ words/greek/net/basic-conversions/_index.md | 1 + .../_index.md | 196 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/greek/net/working-with-fonts/_index.md | 5 +- .../_index.md | 219 ++++++++++++ words/hindi/net/basic-conversions/_index.md | 11 +- .../_index.md | 194 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 201 +++++++++++ words/hindi/net/working-with-fonts/_index.md | 5 +- .../_index.md | 217 ++++++++++++ .../hongkong/net/basic-conversions/_index.md | 1 + .../_index.md | 206 ++++++++++++ .../_index.md | 2 + .../_index.md | 313 +++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 212 ++++++++++++ .../hongkong/net/working-with-fonts/_index.md | 3 +- .../_index.md | 213 ++++++++++++ .../hungarian/net/basic-conversions/_index.md | 1 + .../_index.md | 196 +++++++++++ .../_index.md | 4 + .../_index.md | 316 ++++++++++++++++++ .../_index.md | 273 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ .../net/working-with-fonts/_index.md | 5 +- .../_index.md | 217 ++++++++++++ .../net/basic-conversions/_index.md | 1 + .../_index.md | 206 ++++++++++++ .../_index.md | 4 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ .../net/working-with-fonts/_index.md | 2 +- .../_index.md | 217 ++++++++++++ words/italian/net/basic-conversions/_index.md | 1 + .../_index.md | 205 ++++++++++++ .../_index.md | 5 +- .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ .../italian/net/working-with-fonts/_index.md | 2 +- .../_index.md | 217 ++++++++++++ .../japanese/net/basic-conversions/_index.md | 1 + .../_index.md | 194 +++++++++++ .../_index.md | 2 + .../_index.md | 314 +++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 273 +++++++++++++++ .../japanese/net/working-with-fonts/_index.md | 1 + .../_index.md | 213 ++++++++++++ words/korean/net/basic-conversions/_index.md | 1 + .../_index.md | 206 ++++++++++++ .../_index.md | 4 +- .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 212 ++++++++++++ words/korean/net/working-with-fonts/_index.md | 2 +- .../_index.md | 215 ++++++++++++ words/polish/net/basic-conversions/_index.md | 3 +- .../_index.md | 196 +++++++++++ .../_index.md | 6 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ words/polish/net/working-with-fonts/_index.md | 2 +- .../_index.md | 219 ++++++++++++ .../net/basic-conversions/_index.md | 2 + .../_index.md | 206 ++++++++++++ .../_index.md | 6 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 213 ++++++++++++ .../net/working-with-fonts/_index.md | 6 +- .../_index.md | 217 ++++++++++++ words/russian/net/basic-conversions/_index.md | 1 + .../_index.md | 195 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ .../russian/net/working-with-fonts/_index.md | 2 +- .../_index.md | 219 ++++++++++++ words/spanish/net/basic-conversions/_index.md | 3 +- .../_index.md | 195 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 213 ++++++++++++ .../spanish/net/working-with-fonts/_index.md | 4 +- .../_index.md | 216 ++++++++++++ words/swedish/net/basic-conversions/_index.md | 1 + .../_index.md | 195 +++++++++++ .../_index.md | 7 +- .../_index.md | 315 +++++++++++++++++ .../_index.md | 269 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 204 +++++++++++ .../swedish/net/working-with-fonts/_index.md | 3 +- .../_index.md | 217 ++++++++++++ words/thai/net/basic-conversions/_index.md | 1 + .../_index.md | 192 +++++++++++ .../_index.md | 7 +- .../_index.md | 314 +++++++++++++++++ .../_index.md | 271 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 211 ++++++++++++ words/thai/net/working-with-fonts/_index.md | 1 + .../_index.md | 215 ++++++++++++ words/turkish/net/basic-conversions/_index.md | 1 + .../_index.md | 196 +++++++++++ .../_index.md | 2 + .../_index.md | 315 +++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 1 + .../_index.md | 214 ++++++++++++ .../turkish/net/working-with-fonts/_index.md | 3 +- .../_index.md | 219 ++++++++++++ .../net/basic-conversions/_index.md | 1 + .../_index.md | 207 ++++++++++++ .../_index.md | 2 + .../_index.md | 316 ++++++++++++++++++ .../_index.md | 272 +++++++++++++++ .../programming-with-txtsaveoptions/_index.md | 2 +- .../_index.md | 214 ++++++++++++ .../net/working-with-fonts/_index.md | 1 + .../_index.md | 217 ++++++++++++ 207 files changed, 28155 insertions(+), 65 deletions(-) create mode 100644 words/arabic/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/arabic/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/arabic/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/arabic/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/arabic/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/chinese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/chinese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/chinese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/chinese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/chinese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/czech/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/czech/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/czech/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/czech/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/czech/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/dutch/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/dutch/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/dutch/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/dutch/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/dutch/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/english/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/english/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/english/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/english/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/english/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/french/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/french/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/french/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/french/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/french/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/german/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/german/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/german/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/german/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/german/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/greek/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/greek/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/greek/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/greek/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/greek/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/hindi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/hindi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/hindi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/hindi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/hindi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/hongkong/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/hongkong/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/hongkong/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/hongkong/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/hongkong/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/hungarian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/hungarian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/hungarian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/hungarian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/hungarian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/indonesian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/indonesian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/indonesian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/indonesian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/indonesian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/italian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/italian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/italian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/italian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/italian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/japanese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/japanese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/japanese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/japanese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/japanese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/korean/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/korean/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/korean/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/korean/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/korean/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/polish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/polish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/polish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/polish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/polish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/portuguese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/portuguese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/portuguese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/portuguese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/portuguese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/russian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/russian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/russian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/russian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/russian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/spanish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/spanish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/spanish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/spanish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/spanish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/swedish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/swedish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/swedish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/swedish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/swedish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/thai/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/thai/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/thai/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/thai/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/thai/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/turkish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/turkish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/turkish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/turkish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/turkish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md create mode 100644 words/vietnamese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md create mode 100644 words/vietnamese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md create mode 100644 words/vietnamese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md create mode 100644 words/vietnamese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md create mode 100644 words/vietnamese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md diff --git a/words/arabic/net/basic-conversions/_index.md b/words/arabic/net/basic-conversions/_index.md index c94cb16ecc..ae02b33521 100644 --- a/words/arabic/net/basic-conversions/_index.md +++ b/words/arabic/net/basic-conversions/_index.md @@ -25,6 +25,7 @@ | [تحويل Docx إلى RTF](./docx-to-rtf/) تعلّم كيفية تحويل DOCX إلى RTF باستخدام Aspose.Words لـ .NET من خلال دليلنا خطوة بخطوة. تحويل سهل لمعالجة مستندات سلسة. | | [تحويل ملف Word إلى PDF](./docx-to-pdf/) تعرّف على كيفية تحويل ملفات Word إلى PDF بسهولة باستخدام Aspose.Words for .NET من خلال دليلنا. مثالي للمطورين الذين يبحثون عن تحويل سريع وموثوق للمستندات. | | [تحويل Word إلى PDF باستخدام C# و Aspose.Words – دليل](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | تعرّف على كيفية تحويل مستندات Word إلى PDF باستخدام C# و Aspose.Words خطوة بخطوة مع أمثلة عملية. | +| [تحويل Word إلى PDF باستخدام C# – دليل كامل مع Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | تعرّف على كيفية تحويل مستندات Word إلى PDF باستخدام C# و Aspose.Words خطوة بخطوة مع أمثلة عملية وشاملة. | | [حفظ مستند Word كـ PDF باستخدام Aspose.Words – دليل C# كامل](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | تعرّف على طريقة حفظ مستندات Word بصيغة PDF باستخدام Aspose.Words في C# مع شرح مفصل وأمثلة عملية. | | [تحويل Docx إلى بايت](./docx-to-byte/) | تعلّم كيفية تحويل ملفات Docx إلى مصفوفة بايت في .NET باستخدام Aspose.Words لمعالجة مستندات فعّالة. دليل خطوة بخطوة مُرفق. | | [تحويل Docx إلى Epub](./docx-to-epub/) حوّل ملفات DOCX إلى EPUB بسهولة باستخدام Aspose.Words لـ .NET. اتبع دليلنا التعليمي لدمجها بسلاسة في تطبيقات .NET. diff --git a/words/arabic/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/arabic/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..10c7582902 --- /dev/null +++ b/words/arabic/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,198 @@ +--- +category: general +date: 2026-04-05 +description: تحويل Word إلى PDF في C# باستخدام Aspose.Words. تعلم كيفية حفظ ملف docx كـ PDF، + وتصدير PDF قابل للوصول، وتحميل مستند Word بكفاءة. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: ar +og_description: تحويل Word إلى PDF في C# مع دليل خطوة بخطوة. اكتشف كيفية حفظ ملف docx + كـ PDF، وتصدير PDF قابل للوصول، وتحميل مستند Word باستخدام Aspose.Words. +og_title: تحويل Word إلى PDF في C# – دليل Aspose.Words الكامل +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: تحويل Word إلى PDF في C# – دليل كامل مع Aspose.Words +url: /ar/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل Word إلى PDF باستخدام C# – دليل برمجة كامل + +هل تساءلت يومًا كيف **convert word to pdf** دون الحاجة إلى التعامل مع أدوات سطر الأوامر المعقدة أو الخدمات الخارجية؟ لست وحدك. يواجه العديد من المطورين هذه المشكلة عندما يطلب العميل ملف PDF سهل الوصول مباشرةً من ملف DOCX. الخبر السار؟ ببضع أسطر من C# ومكتبة Aspose.Words القوية، يمكنك تحويل مستند Word إلى PDF متوافق مع المعايير في لحظة. + +في هذا الدليل سنستعرض كل ما تحتاج إلى معرفته: من أساسيات **load word document**، مرورًا بتكوين الخيارات الصحيحة إلى **how to export accessible pdf**، وأخيرًا حفظ النتيجة حتى تتمكن من **save docx as pdf** بثقة. في النهاية ستحصل على مقطع جاهز للتنفيذ يمكنك إدراجه في أي مشروع .NET. + +> **نصيحة احترافية:** إذا كنت تستهدف توافق PDF/UA‑2 (معيار الوصول الذي تتطلبه العديد من الجهات الحكومية)، فإن نفس الكود يعمل دون أي خطوات إضافية—فقط اضبط العلامة `PdfCompliance` الصحيحة. + +--- + +## ما ستتعلمه + +- كيفية **load word document** باستخدام Aspose.Words في C#. +- الإعدادات الدقيقة المطلوبة لـ **how to export accessible pdf** (PDF/UA‑2). +- مثال كامل قابل للتنفيذ يقوم بـ **save docx as pdf** باستدعاء طريقة واحدة. +- المشكلات الشائعة عند **c# convert docx pdf** وكيفية تجنبها. +- طرق سريعة للتحقق من أن PDF المُنشأ يفي بتوقعات الوصول. + +بدون أدوات خارجية، بدون ملفات إعدادات غامضة—فقط كود C# نقي يمكنك تجميعه اليوم. + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من أن لديك: + +1. **.NET 6.0** (أو أي نسخة .NET حديثة) مثبتة. الإطارات الأقدم تعمل أيضًا، لكن الصياغة أدناه تفترض SDK الحديثة. +2. **رخصة** لـ Aspose.Words for .NET. المكتبة تقدم نسخة تجريبية مجانية، لكن للإنتاج ستحتاج إلى مفتاح صالح. +3. حزمة **Aspose.Words** NuGet مضافة إلى مشروعك: + +```bash +dotnet add package Aspose.Words +``` + +هذا كل شيء—بدون ملفات تنفيذية إضافية، بدون تفاعل COM، فقط مرجع NuGet نظيف. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +--- + +## تنفيذ خطوة بخطوة + +فيما يلي نقسم العملية إلى أجزاء منطقية. كل خطوة تحتوي على مقتطف كود صغير، شرح **لماذا** هو مهم، ونصيحة مستمدة من الاستخدام الواقعي. + +### ## تحويل Word إلى PDF – تحميل المستند المصدر + +أول شيء تحتاج إلى القيام به هو **load word document** في الذاكرة. تقوم Aspose.Words بتجريد عملية تحليل OpenXML، لذا يمكنك العمل مع ملفات DOCX أو DOC أو حتى RTF دون القلق بشأن خصوصيات التنسيق. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**لماذا هذا مهم:** +تحميل الملف ينشئ كائن `Document` يمثل ملف Word بالكامل، بما في ذلك الرؤوس، التذييلات، الأنماط، والبيانات الوصفية المخفية. إذا تخطيت هذه الخطوة أو حاولت قراءة الملف كتيار خام، ستفقد معلومات التخطيط التي تحدد لاحقًا مظهر PDF. + +> **ملاحظة جانبية:** يعمل نفس مُنشئ `Document` مع `.doc` و `.rtf`. وهذا يعني أنه يمكنك **c# convert docx pdf** حتى عندما لا يكون المصدر DOCX بالضرورة. + +### ## حفظ DOCX كـ PDF – تكوين توافق PDF/UA‑2 + +الآن بعد أن أصبح المستند في الذاكرة، نخبر Aspose.Words كيف نريد توليد PDF. بالنسبة لمعظم الحالات، الإعدادات الافتراضية مناسبة، ولكن عندما تحتاج إلى **accessible PDF** يجب تمكين علم توافق PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**لماذا هذا مهم:** +`PdfCompliance.PdfUAXmpA2` يخبر المكتبة بدمج العلامات والهياكل الضرورية التي يعتمد عليها قارئ الشاشة. بدون هذا العلم، قد تحصل على PDF يبدو ممتازًا لكنه يفشل في تدقيق الوصول. + +> **نصيحة:** إذا كنت تحتاج فقط إلى PDF عادي، يمكنك حذف سطر `Compliance`. باقي الخيارات لا تزال تمنحك مخرجات عالية الجودة. + +### ## تحويل Word إلى PDF – كتابة الملف + +مع إعداد الخيارات، الخطوة الأخيرة هي **save docx as pdf**. هذا الاستدعاء الواحد يقوم بكل الأعمال الثقيلة: تحويل التخطيط، تضمين الخطوط، وإضافة علامات الوصول. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**ما ستحصل عليه:** +- ملف PDF في `outputPath` يعكس تخطيط Word. +- إذا استخدمت علم `PdfUAXmpA2`، سيتم وضع علامة على PDF بأنه متوافق مع PDF/UA‑2. +- جميع الخطوط مدمجة، لذا يبدو الملف متطابقًا على أي جهاز. + +### ## التحقق من PDF القابل للوصول (اختياري لكن موصى به) + +بعد التحويل، من الجيد التحقق مرة أخرى من أن PDF فعليًا **how to export accessible pdf** بشكل صحيح. يمكنك استخدام أدوات مجانية مثل “فحص الوصول” في Adobe Acrobat Reader أو أداة التحقق المفتوحة المصدر `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +إذا أبلغت أداة التحقق عن عدم وجود أخطاء، فقد نجحت في **convert word to pdf** بدعم كامل للوصول. + +### ## المشكلات الشائعة عند تحويل C# DOCX إلى PDF + +| المشكلة | سبب حدوثه | الحل | +|-------|----------------|-----| +| الخطوط المفقودة | ملف DOCX الأصلي يستخدم خطًا مخصصًا غير مثبت على الخادم. | اضبط `EmbedFullFonts = true` أو قم بتثبيت الخط على الجهاز. | +| حجم الملف كبير | يتم تضمين الصور بدقة كاملة. | استخدم `ImageCompression = PdfImageCompression.Jpeg` واضبط `JpegQuality` على قيمة أقل. | +| الروابط المعطلة | الروابط تشير إلى مسارات نسبية غير موجودة على العميل. | تأكد من أن عناوين URL مطلقة أو عدل خاصية `HyperlinkTarget`. | +| الوسوم الخاصة بإمكانية الوصول مفقودة | لم يتم ضبط علم `Compliance`. | أضف `Compliance = PdfCompliance.PdfUAXmpA2` كما هو موضح أعلاه. | + +مراعاة هذه النقاط سيجعل روتين **c# convert docx pdf** قويًا وجاهزًا للإنتاج. + +## مثال كامل يعمل + +بجمع كل ذلك معًا، إليك تطبيق console مستقل يمكنك تجميعه وتشغيله الآن. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**النتيجة المتوقعة:** بعد تشغيل البرنامج، ستجد `output.pdf` في `C:\Docs`. افتحه في أي عارض PDF؛ يجب أن يتطابق التخطيط مع `input.docx` بدقة البكسل، وسيتأكد فحص الوصول من توافقه مع PDF/UA‑2. + +## الخلاصة + +لقد استعرضنا للتو حلاً كاملاً من البداية إلى النهاية لكيفية **convert word to pdf** باستخدام C# و Aspose.Words. من خلال **load word document**، تكوين `PdfSaveOptions` المناسب، وأخيرًا **save docx as pdf**، ستحصل على PDF عالي الجودة وسهل الوصول بأقل قدر من الكود. سواء كنت تبني خدمة ميكرو لتوليد المستندات، أو محول دفعي محلي، + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-markdownsaveoptions/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/_index.md index 46ce6eb44b..dfab7640b7 100644 --- a/words/arabic/net/programming-with-markdownsaveoptions/_index.md +++ b/words/arabic/net/programming-with-markdownsaveoptions/_index.md @@ -36,12 +36,16 @@ ### [حفظ docx كـ markdown – دليل C# كامل مع استخراج الصور](./save-docx-as-markdown-full-c-guide-with-image-extraction/) +### [تحويل DOCX إلى Markdown – استخراج الصور من DOCX باستخدام Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) + ### [كيفية تصدير Markdown من Word – دليل C# كامل](./how-to-export-markdown-from-word-complete-c-guide/) ### [كيفية حفظ Markdown من DOCX – دليل خطوة بخطوة](./how-to-save-markdown-from-docx-step-by-step-guide/) ### [كيفية تصدير Markdown من DOCX – دليل كامل](./how-to-export-markdown-from-docx-complete-guide/) +### [تحويل Word إلى Markdown – دليل كامل مع تصدير PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..c8771e4529 --- /dev/null +++ b/words/arabic/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: تعلم كيفية تحويل ملفات DOCX إلى Markdown واستخراج الصور من DOCX باستخدام + C#. دليل خطوة بخطوة مع الشيفرة الكاملة والنصائح. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: ar +og_description: تحويل DOCX إلى Markdown واستخراج الصور من DOCX باستخدام Aspose.Words. + دليل كامل بلغة C# يتضمن الشيفرة، الشرح، ونصائح أفضل الممارسات. +og_title: تحويل DOCX إلى Markdown – استخراج الصور من DOCX باستخدام C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: تحويل DOCX إلى Markdown – استخراج الصور من DOCX باستخدام Aspose.Words +url: /ar/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل DOCX إلى Markdown – استخراج الصور من DOCX باستخدام C# + +هل احتجت يومًا إلى **تحويل DOCX إلى Markdown** لكنك واجهت صعوبة في اختفاء الصور في الناتج؟ لست وحدك. في العديد من المشاريع تكون نسخة الـ markdown مثالية للتحكم في الإصدارات أو مولدات المواقع الثابتة، لكن الصور تُترك خلفها، مما يحول مستندًا غنيًا إلى ملف نصي جاف. + +الأخبار السارة؟ باستخدام بضع أسطر من C# و Aspose.Words يمكنك **تحويل DOCX إلى Markdown** *و* **استخراج الصور من DOCX** تلقائيًا. هذا الدليل يشرح لك العملية بالكامل، ويوضح لماذا كل جزء مهم، ويظهر لك أيضًا كيفية الحفاظ على مجلد الصور منظمًا. + +## ما ستتعلمه + +- كيفية تحميل ملف DOCX يحتوي على صور. +- كيفية تعريف `IResourceSavingCallback` مخصص يحدد أين تُحفظ كل صورة. +- كيفية تكوين `MarkdownSaveOptions` بحيث تشير الـ markdown المُنشأة إلى الصور المستخرجة بشكل صحيح. +- نصائح للتعامل مع الحالات الخاصة مثل أسماء الصور المتكررة أو الصيغ غير PNG. +- عينة كود كاملة جاهزة للنسخ واللصق يمكنك تشغيلها اليوم. + +### المتطلبات المسبقة + +- .NET 6.0 أو أحدث (تعمل الواجهة البرمجية على .NET Core و .NET Framework و .NET 5+). +- رخصة لـ **Aspose.Words for .NET** (الإصدار التجريبي المجاني يعمل للاختبار). +- إلمام أساسي بـ C# و Visual Studio (أو بيئة التطوير المفضلة لديك). + +إذا كان لديك هذه المتطلبات، هيا نبدأ. + +--- + +## الخطوة 1: إعداد المشروع وتثبيت Aspose.Words + +أولاً، أنشئ تطبيق console جديد (أو دمجه في حل موجود). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **نصيحة احترافية:** استخدم أحدث نسخة من NuGet (اعتبارًا من أبريل 2026 الإصدار 24.12) للحصول على أحدث تحسينات تصدير markdown. + +--- + +## الخطوة 2: إنشاء رد نداء لحفظ الصور في المكان الذي تريده + +يتيح لك Aspose.Words اعتراض كل مورد (صور، SVGs، إلخ) يتم كتابته أثناء تصدير markdown. من خلال تنفيذ `IResourceSavingCallback` يمكنك: + +1. اختيار مجلد يقع بجوار ملف markdown الخاص بك. +2. إنشاء اسم ملف فريد (حتى لا تقوم بالكتابة فوق صورة موجودة). +3. تحديد الصيغة (هنا نجبر على PNG للاتساق). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### لماذا اسم مبني على GUID؟ + +إذا كان ملف DOCX المصدر يحتوي على صورتين بنفس الاسم الأصلي، فإن النسخ‑اللصق البسيط سيستبدل إحداهما. استخدام `Guid.NewGuid()` يضمن التفرد، وهو مفيد جدًا عندما تقوم بتشغيل التحويل عدة مرات في خط أنابيب آلي. + +--- + +## الخطوة 3: تحميل DOCX وربط خيارات Markdown + +الآن نقوم بتحميل المستند إلى الذاكرة وربط رد النداء الذي أنشأناه للتو. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### ما يفعله الكود خطوة بخطوة + +| الخطوة | الغرض | +|------|---------| +| **تحديد المسارات** | يحافظ على مرونة مشروعك؛ يمكنك الإشارة إلى أي مجلد دون الحاجة لإعادة التجميع. | +| **تحميل الـ DOCX** | `Document` يحلل ملف Word، مما يجعل جميع العناصر (فقرات، جداول، صور) متاحة. | +| **تكوين `MarkdownSaveOptions`** | `ResourceSavingCallback` هو النقطة التي تستخرج الصور. بدونه، سيقوم Aspose.Words إما بدمج الصور كسلاسل base64 أو حذفها تمامًا، حسب الإعدادات. | +| **حفظ** | `doc.Save` يكتب ملف markdown ويُطلق رد النداء لكل صورة. | + +--- + +## الخطوة 4: التحقق من الناتج – ماذا يجب أن ترى؟ + +بعد تشغيل البرنامج، افتح `DocWithImages.md`. ستلاحظ روابط صور markdown التي تبدو هكذا: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +وفي `C:\Docs\MarkdownResources` ستجد مجموعة من ملفات PNG بأسماء GUID. افتح أيًا منها – يجب أن تكون مطابقة للصور التي كانت مدمجة في الـ DOCX الأصلي. + +إذا فتحت ملف markdown في عارض يحترم المسارات النسبية (مثل معاينة VS Code، GitHub، أو مولد موقع ثابت)، ستظهر الصور كما ظهرت في Word. + +### الأخطاء الشائعة وكيفية تجنبها + +| العَرَض | السبب المحتمل | الحل | +|---------|--------------|-----| +| الصور تظهر كروابط مكسورة | `ResourceFileName` لم يتم تعيينه، لذا يشير الـ markdown إلى ملف غير موجود. | تأكد من `args.ResourceFileName = newFileName;` داخل رد النداء. | +| ملفات PNG ضخمة | الصور الأصلية كانت JPEG أو BMP؛ تحويلها إلى PNG قد يزيد الحجم. | اكتشف الصيغة الأصلية عبر `args.ResourceContentType` وحافظ عليها: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| الصور المتكررة لا تزال تظهر | استخدمت اسم ملف ثابت بدلاً من GUID. | ارجع إلى منطق GUID أو أضف عدادًا لكل نوع صورة. | +| التحويل يطرح استثناء `FileNotFoundException` | مسار DOCX المصدر غير صحيح أو المجلد يفتقر إلى صلاحية القراءة. | تحقق من المسار ومنح الصلاحيات المناسبة لنظام الملفات. | + +--- + +## الخطوة 5: تعديلات متقدمة (اختياري) + +### 5.1 الحفاظ على صيغ الصور الأصلية + +إذا كنت تريد أن تحتفظ الصور الناتجة بامتداداتها الأصلية، عدل رد النداء: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 تضمين الصور كـ Base64 (عندما *لا تريد* ملفات منفصلة) + +أحيانًا يكون markdown بملف واحد مفضلاً (مثلاً للإرسال عبر البريد الإلكتروني). غيّر الخيار: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +لكن تذكر: **استخراج الصور من DOCX** هو الهدف الأساسي لمعظم سير عمل المواقع الثابتة، لذا فإن نهج المجلد عادةً ما يكون الخيار الأفضل. + +--- + +## مثال كامل يعمل (جاهز للنسخ واللصق) + +فيما يلي البرنامج الكامل في ملف واحد. فقط استبدل المسارات بمساراتك الخاصة وشغّله. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +شغّله باستخدام `dotnet run`. عندما يطبع الطرفية السطر ✅، افتح ملف markdown ويجب أن ترى الصور معروضة بشكل صحيح. + +--- + +## الخلاصة + +أصبح لديك الآن **حل كامل وجاهز للإنتاج لتحويل DOCX إلى Markdown واستخراج الصور من DOCX** باستخدام Aspose.Words في C#. الكلمة المفتاحية الأساسية تظهر طوال الدليل، مما يعزز الصلة لمحركات البحث ومساعدي الذكاء الاصطناعي. + +في خطوة واحدة يقوم الكود بـ: + +1. تحميل مستند Word. +2. اعتراض كل صورة عبر `IResourceSavingCallback`. +3. حفظ كل صورة في مجلد متوقع باسم فريد. +4. توليد markdown يشير إلى تلك الصور. + +من هنا يمكنك: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/arabic/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..1c17e92509 --- /dev/null +++ b/words/arabic/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: حوّل مستند Word إلى Markdown بسرعة وتعلم أيضًا كيفية حفظه كملف PDF/UA + باستخدام C#. كود خطوة بخطوة، نصائح وتعامل مع الحالات الخاصة. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: ar +og_description: حوّل ملفات Word إلى Markdown واحفظها كملف PDF/UA باستخدام Aspose.Words. + تعلّم الأسباب، والطريقة، ونصائح أفضل الممارسات في دليل مختصر واحد. +og_title: تحويل Word إلى Markdown – دليل C# الكامل +tags: +- Aspose.Words +- C# +- Document Conversion +title: تحويل Word إلى Markdown – دليل كامل مع تصدير PDF/UA +url: /ar/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل Word إلى Markdown – دليل كامل مع تصدير PDF/UA + +هل تساءلت يومًا كيف **تحويل Word إلى Markdown** دون فقدان المعادلات أو الصور؟ لست وحدك. يحتاج العديد من المطورين إلى طريقة موثوقة لتحويل ملفات `.docx` إلى Markdown نظيفة مع القدرة على **حفظ كـ PDF/UA** للحصول على ملفات PDF متوافقة مع معايير إمكانية الوصول. في هذا الدرس سنستعرض حلًا كاملاً جاهزًا للتنفيذ باستخدام Aspose.Words for .NET، نشرح لماذا كل إعداد مهم، ونظهر لك كيفية التعامل مع الأجزاء الصعبة مثل OfficeMath والأشكال العائمة. + +بنهاية هذا الدليل ستحصل على برنامج C# واحد يقوم بـ: + +1. تحميل مستند Word مع استرداد مرن (حتى لا تتعطل العملية عند وجود ملفات تالفة). +2. تصديره إلى Markdown، مع تحويل المعادلات إلى LaTeX وتخزين الصور عبر رد نداء مخصص. +3. حفظ نفس المستند كملف PDF/UA‑2 متوافق، مع تضمين الأشكال العائمة كوسوم داخلية. + +يبدو كثيرًا؟ لا تقلق—لنبدأ. + +## ما ستحتاجه + +- **Aspose.Words for .NET** (أحدث نسخة، 23.x في وقت كتابة هذا الدليل). +- بيئة تطوير .NET (Visual Studio 2022، Rider، أو سطر أوامر `dotnet`). +- ملف Word تجريبي (`input.docx`) موجود في مجلد يمكنك الإشارة إليه. +- إلمام أساسي بصياغة C#—ليس شيئًا معقدًا، مجرد بضع جمل `using`. + +> **نصيحة احترافية:** إذا كنت تستخدم مدير حزم NuGet، أضف المكتبة بالأمر +> `dotnet add package Aspose.Words` أو عبر واجهة NuGet في Visual Studio. + +## الخطوة 1 – تحميل مستند Word مع الاسترداد المُرخّص + +عند استلام ملفات Word من مصادر خارجية قد تحتوي على بعض الفساد البسيط. تمكين الاسترداد **Relaxed** يخبر Aspose.Words بالاستمرار بدلاً من إلقاء استثناء. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**لماذا هذا مهم:** +- `RecoveryMode.Relaxed` يمنع فقرة واحدة غير صحيحة من إيقاف عملية التحويل بالكامل. +- توفير كائن `FontSettings` يضمن استبدال الخطوط المفقودة بشكل سلس، وهو أمر حاسم عندما تقوم لاحقًا بتحويل المعادلات إلى LaTeX. + +## الخطوة 2 – تصدير إلى Markdown (OfficeMath → LaTeX، الصور عبر رد نداء) + +لا يدعم Markdown طريقة أصلية لتمثيل معادلات Word. يمكن لـ Aspose.Words تحويل كائنات **OfficeMath** إلى LaTeX، وهو ما يفهمه معظم عارضات Markdown. أما الصور، فتحتاج إلى حفظها في مكان ما؛ **resource‑saving callback** مخصص يمنحك التحكم الكامل في بنية المجلدات وأسماء الملفات. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### رد نداء حفظ الموارد + +الشفرة التالية صغيرة جدًا تقوم بتخزين كل صورة في مجلد فرعي يُسمى `images` وتسمية الملفات بـ `img001.png`، `img002.png`، إلخ. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**لماذا تحتاج هذا:** +- بدون رد نداء، ينشئ Aspose.Words مجلدًا مسطحًا بأسماء GUID عشوائية، مما يجعل التحكم في الإصدارات فوضويًا. +- عبر التحكم في نظام التسمية تحافظ على تنظيم مستودع Markdown وتجعله قابلًا لإعادة الإنتاج. + +### النتيجة المتوقعة للـ Markdown + +افتح `doc.md` بعد التنفيذ وسترى: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +تظهر المعادلات كـ LaTeX محاطة بـ `$$ … $$`، وتُشير الصور إلى مجلد `images` الذي أنشأته للتو. + +## الخطوة 3 – تصدير إلى PDF/UA‑2 (جاهز لإمكانية الوصول) + +إذا كنت بحاجة لمشاركة المستند مع مستخدمين يعتمدون على قارئات الشاشة أو تقنيات مساعدة أخرى، فإن التوافق مع **PDF/UA‑2** هو المعيار الذهبي. يمكن لـ Aspose.Words فرض ذلك بعلامة واحدة، كما يمكنه تسوية الأشكال العائمة إلى وسوم داخلية حتى لا تُفقد أثناء التحويل. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**لماذا PDF/UA مهم:** +- PDF/UA (Universal Accessibility) يضمن أن ملف PDF الناتج يحتوي على وسم صحيح، ترتيب قراءة منطقي، ونص بديل للصور. +- ضبط `ExportFloatingShapesAsInlineTag` يضمن عدم إهمال أو إزاحة الأشكال مثل صناديق النص أو التعليقات—a مشكلة شائعة عند تحويل تخطيطات معقدة. + +### التحقق من توافق PDF/UA + +بعد التصدير، افتح ملف PDF في Adobe Acrobat Pro وشغّل **“Accessibility Check”** (Tools → Accessibility → Full Check). إذا أظهر الأداة **0 errors**، فقد نجحت. + +## حالات الحافة والمشكلات الشائعة + +| الحالة | ما يجب مراقبته | الحل / التوصية | +|------------------------------------------|------------------------------------------------------|-----------------------------------------------------------| +| ملف Word يحتوي على **خطوط غير مدعومة** | قد تُستبدل الخطوط، مما يفسد تنسيق المعادلات | قدم `FontSettings` مخصص مع خطوط احتياطية. | +| مستندات كبيرة (> 100 MB) | ضغط على الذاكرة أثناء التحويل | استخدم `LoadOptions` مع `LoadFormat.Docx` وقراءة الملف عبر تدفق. | +| الصور هي رسومات متجهة **EMF/WMF** | قد تُرسم كصور نقطية عن غير قصد | حوّلها إلى PNG عبر `ImageSaveOptions` قبل الحفظ. | +| فشل PDF/UA في التحقق على **جداول متداخلة** | قد يصبح الوسم غير واضح | فعّل `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` لمساعدة المحرك. | +| الحاجة إلى **الحفاظ على الأنماط المخصصة** | Markdown يملك قدرات تنسيق محدودة | صدّر ملف CSS بجانب Markdown وأشر إليه. | + +## مثال عملي كامل (كل الشيفرات معًا) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +شغّل البرنامج، وستجد كلًا من `doc.md` (مع معادلات LaTeX وروابط صور نظيفة) و`doc.pdf` (متوافق تمامًا مع PDF/UA‑2) في `YOUR_DIRECTORY`. + +## نظرة بصرية + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*نص بديل:* **مثال تحويل Word إلى Markdown** – مخطط يوضح مسار التحويل من ملف Word إلى Markdown وملف PDF/UA. + +## ملخص وخطوات قادمة + +لقد **حولنا Word إلى Markdown** مع الحفاظ على المعادلات، وخزنّا الصور في مجلد منظم، وأنتجنا ملف **حفظ كـ PDF/UA** يجتاز فحوصات إمكانية الوصول. النقاط الأساسية هي: + +- استخدم `LoadOptions.RecoveryMode.Relaxed` لتتحمل ملفات Word غير المثالية. +- اضبط `OfficeMathExportMode` إلى `LaTeX` للحصول على عرض معادلات نظيف. +- نفّذ `ResourceSavingCallback` للتحكم في إخراج الصور. +- فعّل `PdfCompliance.PdfUAXmpA2` و`ExportFloatingShapesAsInlineTag` للحصول على PDF متوافق مع المعايير. + +### ما الذي يمكنك استكشافه لاحقًا؟ + +- **CSS مخصص للـ Markdown** – أنشئ ورقة أنماط تعكس أنماط Word الخاصة بك. +- **معالجة دفعات** – كرّر عبر مجلد من ملفات `.docx` لأتمتة ترحيل كميات كبيرة. +- **ميزات PDF/UA المتقدمة** – أضف وسومًا مخصصة، عيّن خصائص اللغة، أو أدمج أوصافًا صوتية. +- **التكامل مع CI/CD** – تأكد من أن كل بناء ينتج ملفات PDF قابلة للوصول تلقائيًا. + +إذا واجهت أي مشكلة، تحقق مرة أخرى من أن نسخة Aspose.Words التي تستخدمها تتطابق مع الـ API المذكور هنا، وتذكر أن وثائق المكتبة نفسها تُعد مرجعًا ثانويًا قويًا. + +برمجة سعيدة، ولتظل مستنداتك جميلة **و** قابلة للوصول! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/programming-with-txtsaveoptions/_index.md b/words/arabic/net/programming-with-txtsaveoptions/_index.md index b047adbbaf..6e48c3969f 100644 --- a/words/arabic/net/programming-with-txtsaveoptions/_index.md +++ b/words/arabic/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ | [إضافة علامات Bidi في مستند Word](./add-bidi-marks/) تعرّف على كيفية إضافة علامات ثنائية الاتجاه (Bidi) في مستندات Word باستخدام Aspose.Words لـ .NET من خلال هذا الدليل. تأكد من اتجاه النص الصحيح للمحتوى متعدد اللغات. | [استخدم حرف Tab لكل مستوى لتقسيم القائمة](./use-tab-character-per-level-for-list-indentation/) | تعلّم كيفية إنشاء قوائم متعددة المستويات مع مسافات بادئة مبوبة باستخدام Aspose.Words لـ .NET. اتبع هذا الدليل لتنسيق القوائم بدقة في مستنداتك. | | [استخدم حرف المسافة لكل مستوى لتجويف القائمة](./use-space-character-per-level-for-list-indentation/) | تعلّم كيفية إنشاء قوائم متعددة المستويات مع إضافة مسافة بادئة في Aspose.Words لـ .NET. دليل خطوة بخطوة لتنسيق المستندات بدقة. | - +| [حفظ docx كملف txt – تصدير معادلات Word إلى LaTeX باستخدام C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | تعلم كيفية حفظ مستندات docx كملفات نصية وتصدير المعادلات إلى LaTeX باستخدام C# و Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/arabic/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/arabic/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..2ff22dca89 --- /dev/null +++ b/words/arabic/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-04-05 +description: احفظ ملف docx كملف txt باستخدام Aspose.Words – تحويل سريع من Word إلى txt وتعلّم + كيفية تصدير المعادلات الرياضية كـ LaTeX. كود C# بسيط، لا حاجة لأدوات إضافية. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: ar +og_description: احفظ ملف docx كملف txt في C# وتعرّف على كيفية تصدير الرياضيات إلى LaTeX. + اتبع هذا الدليل خطوة بخطوة لتحويل Word إلى txt مع الحفاظ على المعادلات. +og_title: حفظ ملف docx كملف txt – تصدير معادلات Word إلى LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: حفظ ملف docx كملف txt – تصدير معادلات Word إلى LaTeX باستخدام C# +url: /ar/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# حفظ docx كملف txt – تصدير معادلات Word إلى LaTeX باستخدام C# + +هل احتجت يوماً إلى **save docx as txt** لكنك كنت قلقاً من أن تختفي معادلاتك أو تتحول إلى رموز غير قابلة للقراءة؟ لست وحدك. يواجه العديد من المطورين هذه المشكلة عندما يحاولون **convert word to txt** للمعالجة اللاحقة، خاصةً عندما يحتوي ملف المصدر على كائنات Office Math. + +الخبر السار؟ ببضع أسطر من C# والخيارات المناسبة، يمكنك ليس فقط **convert Word to txt** بل أيضاً الحفاظ على كل معادلة كترميز LaTeX نظيف. في هذا الدرس سنستعرض العملية بالكامل، نشرح لماذا كل إعداد مهم، ونظهر لك كيفية التحقق من النتيجة. + +سنغطي: + +* تثبيت مكتبة Aspose.Words for .NET +* تحميل ملف `.docx` يحتوي على معادلات رياضية +* تكوين `TxtSaveOptions` بحيث يصبح **how to export math** سلسلة صديقة لـ LaTeX +* حفظ الملف والتحقق من الناتج + +في النهاية، ستحصل على مقتطف قابل لإعادة الاستخدام يتيح لك **save docx as txt** مع الحفاظ على كل صيغة كـ LaTeX—مثالي لسلاسل الأنابيب العلمية، مولدات المواقع الثابتة، أو أي سير عمل يحتاج إلى رياضيات نصية عادية. + +--- + +## المتطلبات المسبقة + +قبل أن نغوص في التفاصيل، تأكد من أن لديك: + +* .NET 6.0 أو أحدث (الكود يعمل أيضاً مع .NET Framework 4.6+ ) +* Visual Studio 2022 (أو أي بيئة تطوير تفضلها) +* حزمة **Aspose.Words for .NET** عبر NuGet – ثبّتها باستخدام + +```bash +dotnet add package Aspose.Words +``` + +لا توجد محولات إضافية أو أدوات خارجية مطلوبة؛ Aspose.Words يتولى كل العمل ثقيلًا داخليًا. + +--- + +## الخطوة 1: تثبيت وإضافة مرجع Aspose.Words + +أولاً، أضف المكتبة إلى مشروعك. إذا كنت تستخدم سطر الأوامر، شغّل الأمر أعلاه. في Visual Studio يمكنك أيضاً النقر بزر الماوس الأيمن على **Dependencies → Manage NuGet Packages** والبحث عن *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** استخدم أحدث نسخة مستقرة (حتى أبريل 2026 الإصدار هو 24.10). الإصدارات الأحدث تجلب إصلاحات للأخطاء المتعلقة بمعالجة OfficeMath، مما يجنبك فقدان الرموز غير المتوقّع. + +--- + +## الخطوة 2: تحميل المستند المصدر + +الآن نقوم بتحميل ملف `.docx` الذي يحتوي على المعادلات التي تريد الاحتفاظ بها. فئة `Document` تمثل ملف Word بالكامل، وتمنحك الوصول إلى النصوص، الصور، وكائنات Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +لماذا نحمل الملف أولاً؟ Aspose.Words يحلل الملف إلى نموذج كائنات، مما يسمح لنا بفحص أو تعديل المحتوى قبل أن نقرر طريقة التصدير. هنا تبدأ قرارات **how to export math** في إظهار أهميتها. + +--- + +## الخطوة 3: تكوين TxtSaveOptions لتصدير LaTeX + +جوهر الحل هو فئة `TxtSaveOptions`. بشكل افتراضي، حفظ الملف كـ TXT يزيل كل Office Math تمامًا. ضبط `OfficeMathExportMode` إلى `LaTeX` يخبر المكتبة بترجمة كل معادلة إلى تمثيل LaTeX الخاص بها. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX هو اللغة المشتركة للنشر العلمي. بتصدير الرياضيات بهذه الطريقة، تحتفظ بدلالة المعادلة بدلاً من صورة مسطحة أو سلسلة مشوشة. إذا قمت لاحقًا بتمرير ملف TXT إلى معالج Markdown يدعم MathJax، ستظهر المعادلات بشكل مثالي. + +--- + +## الخطوة 4: حفظ المستند كنص عادي + +مع تكوين الخيارات، الخطوة الأخيرة هي سطر واحد يكتب الملف إلى القرص. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +هذا كل شيء—ملف `.docx` الخاص بك أصبح الآن ملف `.txt` حيث تظهر كل معادلة كقطة LaTeX، جاهزة للاستخدام في المراحل اللاحقة. + +--- + +## التحقق من النتيجة (كيفية حفظ txt بشكل صحيح) + +افتح `MathSample.txt` في أي محرر نصوص. يجب أن ترى شيئًا مشابهًا لـ: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +إذا لاحظت وجود أحرف خاصة بـ Word (مثل `?` أو رموز مفقودة)، تأكد من: + +* أنك تستخدم نسخة حديثة من Aspose.Words (الإصدارات القديمة كانت تحتوي على أخطاء في OfficeMath). +* أن المستند المصدر يحتوي فعليًا على كائنات **OfficeMath**—not كائنات محرر المعادلات Legacy. بالنسبة الأخيرة، قد تحتاج إلى تحويلها يدويًا أو استخدام طريقة `ConvertMathToOfficeMath` قبل الحفظ. + +--- + +## الاختلافات الشائعة وحالات الحافة + +| الحالة | ما الذي يجب فعله | +|-----------|------------| +| **Legacy Equation Editor** objects | استدعِ `doc.ConvertMathToOfficeMath()` قبل الخطوة 3. | +| **You need plain Unicode math, not LaTeX** | عيّن `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | قم ببث عملية الحفظ باستخدام `doc.Save(Stream, txtOptions)` لتجنب استهلاك الذاكرة العالي. | +| **You want to keep the original file name** | استخدم `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` عند إنشاء مسار الإخراج. | + +هذه التعديلات تجيب على سؤال “**how to export math**” لمختلف سلاسل الأنابيب، وتضمن أن يكون حلك قويًا بغض النظر عن المصدر. + +--- + +## مثال كامل يعمل (جميع الخطوات في مكان واحد) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +شغّل البرنامج، افتح ملف `.txt` المُولد، وسترى معادلات LaTeX مدمجة في المكان الذي كانت فيه. هذه هي أبسط طريقة لـ **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/arabic/net/working-with-fonts/_index.md b/words/arabic/net/working-with-fonts/_index.md index f958b30423..eb45ad5e35 100644 --- a/words/arabic/net/working-with-fonts/_index.md +++ b/words/arabic/net/working-with-fonts/_index.md @@ -32,6 +32,7 @@ | [تعيين علامة التأكيد على الخط](./set-font-emphasis-mark/) تعرّف على كيفية ضبط علامات توكيد الخطوط في مستندات Word باستخدام Aspose.Words لـ .NET من خلال هذا الدليل المفصل خطوة بخطوة. مثالي لمطوري .NET. | [تعيين مجلدات الخطوط](./set-fonts-folders/) تعرّف على كيفية إعداد مجلدات خطوط مخصصة في Aspose.Words لـ .NET من خلال هذا الدليل الشامل خطوة بخطوة. مثالي للمطورين الذين يرغبون في تحسين خطوط المستندات. | [تمكين تعطيل استبدال الخط](./enable-disable-font-substitution/) تعرّف على كيفية تفعيل أو تعطيل استبدال الخطوط في مستندات Word باستخدام Aspose.Words لـ .NET. تأكد من تناسق مستنداتك على جميع المنصات. +| [استبدال خطوط Aspose – اكتشاف الخطوط المفقودة في مستندات Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) |تعلم كيفية اكتشاف الخطوط المفقودة في مستندات Word باستخدام Aspose.Words لـ .NET وإدارة استبدال الخطوط. | | [تعيين إعدادات الخط الاحتياطي](./set-font-fallback-settings/) |تعرف على كيفية تعيين إعدادات استبدال الخط في Aspose.Words لـ .NET وتخصيص استبدال الخط في مستندات Word الخاصة بك. | | [تحميل إعدادات Noto الاحتياطية](./load-noto-fallback-settings/) | تعرّف على كيفية تحميل إعدادات Noto الاحتياطية في مستند Word باستخدام Aspose.Words لـ .NET. اتبع دليلنا خطوة بخطوة لضمان عرض جميع الأحرف بشكل صحيح. | | [تعيين مثيلات مجلدات الخطوط الافتراضية](./set-fonts-folders-default-instance/) تعرّف على كيفية تعيين مجلدات الخطوط للنسخة الافتراضية في Aspose.Words لـ .NET من خلال هذا البرنامج التعليمي خطوة بخطوة. خصّص مستندات Word بسهولة. diff --git a/words/arabic/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/arabic/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..798be88676 --- /dev/null +++ b/words/arabic/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-04-05 +description: دليل استبدال الخطوط من Aspose لاكتشاف الخطوط المفقودة أثناء تحميل مستند + Word. تعلّم كيفية تكوين إعدادات الخطوط ومعالجة الخطوط المفقودة بكفاءة. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: ar +og_description: دليل استبدال الخطوط من Aspose لاكتشاف الخطوط المفقودة أثناء تحميل + مستند Word. تعلّم كيفية تكوين إعدادات الخطوط ومعالجة الخطوط المفقودة بفعالية. +og_title: استبدال الخطوط في Aspose – اكتشاف الخطوط المفقودة في مستندات Word +tags: +- Aspose.Words +- C# +- Font Management +title: استبدال الخطوط في Aspose – اكتشاف الخطوط المفقودة في مستندات Word +url: /ar/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استبدال الخطوط في Aspose – اكتشاف الخطوط المفقودة في مستندات Word + +هل صادفت يومًا ملف Word يبدو مثاليًا على جهاز واحد لكنه يظهر تغييرات غريبة في الخطوط على جهاز آخر؟ هذه هي المشكلة الكلاسيكية **aspose font substitution**، وعادةً ما تعني أن بعض الخطوط مفقودة على النظام المستهدف. في هذا الدرس سنوضح لك خطوة بخطوة كيفية **اكتشاف الخطوط المفقودة** عند **تحميل مستند Word**، وكيفية **تكوين إعدادات الخطوط**، وما يجب فعله **للتعامل مع الخطوط المفقودة** بشكل سلس. + +سنستعرض مثالًا كاملًا وقابلًا للتنفيذ بلغة C#، نشرح لماذا كل سطر مهم، وحتى نعرض لك مخرجات وحدة التحكم المتوقعة. بنهاية الدرس ستكون قادرًا على اكتشاف استبدال الخطوط في اللحظة التي يتم فيها تحميل المستند—دون الحاجة للتخمين. + +## ما ستتعلمه + +- كيفية تمكين جامع التشخيص في Aspose.Words لتحذيرات الخطوط. +- الكود الدقيق اللازم **لتحميل مستند Word** مع **إعدادات خطوط** مخصصة. +- كيفية التكرار على كائنات `WarningInfo` لسرد كل خط تم استبداله. +- نصائح لكتم التحذيرات غير المرغوب فيها أو توفير خطوط احتياطية. +- عينة جاهزة للتنفيذ يمكنك نسخها ولصقها في Visual Studio. + +### المتطلبات المسبقة + +- .NET 6.0 أو أحدث (تعمل الواجهة البرمجية بنفس الطريقة على .NET Framework). +- Aspose.Words for .NET (حزمة NuGet `Aspose.Words`). +- ملف Word يحتوي على خط غير مثبت لديك (مثال: `MissingFont.docx`). + +إذا كان لديك هذه المتطلبات، فلنبدأ. + +## الخطوة 1 – تمكين جامع التشخيص (تكوين إعدادات الخطوط) + +أولًا وقبل كل شيء: Aspose.Words يسجل تحذيرات استبدال الخطوط فقط إذا طلبت ذلك. يتم ذلك بإنشاء كائن `FontSettings` وتعيينه إلى مثيل `LoadOptions`. فكر في ذلك كتشغيل “أضواء التصحيح” لمعالجة الخطوط. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**لماذا؟** +بدون كائن `FontSettings` يبقى جامع التحذيرات صامتًا، ولن تعرف أبدًا أي الخطوط تم استبدالها. بتهيئته فارغًا نسمح لـ Aspose باستخدام خطوط النظام الافتراضية *و* تتبع أي استبدالات. + +> **نصيحة احترافية:** إذا كنت تعرف أن مجلدًا معينًا يحتوي على خطوط الشركة، فوجه `FontSettings` إليه باستخدام `SetFontsFolder("path")`. يمكن أن يقلل ذلك من عدد تحذيرات الخطوط المفقودة. + +## الخطوة 2 – تحميل المستند باستخدام الخيارات المكوَّنة (Load Word Document) + +الآن بعد أن تم تفعيل الجامع، قم بتحميل ملف `.docx` الخاص بك باستخدام نفس `LoadOptions`. هذه هي اللحظة التي يقوم فيها Aspose بفحص المستند، والبحث عن كل إشارة إلى خط، وتحديد ما إذا كان هناك حاجة لاستبدال. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**لماذا هذا مهم؟** +إذا قمت ببساطة باستدعاء `new Document("MissingFont.docx")`، فستُطبق الإعدادات الافتراضية *وسيظل* قائمة التحذيرات فارغة. تمرير `loadOptions` يضمن أن جامع التشخيص متصل بعملية تحميل المستند. + +## الخطوة 3 – استرجاع وعرض تحذيرات استبدال الخطوط (اكتشاف الخطوط المفقودة) + +بعد تحميل المستند في الذاكرة، يقوم Aspose بتخزين أي تحذيرات في `document.WarningCallback.Warnings`. قم بالتكرار عبر تلك المجموعة، صَفِّها حسب `WarningType.FontSubstitution`، واطبع الوصف. كل وصف يخبرك أي خط كان مفقودًا وأي خط استُبدل به. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**مخرجات وحدة التحكم المتوقعة** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +تُظهر هذه المخرجات بالضبط أي الخطوط مفقودة على الجهاز الذي يشغل الكود. الآن يمكنك اتخاذ قرار بتثبيت الخطوط المفقودة، أو تضمينها في المستند، أو الإبقاء على الاستبدال. + +![مخرجات وحدة التحكم تُظهر تحذيرات استبدال الخطوط في Aspose](/images/aspose-font-substitution-console.png) + +*نص بديل للصورة:* استبدال الخطوط في Aspose – مخرجات وحدة التحكم التي تسرد الخطوط المستبدلة + +## الخطوة 4 – اختياري: تخصيص سلوك الاستبدال (التعامل مع الخطوط المفقودة) + +أحيانًا لا تريد فقط معرفة *أن* استبدالًا قد حدث—بل تريد التحكم *في كيفية* حدوثه. يتيح لك Aspose.Words تسجيل قاعدة استبدال خطوط مخصصة `IFontSubstitutionRule`. أدناه مثال سريع يجبر أي خط مفقود على الرجوع إلى `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**متى قد تستخدم هذا؟** +إذا كنت تُنشئ ملفات PDF لخدمة ويب وتعلم أن كل عميل يمكنه عرض `Tahoma`، فإن إجبار الرجوع يضمن اتساقًا بصريًا دون الحاجة لإرسال عشرات ملفات الخطوط. + +## مثال كامل يعمل (جميع الخطوات مجمعة) + +إليك البرنامج الكامل الذي يمكنك لصقه في مشروع وحدة تحكم جديد. يتجميع كما هو، بشرط أن تكون قد ثبت حزمة NuGet الخاصة بـ Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +شغّل البرنامج، راقب وحدة التحكم، وسترى كل حدث خط مفقود يُطبع. من هناك يمكنك اتخاذ قرار بتثبيت الخطوط المفقودة، أو تضمينها، أو الإبقاء على الرجوع. + +## الأسئلة المتكررة + +**س: هل يعمل هذا مع تحويل PDF؟** +نعم. عندما تستدعي لاحقًا `doc.Save("output.pdf")`، ستكون أي خطوط تم استبدالها أثناء التحميل هي التي تُضمّن في ملف PDF. لذا فإن التقاط التحذيرات مبكرًا يساعدك على تجنّب تغييرات الخط المفاجئة في PDF النهائي. + +**س: ماذا لو كان لدي العديد من المستندات للمعالجة؟** +قم بلف منطق التحميل داخل كتلة try‑catch وأعد استخدام كائن `FontSettings` واحد عبر المستندات. هذا يقلل من الحمل ويحافظ على نشاط جامع التحذيرات لكل ملف. + +**س: هل يمكنني كتم التحذيرات تمامًا؟** +يمكنك تعيين `loadOptions.WarningCallback = null;` قبل التحميل، لكنك ستفقد القدرة على **اكتشاف الخطوط المفقودة**—وهو عادةً ليس ما تريد. + +## الخلاصة + +لقد غطينا كل ما تحتاجه لإتقان **aspose font substitution**: تمكين جامع التشخيص، تحميل ملف Word بإعدادات **خطوط** مخصصة، استخراج قائمة الخطوط المفقودة، وحتى تجاوز قاعدة الاستبدال الافتراضية لت **التعامل مع الخطوط المفقودة** بطريقتك. ببضع أسطر من C# تحصل على رؤية كاملة لمشكلات الخطوط التي كانت ستختفي خلف تغييرات تخطيطية دقيقة. + +ما الخطوات التالية؟ جرّب تضمين الخطوط الأصلية في المستند باستخدام `FontSettings.SetFontsFolder` أو استكشف `FontSourceBase` لتحميل الخطوط من قاعدة بيانات. يمكنك أيضًا تجربة مجموعة `Document.BuiltInStyle` لمعرفة كيفية انتشار تغييرات الخط على مستوى الأنماط. + +هل لديك المزيد من الأسئلة حول Aspose.Words أو إدارة الخطوط؟ اترك تعليقًا، استكشف وثائق Aspose الرسمية، أو ابدأ مشروعًا جديدًا وجرب الكود أعلاه. برمجة سعيدة، ولتظهر مستنداتك دائمًا كما هو مقصود! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/basic-conversions/_index.md b/words/chinese/net/basic-conversions/_index.md index b1a77577d3..928e7d745a 100644 --- a/words/chinese/net/basic-conversions/_index.md +++ b/words/chinese/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [如何从 Word 导出 LaTeX – 步骤指南](./how-to-export-latex-from-word-step-by-step-guide/) | 学习如何使用 Aspose.Words for .NET 将 Word 文档导出为 LaTeX,提供分步指南和代码示例,帮助开发者实现文档转换。| | [使用 Aspose.Words 将 Word 转换为 PDF(C#)指南](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Word 文档转换为 PDF,提供分步指南和代码示例。| | [使用 Aspose.Words 将 Word 保存为 PDF – 完整 C# 指南](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Word 文档保存为 PDF,提供完整的分步指南和代码示例。| +| [在 C# 中将 Word 转换为 PDF – 完整指南(使用 Aspose.Words)](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | 学习如何使用 Aspose.Words for .NET 在 C# 中将 Word 文档完整转换为 PDF,提供分步指南和代码示例。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/chinese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..69e6305a55 --- /dev/null +++ b/words/chinese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,194 @@ +--- +category: general +date: 2026-04-05 +description: 使用 Aspose.Words 在 C# 中将 Word 转换为 PDF。了解如何将 docx 保存为 PDF、导出可访问的 PDF,以及高效加载 + Word 文档。 +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: zh +og_description: 在 C# 中将 Word 转换为 PDF 的分步指南。了解如何将 docx 保存为 PDF、导出可访问的 PDF,以及使用 Aspose.Words + 加载 Word 文档。 +og_title: 在 C# 中将 Word 转换为 PDF – 完整的 Aspose.Words 教程 +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: 在 C# 中将 Word 转换为 PDF – 使用 Aspose.Words 的完整指南 +url: /zh/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中将 Word 转换为 PDF – 完整编程教程 + +有没有想过如何在不与繁琐的命令行工具或第三方服务斗争的情况下**convert word to pdf**?你并不是唯一有此困惑的人。当客户要求直接从 DOCX 文件生成可访问的 PDF 时,许多开发者都会碰壁。好消息是,只需几行 C# 代码和强大的 Aspose.Words 库,你就能瞬间将 Word 文档转换为符合标准的 PDF。 + +在本指南中,我们将逐步讲解你需要了解的全部内容:从 **load word document** 基础、配置正确的选项以实现 **how to export accessible pdf**,以及最终保存结果,使你能够可靠地 **save docx as pdf**。完成后,你将拥有一个可直接运行的代码片段,能够嵌入任何 .NET 项目中。 + +> **Pro tip:** 如果你需要满足 PDF/UA‑2 合规性(许多政府机构要求的可访问性标准),相同的代码即可工作,无需额外步骤——只需设置正确的 `PdfCompliance` 标志。 + +## 你将学到的内容 + +- 如何在 C# 中使用 Aspose.Words **load word document**。 +- 实现 **how to export accessible pdf**(PDF/UA‑2)所需的精确设置。 +- 一个完整且可运行的示例,使用一次方法调用即可 **save docx as pdf**。 +- 常见陷阱:当你 **c# convert docx pdf** 时以及如何避免它们。 +- 快速验证生成的 PDF 是否符合可访问性期望的方法。 + +无需外部工具,也不需要晦涩的配置文件——只需纯 C# 代码,今天即可编译。 + +## 先决条件 + +在深入之前,请确保你已经拥有: + +1. **.NET 6.0**(或任何近期的 .NET 版本)已安装。旧版框架也可使用,但下面的语法假设使用现代 SDK。 +2. Aspose.Words for .NET 的 **license**。该库提供免费试用,但在生产环境中需要有效的密钥。 +3. 已在项目中添加 **Aspose.Words** NuGet 包: + +```bash +dotnet add package Aspose.Words +``` + +就这些——无需额外的二进制文件、无需 COM 互操作,只需一个干净的 NuGet 引用。 + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## 分步实现 + +下面我们将过程拆分为逻辑块。每一步都包含一个小代码片段、对 **why** 重要性的解释,以及来自实际使用的提示。 + +### ## 将 Word 转换为 PDF – 加载源文档 + +你需要做的第一件事是将 **load word document** 加载到内存中。Aspose.Words 抽象了 OpenXML 解析,你可以处理 DOCX、DOC,甚至 RTF 文件,而无需担心格式细节。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**为什么这很重要:** +加载文件会创建一个 `Document` 对象,代表整个 Word 文件,包括页眉、页脚、样式和隐藏的元数据。如果跳过此步骤或尝试将文件作为原始流读取,你将失去后续决定 PDF 外观的布局信息。 + +> **Side note:** 同一个 `Document` 构造函数同样适用于 `.doc` 和 `.rtf`。这意味着即使源文件不是严格的 DOCX,你也可以 **c# convert docx pdf**。 + +### ## 将 DOCX 保存为 PDF – 配置 PDF/UA‑2 合规性 + +现在文档已在内存中,我们告诉 Aspose.Words 我们希望如何生成 PDF。对于大多数用例,默认设置已经足够,但当你需要 **accessible PDF** 时,必须启用 PDF/UA‑2 合规标志。 + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**为什么这很重要:** +`PdfCompliance.PdfUAXmpA2` 告诉库嵌入屏幕阅读器所依赖的必要标签和结构。如果不设置此标志,可能会得到外观完美的 PDF,却在可访问性审计中失败。 + +> **Tip:** 如果只需要普通 PDF,你可以去掉 `Compliance` 行。其余选项仍然可以生成高质量的输出。 + +### ## 将 Word 转换为 PDF – 写入文件 + +准备好选项后,最后一步是 **save docx as pdf**。这一次调用完成所有繁重工作:布局转换、字体嵌入以及可访问性标签。 + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**你将得到:** +- 位于 `outputPath` 的 PDF 文件,其布局与 Word 完全一致。 +- 如果使用了 `PdfUAXmpA2` 标志,PDF 将标记为符合 PDF/UA‑2。 +- 所有字体均已嵌入,文件在任何机器上显示效果相同。 + +### ## 验证可访问的 PDF(可选但推荐) + +转换后,最好再次确认 PDF 是否真的正确 **how to export accessible pdf**。你可以使用免费工具,例如 Adobe Acrobat Reader 的 “Accessibility Check” 或开源的 `pdfcpu` 验证器。 + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +如果验证器未报告错误,则表示你已成功 **convert word to pdf**,并具备完整的可访问性支持。 + +### ## 当你 C# 将 DOCX 转换为 PDF 时的常见陷阱 + +| 问题 | 原因 | 解决方案 | +|------|------|----------| +| 缺少字体 | 源 DOCX 使用了服务器上未安装的自定义字体。 | 设置 `EmbedFullFonts = true` 或在机器上安装该字体。 | +| 文件体积大 | 图像以完整分辨率嵌入。 | 使用 `ImageCompression = PdfImageCompression.Jpeg` 并将 `JpegQuality` 设置为较低的值。 | +| 超链接失效 | 链接指向客户端不存在的相对路径。 | 确保 URL 为绝对路径,或调整 `HyperlinkTarget` 属性。 | +| 缺少可访问性标签 | `Compliance` 标志未设置。 | 如上所示,添加 `Compliance = PdfCompliance.PdfUAXmpA2`。 | + +牢记这些要点,将使你的 **c# convert docx pdf** 过程更加稳健,适合生产环境。 + +## 完整工作示例 + +将所有内容整合在一起,下面是一个可自行编译运行的完整控制台应用程序。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** 运行程序后,你将在 `C:\Docs` 中找到 `output.pdf`。在任意 PDF 查看器中打开,布局应与 `input.docx` 完全一致,并且可访问性检查将确认符合 PDF/UA‑2。 + +## 结论 + +我们刚刚完整演示了使用 C# 和 Aspose.Words 将 **convert word to pdf** 的端到端解决方案。通过 **load word document**、配置正确的 `PdfSaveOptions`,最后 **save docx as pdf**,你可以用最少的代码生成高质量、可访问的 PDF。无论你是在构建文档生成微服务,还是本地批量转换器, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-markdownsaveoptions/_index.md b/words/chinese/net/programming-with-markdownsaveoptions/_index.md index 5c051cfedf..e232191db6 100644 --- a/words/chinese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/chinese/net/programming-with-markdownsaveoptions/_index.md @@ -26,6 +26,7 @@ | [如何使用 Markdown:将 DOCX 转换为带 LaTeX 方程的 Markdown](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) 使用 Aspose.Words for .NET 将 DOCX 文档转换为包含 LaTeX 方程的 Markdown,提供完整示例和步骤。| | [将 docx 转换为 markdown – 步骤详解 C# 指南](./convert-docx-to-markdown-step-by-step-c-guide/) 使用 Aspose.Words for .NET 将 docx 文档转换为 Markdown,提供完整示例和分步指南。| | [将 docx 保存为 markdown – 完整 C# 指南(含 LaTeX 方程)](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) 使用 Aspose.Words for .NET 将 docx 文档保存为 Markdown,包含 LaTeX 方程,提供完整示例和分步指南。| +| [将 DOCX 转换为 Markdown – 从 DOCX 提取图像(使用 Aspose.Words)](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) 使用 Aspose.Words for .NET 将 DOCX 文档转换为 Markdown,并提取嵌入的图像,提供完整示例和分步指南。| ### [将 Word 保存为 PDF 并恢复损坏的 Word – 在 C# 中将 Word 转换为 Markdown](./save-word-as-pdf-and-recover-corrupted-word-convert-word-to/) @@ -51,6 +52,10 @@ 使用 Aspose.Words for .NET 将 DOCX 文档导出为 Markdown,提供完整的 C# 示例和分步指南。 +### [将 Word 转换为 Markdown – 完整指南(含 PDF/UA 导出)](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) + +使用 Aspose.Words for .NET 将 Word 文档转换为 Markdown,并导出符合 PDF/UA 标准的 PDF,提供完整示例和分步指南。 + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/chinese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..c967a9d584 --- /dev/null +++ b/words/chinese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-04-05 +description: 学习如何在 C# 中将 DOCX 转换为 Markdown 并从 DOCX 中提取图像。一步步指南,附完整代码和技巧。 +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: zh +og_description: 使用 Aspose.Words 将 DOCX 转换为 Markdown 并提取 DOCX 中的图像。完整的 C# 教程,包含代码、说明和最佳实践技巧。 +og_title: 将 DOCX 转换为 Markdown – 在 C# 中从 DOCX 提取图片 +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: 将 DOCX 转换为 Markdown – 使用 Aspose.Words 从 DOCX 提取图像 +url: /zh/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 DOCX 转换为 Markdown – 从 DOCX 中提取图片(C#) + +是否曾经**将 DOCX 转换为 Markdown**却苦恼于图片在输出中消失?你并非唯一。很多项目中,Markdown 版非常适合版本控制或静态站点生成器,但图片却被遗漏,使得原本丰富的文档变成了枯燥的文本文件。 + +好消息是,只需几行 C# 代码和 Aspose.Words,你就可以**将 DOCX 转换为 Markdown** *并且* **自动从 DOCX 中提取图片**。本指南将完整演示整个过程,解释每一步的意义,并展示如何保持图片文件夹整洁。 + +## 你将学到 + +- 如何加载包含图片的 DOCX。 +- 如何定义自定义 `IResourceSavingCallback` 来决定每张图片的保存位置。 +- 如何配置 `MarkdownSaveOptions`,让生成的 Markdown 正确引用提取出的图片。 +- 处理重复图片名称或非 PNG 格式等边缘情况的技巧。 +- 一个完整的、可直接复制粘贴运行的代码示例。 + +### 前置条件 + +- .NET 6.0 或更高(API 在 .NET Core、.NET Framework 和 .NET 5+ 上均可运行)。 +- **Aspose.Words for .NET** 授权(免费试用版可用于测试)。 +- 基本的 C# 与 Visual Studio(或你喜欢的 IDE)使用经验。 + +如果你满足以上条件,下面开始吧。 + +--- + +## 第一步:创建项目并安装 Aspose.Words + +首先,新建一个控制台应用(或在已有解决方案中集成)。 + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **小贴士:** 使用最新的 NuGet 版本(截至 2026 年 4 月为 24.12),可获得最新的 Markdown 导出改进。 + +--- + +## 第二步:创建回调以将图片保存到指定位置 + +Aspose.Words 允许在 Markdown 导出过程中拦截每个资源(图片、SVG 等)。实现 `IResourceSavingCallback` 后,你可以: + +1. 选择一个与 Markdown 文件同级的文件夹。 +2. 生成唯一的文件名(避免覆盖已有图片)。 +3. 决定保存格式(这里统一为 PNG 以保持一致性)。 + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### 为什么使用基于 GUID 的名称? + +如果源 DOCX 中有两张图片的原始名称相同,直接复制粘贴会导致其中一张被覆盖。使用 `Guid.NewGuid()` 能保证唯一性,特别适合在自动化流水线中多次运行转换时使用。 + +--- + +## 第三步:加载 DOCX 并配置 Markdown 选项 + +现在把文档加载到内存,并挂载刚才创建的回调。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### 代码逐步说明 + +| 步骤 | 目的 | +|------|------| +| **定义路径** | 让项目更灵活;无需重新编译即可指向任意文件夹。 | +| **加载 DOCX** | `Document` 解析 Word 文件,使所有元素(段落、表格、图片)可访问。 | +| **配置 `MarkdownSaveOptions`** | `ResourceSavingCallback` 是提取图片的钩子。若不设置,Aspose.Words 会将图片嵌入为 base64 字符串或直接丢弃,取决于设置。 | +| **保存** | `doc.Save` 写入 Markdown 文件,并为每张图片触发回调。 | + +--- + +## 第四步:验证输出 – 你应该看到什么? + +运行程序后,打开 `DocWithImages.md`。你会看到类似下面的 Markdown 图片链接: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +在 `C:\Docs\MarkdownResources` 中,你会找到一系列以 GUID 命名的 PNG 文件。打开任意一个,它们应与原始 DOCX 中嵌入的图片完全相同。 + +如果在支持相对路径的查看器中打开(例如 VS Code 预览、GitHub 或静态站点生成器),图片会像在 Word 中一样渲染。 + +### 常见问题及规避方法 + +| 症状 | 可能原因 | 解决办法 | +|------|----------|----------| +| 图片显示为失效链接 | `ResourceFileName` 未设置,导致 Markdown 指向了不存在的文件。 | 在回调中确保 `args.ResourceFileName = newFileName;` | +| PNG 文件体积过大 | 原始图片为 JPEG 或 BMP,转换为 PNG 会增大体积。 | 通过 `args.ResourceContentType` 检测原始格式并保留:`args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| 仍出现重复图片 | 使用了静态文件名而非 GUID。 | 恢复 GUID 逻辑或为每种图片类型添加计数器。 | +| 转换抛出 `FileNotFoundException` | DOCX 路径错误或文件夹缺少读取权限。 | 检查路径并授予相应的文件系统权限。 | + +--- + +## 第五步:高级调优(可选) + +### 5.1 保持原始图片格式 + +如果希望输出图片保留原始扩展名,可修改回调: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 将图片嵌入为 Base64(当你*不*想要单独文件时) + +有时单文件 Markdown 更方便(例如通过邮件发送)。修改选项: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +但请记住:对大多数静态站点工作流而言,**从 DOCX 中提取图片** 是主要目标,文件夹方式通常更合适。 + +--- + +## 完整可运行示例(复制粘贴即可) + +下面是一整个文件的完整程序。只需替换为自己的路径后运行。 + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +使用 `dotnet run` 执行。当控制台打印出 ✅ 行时,打开 Markdown 文件,你应能看到图片正确渲染。 + +--- + +## 结论 + +现在你拥有一个**完整、可投入生产的解决方案**,使用 Aspose.Words 在 C# 中**将 DOCX 转换为 Markdown 并提取图片**。本文的关键词在整个指南中多次出现,提升了对搜索引擎和 AI 助手的相关性。 + +代码一次性完成以下工作: + +1. 加载 Word 文档。 +2. 通过 `IResourceSavingCallback` 拦截每张图片。 +3. 将每张图片保存到可预测的文件夹并使用唯一名称。 +4. 生成引用这些图片的 Markdown。 + +接下来你可以: + +- 将 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/chinese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..cf9f311aa2 --- /dev/null +++ b/words/chinese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-05 +description: 快速将 Word 转换为 Markdown,并学习如何在 C# 中保存为 PDF/UA。一步一步的代码、技巧和边缘情况处理。 +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: zh +og_description: 使用 Aspose.Words 将 Word 转换为 Markdown 并保存为 PDF/UA。了解原因、方法以及最佳实践技巧,一站式简明指南。 +og_title: 将 Word 转换为 Markdown – 完整 C# 教程 +tags: +- Aspose.Words +- C# +- Document Conversion +title: 将 Word 转换为 Markdown – 完整指南(含 PDF/UA 导出) +url: /zh/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 Word 转换为 Markdown – 完整指南及 PDF/UA 导出 + +是否曾想过 **将 Word 转换为 Markdown** 时不丢失公式或图片?你并不是唯一的需求者。许多开发者需要一种可靠的方法,将 `.docx` 文件转换为干净的 Markdown,同时还能 **保存为 PDF/UA** 以生成符合可访问性标准的 PDF。在本教程中,我们将逐步演示一个完整、可直接运行的解决方案,使用 Aspose.Words for .NET,解释每个设置的意义,并展示如何处理诸如 OfficeMath 和浮动形状等更棘手的部分。 + +阅读完本指南后,你将拥有一个 C# 程序,能够: + +1. 使用宽松恢复模式加载 Word 文档(即使文件损坏也不会中断运行)。 +2. 导出为 Markdown,将公式转换为 LaTeX,并通过自定义回调保存图片。 +3. 将同一文档保存为符合 PDF/UA‑2 标准的文件,并将浮动形状嵌入为内联标签。 + +听起来很多?别担心——让我们开始吧。 + +## 你需要的准备 + +- **Aspose.Words for .NET**(撰写时的最新版本 23.x)。 +- .NET 开发环境(Visual Studio 2022、Rider,或 `dotnet` CLI)。 +- 一个示例 Word 文件(`input.docx`),放置在可引用的文件夹中。 +- 对 C# 语法的基本了解——不需要高级技巧,只需几个 `using` 语句。 + +> **小贴士:** 如果使用 NuGet 包管理器,可通过以下方式添加库 +> `dotnet add package Aspose.Words` 或在 Visual Studio 的 NuGet UI 中操作。 + +## 第 1 步 – 使用宽松恢复模式加载 Word 文档 + +当你从外部获取 Word 文件时,可能会包含轻微的损坏。启用 **Relaxed** 恢复模式可让 Aspose.Words 继续处理,而不是抛出异常。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**为何重要:** +- `RecoveryMode.Relaxed` 可防止单个格式错误的段落导致整个转换中止。 +- 提供 `FontSettings` 对象可确保缺失的字体被优雅地替代,这在后续将公式渲染为 LaTeX 时至关重要。 + +## 第 2 步 – 导出为 Markdown(OfficeMath → LaTeX,图片通过回调) + +Markdown 本身没有原生方式表示 Word 公式。Aspose.Words 能将 **OfficeMath** 对象转换为 LaTeX,绝大多数 Markdown 渲染器都能识别。图片则需要保存到某处;自定义 **资源保存回调** 让你完全掌控文件夹结构和命名方式。 + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### 资源保存回调 + +下面是一个简短实现,它会将每张图片存入名为 `images` 的子文件夹,并使用 `img001.png`、`img002.png` 等名称。 + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**为何需要此回调:** +- 若不使用回调,Aspose.Words 会在平面文件夹中生成随机 GUID 名称的文件,这会让版本控制变得混乱。 +- 通过自行控制命名规则,你可以保持 Markdown 仓库的整洁与可复现性。 + +### 预期的 Markdown 输出 + +运行后打开 `doc.md`,你会看到: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +公式会以 `$$ … $$` 包裹的 LaTeX 形式出现,图片则引用你刚创建的 `images` 文件夹。 + +## 第 3 步 – 导出为 PDF/UA‑2(可访问性就绪) + +如果需要将文档分享给依赖屏幕阅读器或其他辅助技术的用户,**PDF/UA‑2** 合规是金标准。Aspose.Words 只需一个标志即可强制执行,同时还能将浮动形状展平为内联标签,防止在转换过程中丢失。 + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**为何 PDF/UA 重要:** +- PDF/UA(通用可访问性)确保生成的 PDF 包含正确的标签、逻辑阅读顺序以及图片的替代文字。 +- 设置 `ExportFloatingShapesAsInlineTag` 可避免文本框或标注等形状被省略或错位——这是转换复杂布局时的常见陷阱。 + +### 验证 PDF/UA 合规性 + +导出后,在 Adobe Acrobat Pro 中打开 PDF,运行 **“Accessibility Check”**(工具 → 可访问性 → 完整检查)。若工具报告 **0 错误**,则说明成功。 + +## 边缘情况与常见陷阱 + +| 场景 | 需要注意的点 | 解决方案 / 建议 | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word 文件包含 **不受支持的字体** | 字体可能被替代,导致公式布局错乱 | 提供自定义 `FontSettings` 并配置回退字体。 | +| 大文档(> 100 MB) | 转换期间内存压力增大 | 使用 `LoadOptions` 并指定 `LoadFormat.Docx`,通过流读取文件。 | +| 图片为 **EMF/WMF** 矢量图 | 可能被意外栅格化 | 在保存前使用 `ImageSaveOptions` 将其转换为 PNG。 | +| PDF/UA 在 **嵌套表格** 上验证失败 | 标记可能出现歧义 | 启用 `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` 以帮助引擎。 | +| 需要 **保留自定义样式** | Markdown 的样式能力有限 | 同时导出 CSS 文件并在 Markdown 中引用。 | + +## 完整工作示例(全部代码合并) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +运行程序后,你将在 `YOUR_DIRECTORY` 中看到 `doc.md`(包含 LaTeX 公式和整洁的图片链接)以及 `doc.pdf`(完全符合 PDF/UA‑2 标准)。 + +## 可视化概览 + +![将 Word 转换为 Markdown 示例](https://example.com/placeholder.png "将 Word 转换为 Markdown 示例 – 展示输入 Word、Markdown 输出以及 PDF/UA 文件") + +*替代文字:* **将 Word 转换为 Markdown 示例** – 展示从 Word 文件到 Markdown 和 PDF/UA 的转换流程图。 + +## 小结与后续步骤 + +我们已经 **将 Word 转换为 Markdown**,保持了公式完整,将图片整齐存放,并生成了通过可访问性检查的 **PDF/UA** 文件。关键要点如下: + +- 使用 `LoadOptions.RecoveryMode.Relaxed` 容忍不完美的 Word 文件。 +- 将 `OfficeMathExportMode` 设置为 `LaTeX` 以获得干净的公式渲染。 +- 实现 `ResourceSavingCallback` 来控制图片输出。 +- 启用 `PdfCompliance.PdfUAXmpA2` 与 `ExportFloatingShapesAsInlineTag` 以生成符合标准的 PDF。 + +### 接下来可以探索的方向? + +- **Markdown 的自定义 CSS** – 生成与 Word 样式相匹配的样式表。 +- **批量处理** – 循环遍历目录下的 `.docx` 文件,实现大规模迁移。 +- **高级 PDF/UA 功能** – 添加自定义标签、设置语言属性或嵌入音频描述。 +- **CI/CD 集成** – 确保每次构建都自动生成可访问的 PDF。 + +如果遇到问题,请再次确认你的 Aspose.Words 版本与本文使用的 API 相匹配,并记得库的官方文档是极好的补充参考。 + +祝编码愉快,愿你的文档既美观 **又** 可访问! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/programming-with-txtsaveoptions/_index.md b/words/chinese/net/programming-with-txtsaveoptions/_index.md index 77cad7f527..e1c000cf59 100644 --- a/words/chinese/net/programming-with-txtsaveoptions/_index.md +++ b/words/chinese/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Aspose.Words for .NET 教程将引导您了解该库在处理 Word 文档方面 | [在 Word 文档中添加双向标记](./add-bidi-marks/) 本指南将指导您如何使用 Aspose.Words for .NET 在 Word 文档中添加双向 (Bidi) 标记。确保多语言内容的文本方向正确。| | [每级使用制表符进行列表缩进](./use-tab-character-per-level-for-list-indentation/) 了解如何使用 Aspose.Words for .NET 创建带有制表符缩进的多级列表。请遵循本指南,在文档中设置精确的列表格式。| | [每级使用空格字符进行列表缩进](./use-space-character-per-level-for-list-indentation/) 了解如何在 Aspose.Words for .NET 中创建带有空格字符缩进的多级列表。精确文档格式的分步指南。| - +| [将 docx 保存为 txt – 使用 C# 将 Word 方程导出为 LaTeX](./save-docx-as-txt-export-word-equations-to-latex-with-c/) 本教程演示如何使用 Aspose.Words for .NET 将 Word 文档中的公式导出为 LaTeX,并保存为 txt 文件。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/chinese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..6fa937fce7 --- /dev/null +++ b/words/chinese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-04-05 +description: 使用 Aspose.Words 将 docx 保存为 txt —— 快速将 Word 转换为 txt,并了解如何将数学公式导出为 LaTeX。简单的 + C# 代码,无需额外工具。 +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: zh +og_description: 在 C# 中将 docx 保存为 txt 并了解如何将数学公式导出为 LaTeX。请按照本分步指南,将 Word 转换为 txt,保留公式。 +og_title: 将 docx 保存为 txt – 将 Word 方程导出为 LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: 将 docx 保存为 txt – 使用 C# 将 Word 方程导出为 LaTeX +url: /zh/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 docx 保存为 txt – 使用 C# 将 Word 方程导出为 LaTeX + +是否曾经需要 **save docx as txt**,但又担心公式会消失或变成不可读的乱码?你并不是唯一遇到这种情况的人。许多开发者在尝试 **convert word to txt** 进行下游处理时,尤其是源文件包含 Office Math 对象时,都会碰到这个难题。 + +好消息是?只需几行 C# 代码并使用正确的选项,你不仅可以 **convert Word to txt**,还能将每个公式保留为干净的 LaTeX 标记。在本教程中,我们将完整演示整个过程,解释每个设置为何重要,并展示如何验证结果。 + +我们将覆盖: + +* 安装 Aspose.Words for .NET 库 +* 加载包含数学公式的 `.docx` 文件 +* 配置 `TxtSaveOptions` 使 **how to export math** 成为 LaTeX 友好的字符串 +* 保存文件并检查输出 + +完成后,你将拥有一个可复用的代码片段,能够 **save docx as txt** 的同时将所有公式保留为 LaTeX——这对于科学流水线、静态站点生成器或任何需要纯文本数学的工作流都非常适用。 + +--- + +## Prerequisites + +在开始之前,请确保你具备: + +* .NET 6.0 或更高版本(该代码同样适用于 .NET Framework 4.6+) +* Visual Studio 2022(或你喜欢的任何 IDE) +* **Aspose.Words for .NET** NuGet 包 – 使用以下命令安装 + +```bash +dotnet add package Aspose.Words +``` + +不需要额外的转换器或外部工具;Aspose.Words 在内部完成所有繁重工作。 + +--- + +## Step 1: Install and reference Aspose.Words + +首先,将库添加到你的项目中。如果使用命令行,运行上面的命令。在 Visual Studio 中,你也可以右键点击 **Dependencies → Manage NuGet Packages** 并搜索 *Aspose.Words*。 + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** 使用最新的稳定版本(截至 2026 年 4 月为 24.10)。新版本修复了 OfficeMath 处理的 bug,能够避免意外的符号缺失。 + +--- + +## Step 2: Load the source document + +现在读取包含你想保留的公式的 `.docx`。`Document` 类抽象了整个 Word 文件,提供对文本、图像和 Office Math 对象的访问。 + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +为什么要先加载?Aspose.Words 会将文件解析为对象模型,使我们能够在决定导出方式之前检查或修改内容。这正是 **how to export math** 决策开始发挥作用的地方。 + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +解决方案的核心是 `TxtSaveOptions` 类。默认情况下,保存为 TXT 会完全剥离 Office Math。将 `OfficeMathExportMode` 设置为 `LaTeX`,即可让库将每个公式翻译为其 LaTeX 表示。 + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX 是科学出版的通用语言。以这种方式导出数学,你保留了公式的语义,而不是平面图像或乱码字符串。如果之后将 TXT 输入支持 MathJax 的 Markdown 处理器,公式将能够完美渲染。 + +--- + +## Step 4: Save the document as plain‑text + +配置好选项后,最后一步只需一行代码即可将文件写入磁盘。 + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +就这么简单——你的 `.docx` 现在已经变成 `.txt`,其中每个公式都以 LaTeX 代码片段的形式出现,随时可供下游使用。 + +--- + +## Verifying the output (How to save txt correctly) + +在任意文本编辑器中打开 `MathSample.txt`。你应该会看到类似下面的内容: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +如果发现原始 Word 特有的字符(例如 `?` 或缺失的符号),请检查以下事项: + +* 确认使用的是最近的 Aspose.Words 版本(旧版本在 OfficeMath 上存在 bug)。 +* 确认源文档实际包含 **OfficeMath** 对象,而非旧版 Equation Editor 对象。对于后者,可能需要手动转换或在保存前调用 `ConvertMathToOfficeMath` 方法。 + +--- + +## Common Variations & Edge Cases + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** objects | 在第 3 步之前调用 `doc.ConvertMathToOfficeMath()`。 | +| **You need plain Unicode math, not LaTeX** | 将 `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`。 | +| **Large documents (100 + MB)** | 使用 `doc.Save(Stream, txtOptions)` 进行流式保存,以避免高内存占用。 | +| **You want to keep the original file name** | 在构建输出路径时使用 `Path.GetFileNameWithoutExtension(inputPath) + ".txt"`。 | + +这些调整针对不同流水线中的 “**how to export math**” 问题提供了解决方案,确保你的方案在任何来源下都能稳健运行。 + +--- + +## Full Working Example (All steps in one place) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +运行程序,打开生成的 `.txt`,你会看到 LaTeX 公式正好嵌入在它们原本所在的位置。这是最直接的 **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/chinese/net/working-with-fonts/_index.md b/words/chinese/net/working-with-fonts/_index.md index 4edfb64b65..6f25042c37 100644 --- a/words/chinese/net/working-with-fonts/_index.md +++ b/words/chinese/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ | [接收警告通知](./receive-warning-notification/) 了解如何在使用 Aspose.Words for .NET 时接收警告通知并管理文档中的任何问题或警告。| | [资源 Steam 字体源示例](./resource-steam-font-source-example/) 了解如何使用资源流字体源将自定义字体加载到 Aspose.Words for .NET 中。| | [获取不带后缀的替换](./get-substitution-without-suffixes/) 在本教程中,学习如何使用 Aspose.Words for .NET 在 Word 文档中获取无后缀覆盖。| - +| [Aspose 字体替换 – 检测 Word 文档中缺失的字体](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) 通过分步指南了解如何使用 Aspose.Words for .NET 检测 Word 文档中缺失的字体并进行替换。| {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/chinese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/chinese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..671726bbb4 --- /dev/null +++ b/words/chinese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-04-05 +description: Aspose 字体替换指南:在加载 Word 文档时检测缺失的字体。学习如何配置字体设置并高效处理缺失的字体。 +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: zh +og_description: Aspose 字体替换指南,帮助在加载 Word 文档时检测缺失的字体。了解如何配置字体设置并高效处理缺失的字体。 +og_title: Aspose 字体替换 – 检测 Word 文档中缺失的字体 +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose 字体替换 – 检测 Word 文档中缺失的字体 +url: /zh/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose 字体替换 – 检测 Word 文档中的缺失字体 + +是否遇到过同一个 Word 文件在一台机器上显示完美,而在另一台机器上出现奇怪的字体变化?这就是经典的 **aspose font substitution** 问题,通常意味着目标系统缺少某些字体。在本教程中,我们将一步步演示如何在 **加载 Word 文档** 时 **检测缺失的字体**,如何 **配置字体设置**,以及如何优雅地 **处理缺失字体**。 + +我们将通过一个完整、可运行的 C# 示例,解释每行代码的意义,并展示你应该看到的控制台输出。完成后,你将能够在文档加载的瞬间发现字体替换——无需猜测。 + +## 你将学到 + +- 如何为 Aspose.Words 启用字体警告的诊断收集器。 +- 加载带有自定义 **字体设置** 的 **Word 文档** 所需的完整代码。 +- 如何遍历 `WarningInfo` 对象列出每个被替换的字体。 +- 抑制不需要的警告或提供回退字体的技巧。 +- 一个可直接复制到 Visual Studio 的即用示例。 + +### 前置条件 + +- .NET 6.0 或更高版本(API 在 .NET Framework 上表现相同)。 +- Aspose.Words for .NET(NuGet 包 `Aspose.Words`)。 +- 一个引用了你未安装的字体的 Word 文件(例如 `MissingFont.docx`)。 + +如果你满足以上条件,下面开始吧。 + +## 步骤 1 – 启用诊断收集器(配置字体设置) + +首先:只有在告诉 Aspose.Words 时,它才会记录字体替换警告。这通过创建 `FontSettings` 对象并将其分配给 `LoadOptions` 实例来实现。可以把它想象成为字体处理打开了“调试灯”。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**为什么要这样做?** +如果没有 `FontSettings` 对象,警告收集器会保持沉默,你永远不知道哪些字体被替换了。通过初始化为空,我们让 Aspose 使用默认系统字体 *并* 跟踪所有替换。 + +> **专业提示:** 如果你知道某个文件夹中包含公司字体,可使用 `SetFontsFolder("path")` 将 `FontSettings` 指向该文件夹。这可以减少缺失字体警告的数量。 + +## 步骤 2 – 使用配置好的选项加载文档(加载 Word 文档) + +收集器激活后,使用相同的 `LoadOptions` 加载 `.docx` 文件。这时 Aspose 会扫描文档,查找每个字体引用,并决定是否需要替换。 + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**这有什么意义?** +如果你仅调用 `new Document("MissingFont.docx")`,默认设置会生效,但警告列表将保持为空。传入 `loadOptions` 能确保诊断收集器已挂接到加载流水线。 + +## 步骤 3 – 获取并显示字体替换警告(检测缺失字体) + +文档加载到内存后,Aspose 会将所有警告存放在 `document.WarningCallback.Warnings` 中。遍历该集合,筛选出 `WarningType.FontSubstitution`,并打印描述。每条描述都会告诉你缺失的字体以及使用的替代字体。 + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**预期的控制台输出** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +该输出精准列出了运行代码的机器上缺失的字体。接下来,你可以决定是安装缺失的字体、将其嵌入文档,还是保留替代方案。 + +![控制台输出显示 aspose 字体替换警告](/images/aspose-font-substitution-console.png) + +*图片替代文字:aspose 字体替换 – 控制台输出列出被替换的字体* + +## 步骤 4 – 可选:自定义替换行为(处理缺失字体) + +有时你不仅想知道 *发生了* 替换,还想控制 *如何* 替换。Aspose.Words 允许你注册自定义的 `IFontSubstitutionRule`。下面的示例强制所有缺失的字体回退到 `Tahoma`。 + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**何时使用此方式?** +如果你为 Web 服务生成 PDF,并且知道所有客户端都能渲染 `Tahoma`,强制回退可以保证视觉一致性,而无需分发大量字体文件。 + +## 完整可运行示例(所有步骤合并) + +以下是可以直接粘贴到新控制台项目中的完整程序。只要安装了 Aspose.Words NuGet 包,即可直接编译运行。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +运行程序,观察控制台,你将看到每个缺失字体事件的打印。随后,你可以决定是安装缺失的字体、将其嵌入,还是保持回退。 + +## 常见问题 + +**问:这在 PDF 转换时也有效吗?** +是的。当你随后调用 `doc.Save("output.pdf")` 时,加载期间被替换的字体会被嵌入到 PDF 中。因此提前捕获警告可以避免最终 PDF 出现意外的字体变化。 + +**问:如果要处理大量文档怎么办?** +将加载逻辑放在 try‑catch 块中,并在多个文档之间复用同一个 `FontSettings` 实例。这样可以降低开销,并保持每个文件的警告收集器处于激活状态。 + +**问:能完全抑制警告吗?** +可以在加载前设置 `loadOptions.WarningCallback = null;`,但这样会失去 **检测缺失字体** 的能力——通常这不是你想要的。 + +## 结论 + +我们已经覆盖了掌握 **aspose font substitution** 所需的全部内容:启用诊断收集器、使用自定义 **字体设置** 加载 Word 文件、提取缺失字体列表,以及通过自定义替换规则 **处理缺失字体**。只需几行 C# 代码,你就能完整地看到那些原本隐藏在细微布局变化背后的字体问题。 + +下一步?尝试使用 `FontSettings.SetFontsFolder` 将原始字体嵌入文档,或探索 `FontSourceBase` 从数据库加载字体。你也可以实验 `Document.BuiltInStyle` 集合,观察样式层级的字体变化如何传播。 + +对 Aspose.Words 或字体管理还有其他疑问?欢迎留言,查阅官方 Aspose 文档,或新建项目亲自试验上面的代码。祝编码愉快,愿你的文档始终如你所愿地渲染! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/basic-conversions/_index.md b/words/czech/net/basic-conversions/_index.md index 923bae116a..7e40669917 100644 --- a/words/czech/net/basic-conversions/_index.md +++ b/words/czech/net/basic-conversions/_index.md @@ -23,18 +23,19 @@ Základní konverze vás provede základními konverzemi dokumentů pomocí knih | --- | --- | | [Převod Doc do Docx](./doc-to-docx/) | Naučte se, jak převést DOC do DOCX pomocí Aspose.Words pro .NET. Podrobný návod s příklady kódu. Ideální pro vývojáře. | | [Převod Docx do RTF](./docx-to-rtf/) | Naučte se, jak převést DOCX do RTF pomocí Aspose.Words pro .NET s naším podrobným návodem. Snadná konverze pro bezproblémové zpracování dokumentů. | -| [Převod souboru Wordu do PDF](./docx-to-pdf/) Naučte se, jak snadno převést soubory Wordu do PDF pomocí Aspose.Words pro .NET s naším průvodcem. Ideální pro vývojáře, kteří hledají rychlý a spolehlivý převod dokumentů. | +| [Převod souboru Wordu do PDF](./docx-to-pdf/) | Naučte se, jak snadno převést soubory Wordu do PDF pomocí Aspose.Words pro .NET s naším průvodcem. Ideální pro vývojáře, kteří hledají rychlý a spolehlivý převod dokumentů. | | [Převést Docx na bajty](./docx-to-byte/) | Naučte se, jak převést Docx do bajtového pole v .NET pomocí Aspose.Words pro efektivní zpracování dokumentů. Součástí je podrobný návod. | | [Převod Docx do Epub](./docx-to-epub/) | Snadno převeďte DOCX do EPUB s Aspose.Words pro .NET. Postupujte podle našeho návodu pro bezproblémovou integraci do vašich .NET aplikací. | | [Převod Docx do Mhtml a odesílání e-mailů](./docx-to-mhtml-and-sending-email/) | Naučte se v tomto podrobném návodu, jak převést DOCX do MHTML a odesílat e-maily pomocí Aspose.Words pro .NET. Zvyšte svou produktivitu snadnou automatizací. | | [Převod souboru DOCX do formátu Markdown](./docx-to-markdown/) | Naučte se, jak převést soubory DOCX do Markdownu pomocí Aspose.Words pro .NET. Postupujte podle našeho podrobného návodu pro bezproblémovou integraci do vašich .NET aplikací. | -| [Převod Docx do Txt](./docx-to-txt/) Převeďte DOCX do TXT pomocí Aspose.Words pro .NET s naším podrobným návodem. Naučte se transformovat dokumenty efektivně a bez námahy. | +| [Převod Docx do Txt](./docx-to-txt/) | Převeďte DOCX do TXT pomocí Aspose.Words pro .NET s naším podrobným návodem. Naučte se transformovat dokumenty efektivně a bez námahy. | | [Převod textového souboru do dokumentu Word](./txt-to-docx/) | Naučte se, jak převádět textové soubory do dokumentů Wordu pomocí Aspose.Words pro .NET. Efektivně spravujte převody dokumentů s naším komplexním průvodcem. | | [Uložit PDF jako JPEG](./pdf-to-jpeg/) | Snadno převádějte PDF do JPEG pomocí Aspose.Words pro .NET. Postupujte podle našeho podrobného návodu s příklady a častými dotazy. Ideální pro vývojáře a nadšence. | | [Uložit PDF do formátu Word (Docx)](./pdf-to-docx/) | Naučte se v tomto podrobném návodu krok za krokem, jak převést PDF do dokumentu Word (Docx) pomocí Aspose.Words pro .NET. Ideální pro vývojáře. | | [Jak exportovat LaTeX z Wordu – krok za krokem](./how-to-export-latex-from-word-step-by-step-guide/) | Naučte se, jak pomocí Aspose.Words pro .NET exportovat obsah Wordu do formátu LaTeX. Praktický průvodce s ukázkovým kódem. | | [Převod Wordu do PDF v C# pomocí Aspose.Words – Průvodce](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Naučte se, jak převést dokument Word do PDF pomocí Aspose.Words v C#. Praktický návod s ukázkovým kódem. | | [Uložit Word jako PDF pomocí Aspose.Words – Kompletní průvodce C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Naučte se, jak pomocí Aspose.Words převést dokument Word do PDF v C# s podrobným návodem a ukázkovým kódem. | +| [Převod Wordu do PDF v C# – Kompletní průvodce s Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Naučte se, jak převést dokument Word do PDF v C# pomocí Aspose.Words s podrobným návodem a ukázkovým kódem. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/czech/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..356197684b --- /dev/null +++ b/words/czech/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,198 @@ +--- +category: general +date: 2026-04-05 +description: Převod Wordu na PDF v C# pomocí Aspose.Words. Naučte se, jak uložit docx + jako PDF, exportovat přístupné PDF a efektivně načíst Word dokument. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: cs +og_description: Převod Wordu do PDF v C# s podrobným návodem. Zjistěte, jak uložit + docx jako PDF, exportovat přístupné PDF a načíst dokument Word pomocí Aspose.Words. +og_title: Převod Wordu do PDF v C# – Kompletní tutoriál Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Převod Wordu do PDF v C# – Kompletní průvodce s Aspose.Words +url: /cs/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod Wordu do PDF v C# – Kompletní programovací tutoriál + +Už jste se někdy zamysleli, jak **convert word to pdf** bez boje s nepřehlednými nástroji příkazové řádky nebo službami třetích stran? Nejste v tom sami. Mnoho vývojářů narazí na tento problém, když klient požaduje přístupný PDF přímo z DOCX souboru. Dobrá zpráva? S několika řádky C# a výkonnou knihovnou Aspose.Words můžete převést dokument Word do standardně‑kompatibilního PDF během okamžiku. + +V tomto průvodci projdeme vše, co potřebujete vědět: od základů **load word document**, přes nastavení správných možností pro **how to export accessible pdf**, až po uložení výsledku, takže můžete spolehlivě **save docx as pdf**. Na konci budete mít připravený úryvek kódu, který můžete vložit do libovolného .NET projektu. + +> **Tip:** Pokud cílíte na shodu s PDF/UA‑2 (standard přístupnosti, který vyžaduje mnoho vládních agentur), stejný kód funguje bez dalších kroků — stačí nastavit správný příznak `PdfCompliance`. + +--- + +## Co se naučíte + +- Jak **load word document** pomocí Aspose.Words v C#. +- Přesná nastavení potřebná pro **how to export accessible pdf** (PDF/UA‑2). +- Kompletní, spustitelný příklad, který **save docx as pdf** jedním voláním metody. +- Běžné úskalí při **c# convert docx pdf** a jak se jim vyhnout. +- Rychlé způsoby, jak ověřit, že vygenerované PDF splňuje požadavky na přístupnost. + +Žádné externí nástroje, žádné nejasné konfigurační soubory — pouze čistý C# kód, který můžete dnes zkompilovat. + +--- + +## Požadavky + +1. **.NET 6.0** (nebo jakákoli novější verze .NET) nainstalovaná. Starší frameworky také fungují, ale syntaxe níže předpokládá moderní SDK. +2. **license** pro Aspose.Words for .NET. Knihovna nabízí bezplatnou zkušební verzi, ale pro produkci budete potřebovat platný klíč. +3. **Aspose.Words** NuGet balíček přidaný do vašeho projektu: + +```bash +dotnet add package Aspose.Words +``` + +To je vše — žádné další binární soubory, žádné COM interop, jen čistý odkaz na NuGet. + +![převod wordu do pdf pomocí Aspose.Words v C#](image-placeholder.png "převod wordu do pdf pomocí Aspose.Words v C#") + +--- + +## Implementace krok za krokem + +Níže rozdělujeme proces do logických částí. Každý krok obsahuje malý úryvek kódu, vysvětlení **proč** je důležitý a tip vycházející ze skutečného nasazení. + +### ## Převod Wordu do PDF – Načtení zdrojového dokumentu + +První, co musíte udělat, je **load word document** do paměti. Aspose.Words abstrahuje OpenXML parsování, takže můžete pracovat s DOCX, DOC nebo i RTF soubory, aniž byste se museli starat o zvláštnosti formátu. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Proč je to důležité:** +Načtení souboru vytvoří objekt `Document`, který představuje celý Word soubor, včetně záhlaví, zápatí, stylů a skrytých metadat. Pokud tento krok přeskočíte nebo se pokusíte číst soubor jako surový proud, ztratíte informace o rozložení, které později určují, jak PDF vypadá. + +> **Side note:** Stejný konstruktor `Document` funguje pro `.doc` i `.rtf`. To znamená, že můžete **c# convert docx pdf** i když zdroj není striktně DOCX. + +### ## Uložení DOCX jako PDF – Nastavení souladu s PDF/UA‑2 + +Nyní, když je dokument v paměti, řekneme Aspose.Words, jak má být PDF vygenerováno. Pro většinu případů jsou výchozí nastavení v pořádku, ale když potřebujete **accessible PDF**, musíte povolit příznak souladu PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Proč je to důležité:** +`PdfCompliance.PdfUAXmpA2` říká knihovně, aby vložila potřebné značky a struktury, na které spoléhají čtečky obrazovky. Bez tohoto příznaku můžete získat perfektně vypadající PDF, které neprojde auditom přístupnosti. + +> **Tip:** Pokud potřebujete jen běžný PDF, můžete řádek `Compliance` vynechat. Ostatní možnosti stále poskytují výstup vysoké kvality. + +### ## Převod Wordu do PDF – Zapsání souboru + +S připravenými možnostmi je posledním krokem **save docx as pdf**. Toto jediné volání provede veškerou těžkou práci: konverzi rozložení, vložení fontů a označování přístupnosti. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Co získáte:** +- PDF soubor v `outputPath`, který odráží rozložení Wordu. +- Pokud jste použili příznak `PdfUAXmpA2`, PDF bude označeno jako splňující PDF/UA‑2. +- Všechny fonty jsou vloženy, takže soubor vypadá identicky na jakémkoli počítači. + +### ## Ověření přístupného PDF (volitelné, ale doporučené) + +Po konverzi je dobré dvakrát zkontrolovat, že PDF opravdu **how to export accessible pdf** správně. Můžete použít bezplatné nástroje jako „Accessibility Check“ v Adobe Acrobat Reader nebo open‑source validátor `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Pokud validátor nehlásí žádné chyby, úspěšně jste **convert word to pdf** s plnou podporou přístupnosti. + +### ## Běžné úskalí při převodu C# DOCX do PDF + +| Problém | Proč k tomu dochází | Řešení | +|-------|----------------|-----| +| Chybějící fonty | Zdrojový DOCX používá vlastní font, který není nainstalován na serveru. | Nastavte `EmbedFullFonts = true` nebo nainstalujte font na stroj. | +| Velikost souboru | Obrázky jsou vloženy v plném rozlišení. | Použijte `ImageCompression = PdfImageCompression.Jpeg` a nastavte nižší hodnotu `JpegQuality`. | +| Přerušené hypertextové odkazy | Odkazy ukazují na relativní cesty, které na klientovi neexistují. | Zajistěte, aby URL byly absolutní, nebo upravte vlastnost `HyperlinkTarget`. | +| Chybějící značky přístupnosti | Příznak `Compliance` není nastaven. | Přidejte `Compliance = PdfCompliance.PdfUAXmpA2` podle výše uvedeného příkladu. | + +Mít tyto body na paměti učiní vaši rutinu **c# convert docx pdf** robustní a připravenou pro produkci. + +## Kompletní funkční příklad + +Spojením všech částí získáte samostatnou konzolovou aplikaci, kterou můžete ihned zkompilovat a spustit. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Očekávaný výsledek:** Po spuštění programu najdete `output.pdf` v `C:\Docs`. Otevřete jej v libovolném PDF prohlížeči; rozložení by mělo být pixel‑po‑pixelu shodné s `input.docx` a kontrola přístupnosti potvrdí shodu s PDF/UA‑2. + +## Závěr + +Právě jsme prošli kompletním, end‑to‑end řešením, jak **convert word to pdf** pomocí C# a Aspose.Words. Tím, že **load word document**, nastavíte správné `PdfSaveOptions` a nakonec **save docx as pdf**, získáte vysoce kvalitní, přístupný PDF s minimálním množstvím kódu. Ať už budujete mikroservisu pro generování dokumentů, nebo lokální dávkový převodník, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-markdownsaveoptions/_index.md b/words/czech/net/programming-with-markdownsaveoptions/_index.md index 2f80977c12..4fae1cc75d 100644 --- a/words/czech/net/programming-with-markdownsaveoptions/_index.md +++ b/words/czech/net/programming-with-markdownsaveoptions/_index.md @@ -32,6 +32,8 @@ Zpracování textu pomocí MarkdownSaveOptions je podrobný návod, který vás | [Exportovat Markdown z Wordu – kompletní průvodce v C#](./how-to-export-markdown-from-word-complete-c-guide/) | Naučte se, jak exportovat Markdown z Wordu pomocí kompletního průvodce v C#. | | [Jak uložit Markdown z DOCX – krok za krokem průvodce](./how-to-save-markdown-from-docx-step-by-step-guide/) | Naučte se krok za krokem ukládat soubory DOCX jako Markdown pomocí Aspose.Words pro .NET. | | [Jak exportovat Markdown z DOCX – Kompletní průvodce](./how-to-export-markdown-from-docx-complete-guide/) | Naučte se, jak exportovat Markdown z DOCX pomocí kompletního průvodce. | +| [Převod DOCX do Markdownu – Extrahování obrázků z DOCX pomocí Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Naučte se převádět soubory DOCX do Markdownu a extrahovat obrázky pomocí Aspose.Words pro .NET. | +| [Převod Wordu do Markdownu – Kompletní průvodce s exportem PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Naučte se převádět dokumenty Word do Markdownu a exportovat je jako PDF/UA pomocí Aspose.Words pro .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/czech/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..5300f14745 --- /dev/null +++ b/words/czech/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Naučte se, jak převést DOCX na Markdown a extrahovat obrázky z DOCX v + C#. Průvodce krok za krokem s kompletním kódem a tipy. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: cs +og_description: Převod DOCX na Markdown a extrakce obrázků z DOCX pomocí Aspose.Words. + Kompletní tutoriál v C# s kódem, vysvětlením a tipy na osvědčené postupy. +og_title: Převést DOCX na Markdown – Extrahovat obrázky z DOCX v C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Převod DOCX na Markdown – Extrahování obrázků z DOCX pomocí Aspose.Words +url: /cs/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod DOCX na Markdown – Extrahování obrázků z DOCX v C# + +Už jste někdy potřebovali **convert DOCX to Markdown**, ale potýkali se s tím, že se obrázky v výstupu ztratily? Nejste v tom sami. V mnoha projektech je verze markdown ideální pro správu verzí nebo generátory statických stránek, ale obrázky zůstávají pozadu, což promění bohatý dokument na pustý textový soubor. + +Dobrá zpráva? S několika řádky C# a Aspose.Words můžete **convert DOCX to Markdown** *a* **extract images from DOCX** automaticky. Tento průvodce vás provede celým procesem, vysvětlí, proč je každá část důležitá, a dokonce vám ukáže, jak udržet složku s obrázky v pořádku. + +## Co se naučíte + +- Jak načíst DOCX, který obsahuje obrázky. +- Jak definovat vlastní `IResourceSavingCallback`, který rozhoduje, kam se každý obrázek uloží. +- Jak nakonfigurovat `MarkdownSaveOptions`, aby vygenerovaný markdown správně odkazoval na extrahované obrázky. +- Tipy pro zpracování okrajových případů, jako jsou duplicitní názvy obrázků nebo formáty jiných než PNG. +- Kompletní, připravený k kopírování a vložení kódový příklad, který můžete spustit ještě dnes. + +### Požadavky + +- .NET 6.0 nebo novější (API funguje na .NET Core, .NET Framework a .NET 5+). +- Licence na **Aspose.Words for .NET** (bezplatná zkušební verze funguje pro testování). +- Základní znalost C# a Visual Studio (nebo vašeho oblíbeného IDE). + +Pokud to máte, pojďme na to. + +--- + +## Krok 1: Nastavení projektu a instalace Aspose.Words + +Nejprve vytvořte novou konzolovou aplikaci (nebo ji integrujte do existujícího řešení). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Tip:** Použijte nejnovější verzi NuGet (k dubnu 2026 je to 24.12), abyste získali nejnovější vylepšení exportu do markdown. + +--- + +## Krok 2: Vytvoření callbacku pro ukládání obrázků tam, kde chcete + +Aspose.Words vám umožní zachytit každý zdroj (obrázky, SVG atd.), který je během exportu do markdownu zapsán. Implementací `IResourceSavingCallback` můžete: + +1. Vybrat složku, která leží vedle vašeho markdown souboru. +2. Vygenerovat jedinečný název souboru (aby se nikdy nepřepisoval existující obrázek). +3. Rozhodnout o formátu (zde vynucujeme PNG pro konzistenci). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Proč název založený na GUID? + +Pokud zdrojový DOCX obsahuje dva obrázky se stejným původním názvem, jednoduché kopírování a vložení by jeden z nich přepsalo. Použití `Guid.NewGuid()` zaručuje jedinečnost, což je zvláště užitečné, když spouštíte převod mnohokrát v automatizovaném pipeline. + +--- + +## Krok 3: Načtení DOCX a nastavení možností Markdown + +Nyní přineseme dokument do paměti a připojíme callback, který jsme právě vytvořili. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Co kód dělá, krok po kroku + +| Krok | Účel | +|------|------| +| **Definovat cesty** | Udržuje projekt flexibilní; můžete ukazovat na libovolnou složku bez nutnosti překladu. | +| **Načíst DOCX** | `Document` parsuje Word soubor a zpřístupňuje všechny prvky (odstavce, tabulky, obrázky). | +| **Konfigurovat `MarkdownSaveOptions`** | `ResourceSavingCallback` je hák, který extrahuje obrázky. Bez něj by Aspose.Words vložil obrázky jako base64 řetězce nebo je úplně vynechal, v závislosti na nastavení. | +| **Uložit** | `doc.Save` zapíše markdown soubor a spustí callback pro každý obrázek. | + +--- + +## Krok 4: Ověření výstupu – Co byste měli vidět? + +Po spuštění programu otevřete `DocWithImages.md`. Všimnete si odkazů na obrázky v markdownu, které vypadají takto: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +A v `C:\Docs\MarkdownResources` najdete sérii PNG souborů s názvy GUID. Otevřete kterýkoli – měly by být identické s obrázky, které byly vloženy v původním DOCX. + +Pokud otevřete markdown soubor v prohlížeči, který respektuje relativní cesty (např. náhled ve VS Code, GitHub nebo generátor statických stránek), obrázky se zobrazí stejně jako ve Wordu. + +### Časté problémy a jak se jim vyhnout + +| Symptom | Pravděpodobná příčina | Řešení | +|---------|-----------------------|--------| +| Obrázky se zobrazují jako poškozené odkazy | `ResourceFileName` nebyl nastaven, takže markdown odkazuje na neexistující soubor. | Ujistěte se, že v callbacku je `args.ResourceFileName = newFileName;`. | +| PNG soubory jsou velké | Původní obrázky byly JPEG nebo BMP; převod na PNG může zvýšit velikost. | Detekujte původní formát pomocí `args.ResourceContentType` a zachovejte jej: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplicitní obrázky se stále objevují | Použili jste statický název souboru místo GUID. | Vraťte se k logice GUID nebo přidejte čítač pro každý typ obrázku. | +| Převod vyvolá `FileNotFoundException` | Cesta ke zdrojovému DOCX je špatná nebo složka nemá oprávnění ke čtení. | Ověřte cestu a udělte potřebná oprávnění k souborovému systému. | + +--- + +## Krok 5: Pokročilé úpravy (volitelné) + +### 5.1 Zachování původních formátů obrázků + +Pokud chcete, aby výstupní obrázky zachovaly své původní přípony, upravte callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Vkládání obrázků jako Base64 (když *nechcete* samostatné soubory) + +Někdy je výhodnější mít markdown v jediném souboru (např. pro odeslání e‑mailem). Změňte volbu: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Ale pamatujte: **extract images from DOCX** je hlavním cílem pro většinu workflow s generátory statických stránek, takže přístup se složkou je obvykle lepší volba. + +--- + +## Kompletní funkční příklad (připravený ke kopírování a vložení) + +Níže je celý program v jednom souboru. Stačí nahradit cesty vlastními a spustit. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Spusťte jej pomocí `dotnet run`. Když konzole vytiskne řádek s ✅, otevřete markdown soubor a měli byste vidět obrázky správně zobrazené. + +--- + +## Závěr + +Nyní máte **kompletní, připravené řešení pro převod DOCX na Markdown a extrahování obrázků z DOCX** pomocí Aspose.Words v C#. Hlavní klíčové slovo se v průvodci objevuje po celou dobu, což posiluje relevanci jak pro vyhledávače, tak pro AI asistenty. + +V jediném průchodu kód: + +1. Načte Word dokument. +2. Zachytí každý obrázek pomocí `IResourceSavingCallback`. +3. Uloží každý obrázek do předvídatelné složky s jedinečným názvem. +4. Vygeneruje markdown, který odkazuje na tyto obrázky. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/czech/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..2f7d8e5f6b --- /dev/null +++ b/words/czech/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Rychle převádějte Word do Markdown a zároveň se naučte, jak v C# uložit + jako PDF/UA. Krok za krokem kód, tipy a řešení okrajových případů. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: cs +og_description: Převod Wordu na Markdown a uložení jako PDF/UA pomocí Aspose.Words. + Zjistěte, proč, jak a tipy na nejlepší postupy v jednom stručném průvodci. +og_title: Převod Wordu na Markdown – Kompletní C# tutoriál +tags: +- Aspose.Words +- C# +- Document Conversion +title: Převod Wordu na Markdown – Kompletní průvodce s exportem PDF/UA +url: /cs/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod Wordu do Markdown – Kompletní průvodce s exportem PDF/UA + +Už jste se někdy zamýšleli, jak **převést Word do Markdown** bez ztráty rovnic nebo obrázků? Nejste v tom sami. Mnoho vývojářů potřebuje spolehlivý způsob, jak převést soubory `.docx` na čistý Markdown a zároveň **uložit jako PDF/UA** pro přístupné PDF. V tomto tutoriálu projdeme kompletní, připravené řešení pomocí Aspose.Words pro .NET, vysvětlíme, proč je každé nastavení důležité, a ukážeme, jak řešit složitější části jako OfficeMath a plovoucí tvary. + +Na konci tohoto průvodce budete mít jeden C# program, který: + +1. Načte Word dokument s uvolněným zotavením (aby poškozené soubory nezastavily běh). +2. Exportuje jej do Markdownu, převádí rovnice na LaTeX a ukládá obrázky pomocí vlastního callbacku. +3. Uloží stejný dokument jako soubor kompatibilní s PDF/UA‑2, vkládá plovoucí tvary jako inline tagy. + +Zní to jako hodně? Žádný problém – ponořme se do toho. + +## Co budete potřebovat + +- **Aspose.Words pro .NET** (nejnovější verze, 23.x v době psaní). +- Vývojové prostředí .NET (Visual Studio 2022, Rider nebo `dotnet` CLI). +- Ukázkový Word soubor (`input.docx`) umístěný ve složce, na kterou můžete odkazovat. +- Základní znalost syntaxe C# – nic exotického, jen pár `using` direktiv. + +> **Tip:** Pokud používáte správce balíčků NuGet, přidejte knihovnu pomocí +> `dotnet add package Aspose.Words` nebo přes Visual Studio NuGet UI. + +## Krok 1 – Načtení Word dokumentu s uvolněným zotavením + +Když dostáváte Word soubory z externích zdrojů, mohou obsahovat drobné poškození. Zapnutí **Relaxed** zotavení říká Aspose.Words, aby pokračoval místo vyhození výjimky. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Proč je to důležité:** +- `RecoveryMode.Relaxed` zabraňuje tomu, aby jediný špatně formátovaný odstavec přerušil celou konverzi. +- Poskytnutí objektu `FontSettings` zajistí, že chybějící fonty budou nahrazeny elegantně, což je klíčové, když později převádíte rovnice na LaTeX. + +## Krok 2 – Export do Markdownu (OfficeMath → LaTeX, obrázky přes Callback) + +Markdown nemá nativní způsob, jak reprezentovat Word rovnice. Aspose.Words může převést **OfficeMath** objekty do LaTeXu, který většina Markdown renderérů rozumí. Obrázky však musí být uloženy někde; vlastní **callback pro ukládání zdrojů** vám dává plnou kontrolu nad strukturou složek a pojmenováním. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback pro ukládání zdrojů + +Níže je malá implementace, která ukládá každý obrázek do podsložky `images` a pojmenovává soubory `img001.png`, `img002.png` atd. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Proč to potřebujete:** +- Bez callbacku Aspose.Words vytvoří plochou složku s náhodnými GUID názvy, což ztěžuje verzování. +- Kontrolou pojmenování udržujete Markdown repozitář přehledný a reprodukovatelný. + +### Očekávaný výstup v Markdownu + +Po spuštění otevřete `doc.md` a uvidíte: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Rovnice se zobrazují jako LaTeX uzavřené v `$$ … $$` a obrázky odkazují na složku `images`, kterou jste právě vytvořili. + +## Krok 3 – Export do PDF/UA‑2 (přístupný) + +Pokud potřebujete dokument sdílet s uživateli, kteří používají čtečky obrazovky nebo jinou asistivní techniku, **PDF/UA‑2** je zlatý standard. Aspose.Words to může vynutit jedním příznakem a také může zploštit plovoucí tvary na inline tagy, aby nebyly při konverzi ztraceny. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Proč je PDF/UA důležité:** +- PDF/UA (Universal Accessibility) zaručuje, že výsledné PDF obsahuje správné tagování, logické čtecí pořadí a alternativní text pro obrázky. +- Nastavení `ExportFloatingShapesAsInlineTag` zajistí, že tvary jako textová pole nebo callouty nebudou vynechány nebo špatně umístěny – častý problém při konverzi složitých rozvržení. + +### Ověření souladu s PDF/UA + +Po exportu otevřete PDF v Adobe Acrobat Pro a spusťte **“Accessibility Check”** (Nástroje → Přístupnost → Úplná kontrola). Pokud nástroj hlásí **0 chyb**, máte úspěch. + +## Okrajové případy a časté úskalí + +| Situace | Na co si dát pozor | Oprava / Doporučení | +|----------------------------------------------------|--------------------------------------------------------|--------------------------------------------------------------| +| Word soubor obsahuje **nepodporované fonty** | Fonty mohou být nahrazeny, což rozbije rozvržení rovnic | Poskytněte vlastní `FontSettings` s náhradními fonty. | +| Velké dokumenty (> 100 MB) | Vysoký tlak na paměť během konverze | Použijte `LoadOptions` s `LoadFormat.Docx` a načtěte soubor jako stream. | +| Obrázky jsou **EMF/WMF** vektorová grafika | Mohou být nechtěně rasterizovány | Před uložením je převěďte na PNG pomocí `ImageSaveOptions`. | +| PDF/UA selže při validaci **vnořených tabulek** | Tagování může být nejednoznačné | Aktivujte `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit`. | +| Potřeba **zachovat vlastní styly** | Markdown má omezené možnosti stylování | Exportujte soubor CSS vedle Markdownu a odkazujte na něj. | + +## Kompletní funkční příklad (všechen kód dohromady) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Spusťte program a najdete jak `doc.md` (s LaTeX rovnicemi a čistými odkazy na obrázky), tak `doc.pdf` (plně kompatibilní s PDF/UA‑2) v adresáři `YOUR_DIRECTORY`. + +## Vizualizace + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Alt text:* **convert word to markdown example** – diagram převodního potrubí od Word souboru k Markdownu a PDF/UA. + +## Shrnutí a další kroky + +Právě jsme **převáděli Word do Markdown** a zachovali rovnice, uložili obrázky do přehledné složky a vytvořili **PDF/UA** soubor, který projde kontrolou přístupnosti. Hlavní poznatky jsou: + +- Použijte `LoadOptions.RecoveryMode.Relaxed` pro toleranci neúplných Word souborů. +- Nastavte `OfficeMathExportMode` na `LaTeX` pro čisté zobrazení rovnic. +- Implementujte `ResourceSavingCallback` pro kontrolu výstupu obrázků. +- Aktivujte `PdfCompliance.PdfUAXmpA2` a `ExportFloatingShapesAsInlineTag` pro standardně kompatibilní PDF. + +### Co zkusit dál? + +- **Vlastní CSS pro Markdown** – vytvořte stylopis, který bude odpovídat vašim Word stylům. +- **Dávkové zpracování** – procházejte adresář `.docx` souborů a automatizujte hromadnou migraci. +- **Pokročilé funkce PDF/UA** – přidejte vlastní tagy, nastavte jazykové atributy nebo vložte audio popisy. +- **Integrace s CI/CD** – zajistěte, aby každý build automaticky vytvářel přístupná PDF. + +Pokud narazíte na problém, ověřte, že verze Aspose.Words odpovídá použitému API, a pamatujte, že oficiální dokumentace knihovny je solidní sekundární referencí. + +Šťastné kódování a ať vaše dokumenty zůstávají jak krásné, **tak** přístupné! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/programming-with-txtsaveoptions/_index.md b/words/czech/net/programming-with-txtsaveoptions/_index.md index d7a1b774bf..8849245eca 100644 --- a/words/czech/net/programming-with-txtsaveoptions/_index.md +++ b/words/czech/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Díky těmto tutoriálům budete schopni plně využít funkce Aspose.Words pro | [Přidání oboustranných značek v dokumentu Word](./add-bidi-marks/) | Naučte se v tomto průvodci, jak přidávat obousměrné (Bidi) značky do dokumentů Wordu pomocí Aspose.Words pro .NET. Zajistěte správný směr textu pro vícejazyčný obsah. | | [Použít tabulátor na úroveň pro odsazení seznamu](./use-tab-character-per-level-for-list-indentation/) | Naučte se, jak vytvářet víceúrovňové seznamy s odsazením pomocí tabulátorů pomocí Aspose.Words pro .NET. Pro přesné formátování seznamů ve vašich dokumentech postupujte podle tohoto návodu. | | [Použijte mezeru na úroveň pro odsazení seznamu](./use-space-character-per-level-for-list-indentation/) | Naučte se, jak v Aspose.Words pro .NET vytvářet víceúrovňové seznamy s odsazením mezer. Podrobný návod pro přesné formátování dokumentů. | - +| [Uložení docx jako txt – Export rovnic Word do LaTeXu pomocí C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Naučte se, jak převést rovnice z dokumentu Word do formátu LaTeX při ukládání jako TXT pomocí C# a Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/czech/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..4817b016d6 --- /dev/null +++ b/words/czech/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Uložte docx jako txt pomocí Aspose.Words – rychle převádějte Word do + txt a zjistěte, jak exportovat matematické rovnice jako LaTeX. Jednoduchý C# kód, + žádné další nástroje nejsou potřeba. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: cs +og_description: Uložte docx jako txt v C# a zjistěte, jak exportovat matematiku do + LaTeXu. Postupujte podle tohoto krok‑za‑krokem průvodce a převádějte Word na txt + s rovnicemi zachovanými. +og_title: Uložit docx jako txt – Exportovat rovnice Wordu do LaTeXu +tags: +- Aspose.Words +- C# +- Document Conversion +title: Uložit docx jako txt – Exportovat rovnice z Wordu do LaTeXu pomocí C# +url: /cs/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# uložit docx jako txt – Export rovnic z Wordu do LaTeXu pomocí C# + +Už jste někdy potřebovali **uložit docx jako txt**, ale obávali jste se, že vaše rovnice zmizí nebo se změní na nečitelné nesmysly? Nejste v tom sami. Mnoho vývojářů narazí na tento problém, když se snaží **převést Word na txt** pro následné zpracování, zejména pokud zdrojový soubor obsahuje objekty Office Math. + +Dobrá zpráva? S několika řádky C# a správnými možnostmi můžete nejen **převést Word na txt**, ale také zachovat každou rovnici jako čistý LaTeX kód. V tomto tutoriálu projdeme celý proces, vysvětlíme, proč je každé nastavení důležité, a ukážeme vám, jak výsledek ověřit. + +Pokryjeme: + +* Instalace knihovny Aspose.Words pro .NET +* Načtení `.docx`, který obsahuje matematické rovnice +* Konfigurace `TxtSaveOptions`, aby **jak exportovat matematiku** se stalo řetězcem vhodným pro LaTeX +* Uložení souboru a kontrola výstupu + +Na konci budete mít znovupoužitelný úryvek kódu, který vám umožní **uložit docx jako txt** a přitom zachovat každou formuli v LaTeXu – ideální pro vědecké pipeline, generátory statických stránek nebo jakýkoli workflow, který potřebuje prostý text s matematikou. + +--- + +## Požadavky + +Než se ponoříme, ujistěte se, že máte: + +* .NET 6.0 nebo novější (kód funguje také s .NET Framework 4.6+) +* Visual Studio 2022 (nebo jakékoli IDE, které preferujete) +* NuGet balíček **Aspose.Words for .NET** – nainstalujte jej pomocí + +```bash +dotnet add package Aspose.Words +``` + +Žádné další konvertory ani externí nástroje nejsou potřeba; Aspose.Words provádí veškerou těžkou práci interně. + +--- + +## Krok 1: Instalace a odkazování na Aspose.Words + +Nejprve přidejte knihovnu do svého projektu. Pokud používáte příkazovou řádku, spusťte výše uvedený příkaz. Ve Visual Studiu můžete také kliknout pravým tlačítkem na **Dependencies → Manage NuGet Packages** a vyhledat *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Tip:** Používejte nejnovější stabilní verzi (k dubnu 2026 je to 24.10). Novější vydání přinášejí opravy chyb v zacházení s OfficeMath, takže se vyhnete neočekávaným chybějícím symbolům. + +--- + +## Krok 2: Načtení zdrojového dokumentu + +Nyní načteme `.docx`, který obsahuje rovnice, které chcete zachovat. Třída `Document` abstrahuje celý soubor Word a poskytuje vám přístup k textu, obrázkům a objektům Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Proč to načíst nejprve? Aspose.Words parsuje soubor do objektového modelu, což nám umožňuje prozkoumat nebo upravit obsah, než se rozhodneme, jak jej exportovat. Zde začínají mít význam rozhodnutí o **jak exportovat matematiku**. + +--- + +## Krok 3: Konfigurace TxtSaveOptions pro export do LaTeXu + +Jádrem řešení je třída `TxtSaveOptions`. Ve výchozím nastavení ukládání do TXT kompletně odstraňuje Office Math. Nastavením `OfficeMathExportMode` na `LaTeX` řeknete knihovně, aby každou rovnici přeložila do její LaTeX reprezentace. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Proč LaTeX?** LaTeX je lingua franca vědeckého publikování. Exportováním matematiky tímto způsobem zachováte sémantiku rovnice místo plochého obrázku nebo poškozeného řetězce. Pokud později vložíte TXT do Markdown procesoru, který podporuje MathJax, rovnice se vykreslí perfektně. + +--- + +## Krok 4: Uložení dokumentu jako prostý text + +S nastavenými možnostmi je posledním krokem jednorázový příkaz, který zapíše soubor na disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +A to je vše – váš `.docx` je nyní `.txt` soubor, kde se každá rovnice objeví jako LaTeX úryvek, připravený pro další zpracování. + +--- + +## Ověření výstupu (Jak správně uložit txt) + +Otevřete `MathSample.txt` v libovolném textovém editoru. Měli byste vidět něco jako: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Pokud narazíte na surové specifické znaky Wordu (např. `?` nebo chybějící symboly), zkontrolujte, že: + +* Používáte aktuální verzi Aspose.Words (starší verze měly chyby v OfficeMath). +* Zdrojový dokument skutečně obsahuje objekty **OfficeMath** – ne objekty starého Equation Editoru. V posledním případě je možná budete muset převést ručně nebo použít metodu `ConvertMathToOfficeMath` před uložením. + +--- + +## Běžné varianty a okrajové případy + +| Situace | Co dělat | +|-----------|------------| +| **Legacy Equation Editor** objects | Zavolejte `doc.ConvertMathToOfficeMath()` před krokem 3. | +| **You need plain Unicode math, not LaTeX** | Nastavte `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Streamujte operaci ukládání pomocí `doc.Save(Stream, txtOptions)`, abyste se vyhnuli vysoké spotřebě paměti. | +| **You want to keep the original file name** | Použijte `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` při tvorbě výstupní cesty. | + +Tyto úpravy odpovídají na otázku „**jak exportovat matematiku**“ pro různé pipeline, čímž zajišťují, že vaše řešení je robustní bez ohledu na zdroj. + +--- + +## Úplný funkční příklad (Všechny kroky na jednom místě) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Spusťte program, otevřete vygenerovaný `.txt` a uvidíte LaTeX rovnice vložené přesně tam, kde patřily. Toto je nejužší cesta, jak **převést + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/czech/net/working-with-fonts/_index.md b/words/czech/net/working-with-fonts/_index.md index 906092d16c..6f4e43365d 100644 --- a/words/czech/net/working-with-fonts/_index.md +++ b/words/czech/net/working-with-fonts/_index.md @@ -40,7 +40,7 @@ Ať už chcete formátovat text pomocí různých fontů, nastavit pravidla pro | [Nastavení složek s písmy s prioritou](./set-fonts-folders-with-priority/) | Naučte se, jak nastavit prioritu složek písem v dokumentech Word pomocí Aspose.Words pro .NET. Náš průvodce zajistí, že se vaše dokumenty pokaždé vykreslí perfektně. | | [Nastavení složky s fonty True Type](./set-true-type-fonts-folder/) | Naučte se, jak nastavit složku s písmy True Type v dokumentech Wordu pomocí Aspose.Words pro .NET. Postupujte podle našeho podrobného návodu krok za krokem, abyste zajistili konzistentní správu písem. | | [Zadání výchozího písma při vykreslování](./specify-default-font-when-rendering/) | Naučte se, jak zadat výchozí písmo při vykreslování dokumentů Word pomocí Aspose.Words pro .NET. Zajistěte konzistentní vzhled dokumentu napříč platformami. | -| [Nastavení písma s možnostmi načtení](./font-settings-with-load-options/) Naučte se, jak spravovat nastavení písma pomocí možností načítání v Aspose.Words pro .NET. Podrobný návod pro vývojáře, jak zajistit konzistentní vzhled písma v dokumentech Wordu. +| [Nastavení písma s možnostmi načtení](./font-settings-with-load-options/) Naučte se, jak spravovat nastavení písma pomocí možností načítání v Aspose.Words pro .NET. Podrobný návod pro vývojáře, jak zajistit konzistentní vzhled písma v dokumentech Wordu. | | [Nastavit složku písem](./set-fonts-folder/) | Naučte se, jak nastavit vlastní složku s fonty v Aspose.Words pro .NET, abyste zajistili správné vykreslování dokumentů Wordu bez chybějících fontů. | | [Výchozí instance nastavení písma](./font-settings-default-instance/) | V tomto tutoriálu se naučíte, jak nakonfigurovat výchozí nastavení písma v dokumentu Word pomocí Aspose.Words pro .NET. | | [Zobrazit seznam dostupných písem](./get-list-of-available-fonts/) | Zjistěte, jak získat seznam dostupných písem pomocí Aspose.Words pro .NET v tomto podrobném návodu krok za krokem. Zlepšete si své dovednosti v oblasti správy písem. | @@ -48,6 +48,7 @@ Ať už chcete formátovat text pomocí různých fontů, nastavit pravidla pro | [Přijímat varovné oznámení](./receive-warning-notification/) Naučte se, jak přijímat varovné upozornění při používání Aspose.Words pro .NET a jak řešit případné problémy nebo varování v dokumentech. | | [Příklad zdroje písma Steam](./resource-steam-font-source-example/) | Naučte se, jak používat zdroj písem Resource Stream k načtení vlastních písem do Aspose.Words pro .NET. | | [Získat substituci bez přípon](./get-substitution-without-suffixes/) | V tomto tutoriálu se naučíte, jak získat přepsání bez přípon v dokumentu Word pomocí Aspose.Words pro .NET. | +| [Aspose substituce písem – Detekce chybějících písem v dokumentech Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Naučte se, jak pomocí Aspose.Words detekovat chybějící písma v dokumentech Word a získat upozornění. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/czech/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/czech/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..3703bb356e --- /dev/null +++ b/words/czech/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Průvodce nahrazováním fontů Aspose pro detekci chybějících fontů při + načítání dokumentu Word. Naučte se konfigurovat nastavení fontů a efektivně řešit + chybějící fonty. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: cs +og_description: Průvodce nahrazováním fontů Aspose pro detekci chybějících fontů při + načítání dokumentu Word. Naučte se konfigurovat nastavení fontů a efektivně řešit + chybějící fonty. +og_title: Aspose Nahrazení fontů – Detekce chybějících fontů v dokumentech Word +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose substituce fontů – Detekce chybějících fontů v dokumentech Word +url: /cs/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Detekce chybějících fontů v dokumentech Word + +Už jste někdy narazili na soubor Word, který vypadá perfektně na jednom počítači, ale na jiném vykazuje podivné změny fontů? To je klasický problém **aspose font substitution**, který obvykle znamená, že na cílovém systému chybí některé fonty. V tomto tutoriálu vám krok za krokem ukážeme, jak **detekovat chybějící fonty** při **načítání dokumentu Word**, jak **nastavit font settings**, a co dělat, aby **chybějící fonty** byly zpracovány elegantně. + +Projdeme kompletním, spustitelným příkladem v C#, vysvětlíme, proč je každý řádek důležitý, a dokonce vám ukážeme výstup v konzoli, který byste měli očekávat. Na konci budete schopni odhalit nahrazení fontů okamžitě po načtení dokumentu – žádné hádání. + +## Co se naučíte + +- Jak povolit diagnostický sběrač varování fontů v Aspose.Words. +- Přesný kód potřebný k **načtení dokumentu Word** s vlastními **font settings**. +- Jak iterovat přes objekty `WarningInfo` a vypsat každý nahrazený font. +- Tipy, jak potlačit nechtěná varování nebo poskytnout náhradní fonty. +- Připravený ukázkový kód, který můžete zkopírovat a vložit do Visual Studia. + +### Požadavky + +- .NET 6.0 nebo novější (API funguje stejně i na .NET Framework). +- Aspose.Words pro .NET (NuGet balíček `Aspose.Words`). +- Soubor Word, který odkazuje na font, který nemáte nainstalovaný (např. `MissingFont.docx`). + +Pokud máte vše připravené, pojďme na to. + +## Krok 1 – Povolení diagnostického sběrače (Nastavení font settings) + +Nejprve: Aspose.Words zaznamenává varování o nahrazení fontů jen tehdy, když mu to explicitně povolíte. Uděláte to vytvořením objektu `FontSettings` a přiřazením k instanci `LoadOptions`. Představte si to jako zapnutí „debug světel“ pro práci s fonty. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Proč?** +Bez objektu `FontSettings` zůstane sběrač varování tichý a nikdy se nedozvíte, které fonty byly nahrazeny. Inicializací prázdného objektu umožníme Aspose použít výchozí systémové fonty *a* sledovat jakékoli náhrady. + +> **Tip:** Pokud víte, že konkrétní složka obsahuje firemní fonty, nasměrujte `FontSettings` tam pomocí `SetFontsFolder("cesta")`. Tím můžete snížit počet varování o chybějících fontech. + +## Krok 2 – Načtení dokumentu s nastavenými možnostmi (Load Word Document) + +Jakmile je sběrač aktivní, načtěte svůj soubor `.docx` pomocí stejného `LoadOptions`. V tomto okamžiku Aspose prohledá dokument, najde všechny odkazy na fonty a rozhodne, zda je potřeba provést náhradu. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Proč je to důležité?** +Kdybyste jen zavolali `new Document("MissingFont.docx")`, použily by se výchozí nastavení *a* seznam varování by zůstal prázdný. Předáním `loadOptions` zajistíte, že diagnostický sběrač je zapojen do načítacího pipeline. + +## Krok 3 – Získání a zobrazení varování o nahrazení fontů (Detect Missing Fonts) + +Po načtení dokumentu do paměti Aspose uloží všechna varování do `document.WarningCallback.Warnings`. Projděte tuto kolekci, filtrujte podle `WarningType.FontSubstitution` a vytiskněte popis. Každý popis vám řekne, který font chyběl a který byl místo něj použit. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Očekávaný výstup v konzoli** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Tento výstup přesně ukazuje, které fonty chybí na počítači, na kterém kód běží. Nyní můžete rozhodnout, zda chybějící fonty nainstalujete, vložíte do dokumentu, nebo ponecháte náhradu. + +![aspose font substitution – výstup konzole zobrazující varování o nahrazení fontů](/images/aspose-font-substitution-console.png) + +*Text alt:* aspose font substitution – výstup konzole zobrazující varování o nahrazení fontů + +## Krok 4 – Volitelné: Přizpůsobení chování náhrady (Handle Missing Fonts) + +Někdy nechcete jen vědět, *že* k náhradě došlo – chcete také řídit, *jak* se to provede. Aspose.Words vám umožní zaregistrovat vlastní `IFontSubstitutionRule`. Níže je rychlý příklad, který vynutí, aby jakýkoli chybějící font byl nahrazen `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Kdy byste to použili?** +Pokud generujete PDF pro webovou službu a víte, že každý klient dokáže vykreslit `Tahoma`, vynucení této náhrady zaručí vizuální konzistenci bez nutnosti distribuovat desítky souborů s fonty. + +## Kompletní funkční příklad (Všechny kroky dohromady) + +Zde je celý program, který můžete vložit do nového konzolového projektu. Překompiluje se tak, jak je, pokud máte nainstalovaný NuGet balíček Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Spusťte program, sledujte konzoli a uvidíte každý událost chybějícího fontu vytištěnou. Na základě toho můžete rozhodnout, zda fonty nainstalujete, vložíte, nebo ponecháte náhradu. + +## Často kladené otázky + +**Q: Funguje to i při konverzi do PDF?** +Ano. Když později zavoláte `doc.Save("output.pdf")`, všechny fonty, které byly nahrazeny během načítání, budou ty, které se vloží do PDF. Zachycení varování včas vám pomůže vyhnout se neočekávaným změnám fontů ve finálním PDF. + +**Q: Co když mám zpracovávat mnoho dokumentů?** +Zabalte načítací logiku do `try‑catch` bloku a znovu použijte jedinou instanci `FontSettings` napříč dokumenty. Tím snížíte režii a udržíte sběrač varování aktivní pro každý soubor. + +**Q: Můžu varování úplně potlačit?** +Můžete nastavit `loadOptions.WarningCallback = null;` před načtením, ale přijdete o možnost **detekovat chybějící fonty** – což obvykle není žádoucí. + +## Závěr + +Probrali jsme vše, co potřebujete k ovládnutí **aspose font substitution**: povolení diagnostického sběrače, načtení souboru Word s vlastními **font settings**, extrakci seznamu chybějících fontů a dokonce přepsání výchozího pravidla náhrady, abyste **zvládli chybějící fonty** po svém. Pouhých několik řádků C# vám poskytne úplnou přehlednost o problémech s fonty, které by jinak zůstaly skryté za jemnými změnami rozložení. + +Další kroky? Zkuste vložit původní fonty do dokumentu pomocí `FontSettings.SetFontsFolder` nebo prozkoumejte `FontSourceBase` pro načítání fontů z databáze. Můžete také experimentovat se sbírkou `Document.BuiltInStyle`, abyste viděli, jak se změny fontů na úrovni stylu šíří. + +Máte další otázky ohledně Aspose.Words nebo správy fontů? Zanechte komentář, prozkoumejte oficiální dokumentaci Aspose, nebo si založte nový projekt a pohrávejte si s výše uvedeným kódem. Šťastné programování a ať se vaše dokumenty vždy vykreslí přesně tak, jak mají! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/basic-conversions/_index.md b/words/dutch/net/basic-conversions/_index.md index efcb8258a3..e983c61423 100644 --- a/words/dutch/net/basic-conversions/_index.md +++ b/words/dutch/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Basisconversies begeleidt u door basisdocumentconversies met behulp van de Aspos | [PDF opslaan in Word-formaat (Docx)](./pdf-to-docx/) | Leer hoe u een PDF naar een Word-document (Docx) converteert met Aspose.Words voor .NET in deze gedetailleerde, stapsgewijze handleiding. Perfect voor ontwikkelaars. | | [Hoe LaTeX vanuit Word exporteren – Stapsgewijze handleiding](./how-to-export-latex-from-word-step-by-step-guide/) | Leer hoe u LaTeX vanuit Word kunt exporteren met Aspose.Words voor .NET in een stapsgewijze handleiding. | | [Word opslaan als PDF met Aspose.Words – Complete C#-gids](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Leer hoe u Word-documenten naar PDF converteert met Aspose.Words in C# met een volledige stap‑voor‑stap gids. | +| [Word naar PDF converteren in C# – Volledige gids met Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Leer hoe u Word naar PDF converteert in C# met Aspose.Words. Volledige stap‑voor‑stap gids met voorbeeldcode. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/dutch/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..10a8d4c0cb --- /dev/null +++ b/words/dutch/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-04-05 +description: Converteer Word naar PDF in C# met Aspose.Words. Leer hoe je docx opslaat + als PDF, een toegankelijke PDF exporteert en een Word‑document efficiënt laadt. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: nl +og_description: Converteer Word naar PDF in C# met een stapsgewijze handleiding. Ontdek + hoe je docx als PDF opslaat, een toegankelijke PDF exporteert en een Word‑document + laadt met Aspose.Words. +og_title: Word naar PDF converteren in C# – Complete Aspose.Words‑tutorial +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Word naar PDF converteren in C# – Volledige gids met Aspose.Words +url: /nl/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word naar PDF converteren in C# – Complete programmeertutorial + +Heb je je ooit afgevraagd hoe je **word naar pdf** kunt converteren zonder te worstelen met ingewikkelde command‑line tools of externe services? Je bent niet de enige. Veel ontwikkelaars lopen tegen die muur aan wanneer een klant een toegankelijke PDF rechtstreeks uit een DOCX‑bestand vraagt. Het goede nieuws? Met een paar regels C# en de krachtige Aspose.Words‑bibliotheek kun je een Word‑document in een oogwenk omzetten naar een PDF die voldoet aan de standaarden. + +In deze gids lopen we alles door wat je moet weten: van de basis van **load word document**, via het configureren van de juiste opties voor **how to export accessible pdf**, tot het uiteindelijk opslaan van het resultaat zodat je **save docx as pdf** betrouwbaar kunt uitvoeren. Aan het einde heb je een kant‑klaar snippet dat je in elk .NET‑project kunt plaatsen. + +> **Pro tip:** Als je streeft naar PDF/UA‑2‑compliance (de toegankelijkheidsstandaard die veel overheidsinstanties eisen), werkt dezelfde code zonder extra stappen—zet alleen de juiste `PdfCompliance`‑vlag. + +--- + +## Wat je gaat leren + +- Hoe je **load word document** gebruikt met Aspose.Words in C#. +- De exacte instellingen die nodig zijn om **how to export accessible pdf** (PDF/UA‑2) te maken. +- Een volledig, uitvoerbaar voorbeeld dat **save docx as pdf** doet met één methode‑aanroep. +- Veelvoorkomende valkuilen bij **c# convert docx pdf** en hoe je ze kunt vermijden. +- Snelle manieren om te verifiëren dat de gegenereerde PDF voldoet aan de toegankelijkheidsverwachtingen. + +Geen externe tools, geen obscure configuratiebestanden—alleen pure C#‑code die je vandaag nog kunt compileren. + +--- + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +1. **.NET 6.0** (of een recentere .NET‑versie) geïnstalleerd. Oudere frameworks werken ook, maar de onderstaande syntaxis gaat uit van de moderne SDK. +2. Een **license** voor Aspose.Words for .NET. De bibliotheek biedt een gratis proefversie, maar voor productie heb je een geldige sleutel nodig. +3. Het **Aspose.Words** NuGet‑pakket toegevoegd aan je project: + +```bash +dotnet add package Aspose.Words +``` + +Dat is alles—geen extra binaries, geen COM‑interop, alleen een nette NuGet‑referentie. + +--- + +![convert word to pdf met Aspose.Words in C#](image-placeholder.png "convert word to pdf met Aspose.Words in C#") + +--- + +## Stapsgewijze implementatie + +Hieronder splitsen we het proces op in logische delen. Elke stap bevat een klein code‑fragment, een uitleg **waarom** het belangrijk is, en een tip uit de praktijk. + +### ## Word naar PDF converteren – Laad het bron‑document + +Het eerste wat je moet doen is **load word document** in het geheugen. Aspose.Words abstraheert het OpenXML‑parsen, zodat je met DOCX, DOC of zelfs RTF‑bestanden kunt werken zonder je zorgen te maken over format‑eigenaardigheden. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Waarom dit belangrijk is:** +Het laden van het bestand creëert een `Document`‑object dat het volledige Word‑bestand vertegenwoordigt, inclusief kop‑ en voetteksten, stijlen en verborgen metadata. Als je deze stap overslaat of het bestand als ruwe stream leest, verlies je de lay‑out‑informatie die later bepaalt hoe de PDF eruitziet. + +> **Side note:** Dezelfde `Document`‑constructor werkt voor `.doc` en `.rtf`. Dat betekent dat je **c# convert docx pdf** kunt uitvoeren zelfs wanneer de bron niet strikt een DOCX is. + +### ## DOCX opslaan als PDF – Configureer PDF/UA‑2‑compliance + +Nu het document in het geheugen staat, vertellen we Aspose.Words hoe we de PDF willen genereren. Voor de meeste scenario's zijn de standaardinstellingen prima, maar wanneer je een **accessible PDF** nodig hebt, moet je de PDF/UA‑2‑compliance‑vlag inschakelen. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Waarom dit belangrijk is:** +`PdfCompliance.PdfUAXmpA2` vertelt de bibliotheek om de benodigde tags en structuren in te sluiten waar screenreaders op vertrouwen. Zonder deze vlag krijg je misschien een perfect uitziende PDF die een toegankelijkheidsaudit niet doorstaat. + +> **Tip:** Als je alleen een gewone PDF nodig hebt, kun je de `Compliance`‑regel weglaten. De overige opties leveren nog steeds een hoogwaardige output. + +### ## Word naar PDF converteren – Schrijf het bestand + +Met de opties klaar is de laatste stap om **save docx as pdf** uit te voeren. Deze enkele aanroep doet al het zware werk: lay‑out‑conversie, lettertype‑inbedding en toegankelijkheids‑tagging. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Wat je krijgt:** +- Een PDF‑bestand op `outputPath` dat de Word‑lay‑out weerspiegelt. +- Als je de `PdfUAXmpA2`‑vlag hebt gebruikt, wordt de PDF gemarkeerd als PDF/UA‑2‑compliant. +- Alle lettertypen zijn ingebed, zodat het bestand er op elke machine identiek uitziet. + +### ## Controleer de toegankelijke PDF (optioneel maar aanbevolen) + +Na de conversie is het verstandig om te verifiëren dat de PDF echt **how to export accessible pdf** correct heeft uitgevoerd. Je kunt gratis tools gebruiken zoals Adobe Acrobat Reader’s “Accessibility Check” of de open‑source `pdfcpu`‑validator. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Als de validator geen fouten meldt, heb je met succes **convert word to pdf** uitgevoerd met volledige toegankelijkheidsondersteuning. + +### ## Veelvoorkomende valkuilen bij C# DOCX naar PDF conversie + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| Ontbrekende lettertypen | Het bron‑DOCX gebruikt een aangepast lettertype dat niet op de server is geïnstalleerd. | Zet `EmbedFullFonts = true` of installeer het lettertype op de machine. | +| Grote bestandsgrootte | Afbeeldingen worden ingebed op volledige resolutie. | Gebruik `ImageCompression = PdfImageCompression.Jpeg` en stel `JpegQuality` lager in. | +| Gebroken hyperlinks | Links verwijzen naar relatieve paden die niet bestaan bij de client. | Zorg dat URL’s absoluut zijn of pas de eigenschap `HyperlinkTarget` aan. | +| Ontbrekende toegankelijkheidstags | `Compliance`‑vlag niet ingesteld. | Voeg `Compliance = PdfCompliance.PdfUAXmpA2` toe zoals hierboven getoond. | + +Deze punten in gedachten houden maakt je **c# convert docx pdf** routine robuust en productie‑klaar. + +--- + +## Volledig werkend voorbeeld + +Alles bij elkaar, hier is een zelfstandige console‑app die je nu kunt compileren en uitvoeren. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Verwacht resultaat:** Na het uitvoeren van het programma vind je `output.pdf` in `C:\Docs`. Open het in een PDF‑viewer; de lay‑out moet pixel‑voor‑pixel overeenkomen met `input.docx`, en een toegankelijkheidscheck bevestigt PDF/UA‑2‑compliance. + +--- + +## Conclusie + +We hebben zojuist een complete, end‑to‑end‑oplossing doorlopen voor hoe je **convert word to pdf** kunt uitvoeren met C# en Aspose.Words. Door **load word document**, het juiste `PdfSaveOptions` te configureren, en uiteindelijk **save docx as pdf** uit te voeren, krijg je een hoogwaardige, toegankelijke PDF met minimale code. Of je nu een document‑generatie‑microservice bouwt, een on‑premise batch‑converter, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-markdownsaveoptions/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/_index.md index 5167a87a1d..2434887b99 100644 --- a/words/dutch/net/programming-with-markdownsaveoptions/_index.md +++ b/words/dutch/net/programming-with-markdownsaveoptions/_index.md @@ -54,6 +54,14 @@ Leer hoe u docx-bestanden opslaat als markdown en afbeeldingen extraheert met ee Leer hoe u DOCX-bestanden naar Markdown converteert met een duidelijke stap‑voor‑stap handleiding. +### [DOCX naar Markdown converteren – Afbeeldingen extraheren uit DOCX met Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) + +Leer hoe u afbeeldingen uit een DOCX haalt en het document naar Markdown converteert met Aspose.Words. + +### [Word naar Markdown converteren – Volledige gids met PDF/UA-export](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) + +Leer hoe u Word-documenten naar Markdown converteert en tegelijkertijd PDF/UA exporteert met een uitgebreide C#‑handleiding. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..193c09dcdd --- /dev/null +++ b/words/dutch/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Leer hoe je DOCX naar Markdown converteert en afbeeldingen uit DOCX haalt + in C#. Stapsgewijze gids met volledige code en tips. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: nl +og_description: Converteer DOCX naar Markdown en extraheer afbeeldingen uit DOCX met + Aspose.Words. Complete C#-tutorial met code, uitleg en best‑practice‑tips. +og_title: DOCX naar Markdown converteren – Afbeeldingen uit DOCX extraheren in C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX converteren naar Markdown – Afbeeldingen uit DOCX extraheren met Aspose.Words +url: /nl/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX naar Markdown converteren – Afbeeldingen uit DOCX extraheren in C# + +Heb je ooit **DOCX naar Markdown moeten converteren** maar worstelde je met het verdwijnen van afbeeldingen in de output? Je bent niet de enige. In veel projecten is de markdown‑versie perfect voor versie‑controle of static‑site generators, maar de afbeeldingen blijven achter, waardoor een rijk document verandert in een kale tekstbestand. + +Het goede nieuws? Met een paar regels C# en Aspose.Words kun je **DOCX naar Markdown converteren** *en* **afbeeldingen uit DOCX extraheren** automatisch. Deze gids leidt je door het hele proces, legt uit waarom elk onderdeel belangrijk is, en laat zelfs zien hoe je je afbeeldingsmap netjes houdt. + +## Wat je zult leren + +- Hoe je een DOCX laadt die afbeeldingen bevat. +- Hoe je een aangepaste `IResourceSavingCallback` definieert die bepaalt waar elke afbeelding terechtkomt. +- Hoe je `MarkdownSaveOptions` configureert zodat de gegenereerde markdown de geëxtraheerde afbeeldingen correct verwijst. +- Tips voor het omgaan met randgevallen zoals dubbele afbeeldingsnamen of niet‑PNG‑formaten. +- Een volledige, copy‑and‑paste‑klare code‑voorbeeld die je vandaag kunt uitvoeren. + +### Vereisten + +- .NET 6.0 of later (de API werkt op .NET Core, .NET Framework en .NET 5+). +- Een licentie voor **Aspose.Words for .NET** (de gratis proefversie werkt voor testen). +- Basiskennis van C# en Visual Studio (of je favoriete IDE). + +Als je die hebt, laten we beginnen. + +--- + +## Stap 1: Het project opzetten en Aspose.Words installeren + +Maak eerst een nieuwe console‑app (of integreer in een bestaande oplossing). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tip:** Gebruik de nieuwste NuGet‑versie (vanaf april 2026 is dat 24.12) om de nieuwste markdown‑exportverbeteringen te krijgen. + +--- + +## Stap 2: Maak een callback om afbeeldingen op te slaan waar jij ze wilt + +Aspose.Words laat je elke resource (afbeeldingen, SVG's, enz.) onderscheppen die tijdens de markdown‑export wordt weggeschreven. Door `IResourceSavingCallback` te implementeren kun je: + +1. Een map kiezen die naast je markdown‑bestand staat. +2. Een unieke bestandsnaam genereren (zodat je nooit een bestaande afbeelding overschrijft). +3. Het formaat bepalen (hier forceren we PNG voor consistentie). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Waarom een op GUID gebaseerde naam? + +Als de bron‑DOCX twee afbeeldingen met dezelfde oorspronkelijke naam bevat, zou een eenvoudige copy‑paste er één overschrijven. Het gebruik van `Guid.NewGuid()` garandeert uniciteit, wat vooral handig is wanneer je de conversie vaak uitvoert in een geautomatiseerde pipeline. + +--- + +## Stap 3: Laad de DOCX en configureer de Markdown‑opties + +Nu laden we het document in het geheugen en koppelen we de callback die we zojuist hebben gemaakt. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Wat de code doet, stap voor stap + +| Stap | Doel | +|------|------| +| **Definieer paden** | Houdt je project flexibel; je kunt naar elke map wijzen zonder opnieuw te compileren. | +| **Laad de DOCX** | `Document` parseert het Word‑bestand, waardoor alle elementen (paragrafen, tabellen, afbeeldingen) toegankelijk worden. | +| **Configureer `MarkdownSaveOptions`** | De `ResourceSavingCallback` is de haak die afbeeldingen extraheert. Zonder deze zou Aspose.Words de afbeeldingen embedden als base64‑strings of ze volledig weglaten, afhankelijk van de instellingen. | +| **Opslaan** | `doc.Save` schrijft het markdown‑bestand en activeert de callback voor elke afbeelding. | + +--- + +## Stap 4: Controleer de output – Wat zou je moeten zien? + +Na het uitvoeren van het programma, open `DocWithImages.md`. Je zult markdown‑afbeeldingslinks zien die er zo uitzien: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +En in `C:\Docs\MarkdownResources` vind je een reeks PNG‑bestanden met GUID‑namen. Open er een – ze zouden identiek moeten zijn aan de afbeeldingen die in de oorspronkelijke DOCX waren ingebed. + +Als je het markdown‑bestand opent in een viewer die relatieve paden respecteert (bijv. VS Code preview, GitHub, of een static‑site generator), worden de afbeeldingen weergegeven precies zoals ze in Word stonden. + +### Veelvoorkomende valkuilen & hoe ze te vermijden + +| Symptoom | Waarschijnlijke oorzaak | Oplossing | +|----------|--------------------------|-----------| +| Afbeeldingen verschijnen als kapotte links | `ResourceFileName` was niet ingesteld, waardoor de markdown naar een niet‑bestaand bestand wijst. | Zorg ervoor dat `args.ResourceFileName = newFileName;` in de callback staat. | +| PNG‑bestanden zijn enorm | Originele afbeeldingen waren JPEG of BMP; converteren naar PNG kan de grootte vergroten. | Detecteer het oorspronkelijke formaat via `args.ResourceContentType` en behoud het: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplicaatafbeeldingen blijven verschijnen | Je gebruikte een statische bestandsnaam in plaats van een GUID. | Schakel terug naar GUID‑logica of voeg een teller per afbeeldingstype toe. | +| Conversie geeft `FileNotFoundException` | Het pad naar de bron‑DOCX is onjuist of de map heeft geen leesrechten. | Controleer het pad en geef de juiste bestandsysteemrechten. | + +--- + +## Stap 5: Geavanceerde aanpassingen (optioneel) + +### 5.1 Originele afbeeldingsformaten behouden + +Als je wilt dat de uitvoer‑afbeeldingen hun oorspronkelijke extensies behouden, wijzig dan de callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Afbeeldingen embedden als Base64 (wanneer je *geen* losse bestanden wilt) + +Soms is een markdown‑bestand met één bestand handiger (bijv. voor verzending via e‑mail). Verander de optie: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Maar onthoud: **afbeeldingen uit DOCX extraheren** is het primaire doel voor de meeste static‑site‑workflows, dus de map‑aanpak is meestal de betere keuze. + +--- + +## Volledig werkend voorbeeld (copy‑paste‑klaar) + +Hieronder staat het volledige programma in één bestand. Vervang gewoon de paden door die van jou en voer uit. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Voer het uit met `dotnet run`. Wanneer de console de ✅‑regel afdrukt, open je het markdown‑bestand en zou je de afbeeldingen correct moeten zien. + +--- + +## Conclusie + +Je hebt nu een **volledige, productie‑klare oplossing om DOCX naar Markdown te converteren en afbeeldingen uit DOCX te extraheren** met Aspose.Words in C#. Het primaire trefwoord verschijnt door de hele gids, wat de relevantie voor zowel zoekmachines als AI‑assistenten versterkt. + +In één enkele stap doet de code: + +1. Laadt een Word‑document. +2. Intercepteert elke afbeelding via `IResourceSavingCallback`. +3. Slaat elke afbeelding op in een voorspelbare map met een unieke naam. +4. Genereert markdown die naar die afbeeldingen verwijst. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/dutch/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..37e4cf6bfc --- /dev/null +++ b/words/dutch/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Converteer Word snel naar Markdown en leer ook hoe je opslaat als PDF/UA + in C#. Stapsgewijze code, tips en afhandeling van randgevallen. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: nl +og_description: Converteer Word naar Markdown en sla op als PDF/UA met Aspose.Words. + Leer het waarom, het hoe, en best‑practice tips in één beknopte gids. +og_title: Word naar Markdown converteren – Complete C#‑tutorial +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word naar Markdown converteren – Volledige gids met PDF/UA‑export +url: /nl/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converteer Word naar Markdown – Volledige gids met PDF/UA-export + +Heb je je ooit afgevraagd hoe je **Word naar Markdown converteren** kunt zonder formules of afbeeldingen te verliezen? Je bent niet de enige. Veel ontwikkelaars hebben een betrouwbare manier nodig om `.docx`‑bestanden om te zetten naar schone Markdown, terwijl ze nog steeds **opslaan als PDF/UA** kunnen voor toegankelijkheids‑conforme PDF‑bestanden. In deze tutorial lopen we een complete, kant‑klaar oplossing met Aspose.Words voor .NET stap voor stap door, leggen we uit waarom elke instelling belangrijk is, en laten we zien hoe je de lastigere onderdelen zoals OfficeMath en zwevende vormen aanpakt. + +Aan het einde van deze gids heb je een enkel C#‑programma dat: + +1. Een Word‑document laadt met relaxed recovery (zodat corrupte bestanden de uitvoering niet onderbreken). +2. Het exporteert naar Markdown, waarbij formules worden omgezet naar LaTeX en afbeeldingen worden opgeslagen via een aangepaste callback. +3. Hetzelfde document opslaat als een PDF/UA‑2‑conform bestand, waarbij zwevende vormen worden ingebed als inline‑tags. + +Klinkt als veel? Geen probleem—laten we erin duiken. + +## Wat je nodig hebt + +- **Aspose.Words for .NET** (laatste versie, 23.x op het moment van schrijven). +- Een .NET‑ontwikkelomgeving (Visual Studio 2022, Rider, of de `dotnet` CLI). +- Een voorbeeld‑Word‑bestand (`input.docx`) geplaatst in een map die je kunt refereren. +- Basiskennis van C#‑syntaxis—niets exotisch, slechts een paar `using`‑statements. + +> **Pro tip:** Als je een NuGet‑pakketbeheerder gebruikt, voeg dan de bibliotheek toe met +> `dotnet add package Aspose.Words` of via de Visual Studio NuGet‑UI. + +## Stap 1 – Laad het Word‑document met Relaxed Recovery + +Wanneer je Word‑bestanden van externe bronnen ontvangt, kunnen ze lichte corruptie bevatten. Het inschakelen van **Relaxed** recovery vertelt Aspose.Words om door te gaan in plaats van een uitzondering te gooien. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Waarom dit belangrijk is:** +- `RecoveryMode.Relaxed` voorkomt dat een enkele misvormde alinea de hele conversie onderbreekt. +- Het leveren van een `FontSettings`‑object zorgt ervoor dat eventuele ontbrekende lettertypen op een nette manier worden vervangen, wat cruciaal is wanneer je later formules rendert als LaTeX. + +## Stap 2 – Exporteer naar Markdown (OfficeMath → LaTeX, afbeeldingen via callback) + +Markdown heeft geen native manier om Word‑formules weer te geven. Aspose.Words kan **OfficeMath**‑objecten vertalen naar LaTeX, wat de meeste Markdown‑renderers begrijpen. Afbeeldingen moeten echter ergens worden opgeslagen; een aangepaste **resource‑saving callback** geeft je volledige controle over de mapstructuur en naamgeving. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### De resource‑saving callback + +Hieronder staat een kleine implementatie die elke afbeelding opslaat in een sub‑map genaamd `images` en de bestanden benoemt als `img001.png`, `img002.png`, enz. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Waarom je dit nodig hebt:** +- Zonder een callback maakt Aspose.Words een platte map met willekeurige GUID‑namen, wat versiebeheer rommelig maakt. +- Door het naamgevingsschema te beheersen houd je de Markdown‑repository netjes en reproduceerbaar. + +### Verwachte Markdown‑output + +Open `doc.md` na de uitvoering en je zult zien: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Formules verschijnen als LaTeX ingesloten in `$$ … $$`, en afbeeldingen verwijzen naar de `images`‑map die je zojuist hebt aangemaakt. + +## Stap 3 – Exporteer naar PDF/UA‑2 (toegankelijkheids‑klaar) + +Als je het document moet delen met gebruikers die afhankelijk zijn van schermlezers of andere assistieve technologieën, is **PDF/UA‑2**‑conformiteit de gouden standaard. Aspose.Words kan dit afdwingen met één enkele vlag, en kan ook zwevende vormen flattenen naar inline‑tags zodat ze niet verloren gaan tijdens de conversie. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Waarom PDF/UA belangrijk is:** +- PDF/UA (Universal Accessibility) garandeert dat de resulterende PDF correcte tagging, een logische leesvolgorde en alternatieve tekst voor afbeeldingen bevat. +- Het instellen van `ExportFloatingShapesAsInlineTag` zorgt ervoor dat vormen zoals tekstvakken of call‑outs niet worden weggelaten of verkeerd geplaatst — een veelvoorkomende valkuil bij het converteren van complexe lay-outs. + +### Verifiëren van PDF/UA‑conformiteit + +Na de export open je de PDF in Adobe Acrobat Pro en voer je **“Accessibility Check”** uit (Tools → Accessibility → Full Check). Als het hulpmiddel **0 fouten** rapporteert, ben je geslaagd. + +## Randgevallen & Veelvoorkomende valkuilen + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word‑bestand bevat **niet‑ondersteunde lettertypen** | Lettertypen kunnen worden vervangen, waardoor de lay-out van formules wordt verbroken | Voorzie een aangepaste `FontSettings` met fallback‑lettertypen. | +| Grote documenten (> 100 MB) | Geheugendruk tijdens conversie | Gebruik `LoadOptions` met `LoadFormat.Docx` en stream het bestand. | +| Afbeeldingen zijn **EMF/WMF** vectorafbeeldingen | Ze kunnen onbedoeld gerasterd worden | Converteer ze naar PNG via `ImageSaveOptions` vóór het opslaan. | +| PDF/UA faalt bij validatie van **geneste tabellen** | Tagging kan dubbelzinnig worden | Schakel `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` in om de engine te helpen. | +| Noodzakelijk om **aangepaste stijlen te behouden** | Markdown heeft beperkte opmaakmogelijkheden | Exporteer een CSS‑bestand naast de Markdown en verwijs ernaar. | + +## Volledig werkend voorbeeld (alle code samen) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Voer het programma uit, en je zult zowel `doc.md` (met LaTeX‑formules en nette afbeeldingslinks) als `doc.pdf` (volledig PDF/UA‑2‑conform) vinden in `YOUR_DIRECTORY`. + +## Visueel overzicht + +![voorbeeld van Word naar Markdown conversie](https://example.com/placeholder.png "voorbeeld van Word naar Markdown conversie – toont invoer‑Word, Markdown‑output en PDF/UA‑bestand") + +*Alt‑tekst:* **voorbeeld van Word naar Markdown conversie** – diagram van de conversiepijplijn van een Word‑bestand naar Markdown en PDF/UA. + +## Samenvatting & volgende stappen + +We hebben zojuist **Word naar Markdown geconverteerd** terwijl we formules intact hielden, afbeeldingen opgeslagen in een nette map, en een **opslaan als PDF/UA**‑bestand geproduceerd dat toegankelijkheidscontroles doorstaat. De belangrijkste inzichten zijn: + +- Gebruik `LoadOptions.RecoveryMode.Relaxed` om onvolmaakte Word‑bestanden te tolereren. +- Stel `OfficeMathExportMode` in op `LaTeX` voor nette weergave van formules. +- Implementeer een `ResourceSavingCallback` om de afbeeldingoutput te beheersen. +- Schakel `PdfCompliance.PdfUAXmpA2` en `ExportFloatingShapesAsInlineTag` in voor een standaarden‑conforme PDF. + +### Wat kun je hierna verkennen? + +- **Aangepaste CSS voor Markdown** – genereer een stylesheet die je Word‑stijlen weerspiegelt. +- **Batch‑verwerking** – loop door een map met `.docx`‑bestanden om grote migraties te automatiseren. +- **Geavanceerde PDF/UA‑functies** – voeg aangepaste tags toe, stel taal‑attributen in, of embed audio‑beschrijvingen. +- **Integratie met CI/CD** – zorg ervoor dat elke build automatisch toegankelijke PDF‑bestanden produceert. + +Als je een probleem tegenkomt, controleer dan of je Aspose.Words‑versie overeenkomt met de hier gebruikte API, en onthoud dat de documentatie van de bibliotheek een solide secundaire referentie is. + +Veel plezier met coderen, en moge je documenten zowel mooi **als** toegankelijk blijven! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/programming-with-txtsaveoptions/_index.md b/words/dutch/net/programming-with-txtsaveoptions/_index.md index 531ca961c8..246cd2d574 100644 --- a/words/dutch/net/programming-with-txtsaveoptions/_index.md +++ b/words/dutch/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Dankzij deze tutorials kunt u de functionaliteiten van Aspose.Words voor .NET op | [Bidi-markeringen toevoegen aan een Word-document](./add-bidi-marks/) | Leer hoe u bidirectionele (Bidi) markeringen toevoegt aan Word-documenten met Aspose.Words voor .NET met deze handleiding. Zorg voor de juiste tekstrichting voor meertalige content. | | [Gebruik tabteken per niveau voor lijstinspringing](./use-tab-character-per-level-for-list-indentation/) | Leer hoe u lijsten met meerdere niveaus en tab-inspringing maakt met Aspose.Words voor .NET. Volg deze handleiding voor nauwkeurige lijstopmaak in uw documenten. | | [Gebruik spatieteken per niveau voor lijstinspringing](./use-space-character-per-level-for-list-indentation/) | Leer hoe u lijsten met meerdere niveaus met spatie-inspringing maakt in Aspose.Words voor .NET. Stapsgewijze handleiding voor nauwkeurige documentopmaak. | - +| [docx opslaan als txt – Exporteer Word‑vergelijkingen naar LaTeX met C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Leer hoe u een DOCX-bestand opslaat als TXT en Word‑vergelijkingen exporteert naar LaTeX met C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/dutch/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..4f0354eb52 --- /dev/null +++ b/words/dutch/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: docx opslaan als txt met Aspose.Words – converteer Word snel naar txt + en leer hoe je wiskundige vergelijkingen exporteert als LaTeX. Eenvoudige C#‑code, + geen extra tools nodig. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: nl +og_description: sla docx op als txt in C# en zie hoe je wiskunde exporteert naar LaTeX. + Volg deze stapsgewijze handleiding om Word naar txt te converteren met de vergelijkingen + intact. +og_title: docx opslaan als txt – Exporteer Word‑vergelijkingen naar LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx opslaan als txt – Exporteer Word‑vergelijkingen naar LaTeX met C# +url: /nl/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx opslaan als txt – Word‑vergelijkingen exporteren naar LaTeX met C# + +Heb je ooit **docx opslaan als txt** nodig gehad, maar was je bang dat je vergelijkingen zouden verdwijnen of veranderen in onleesbare rommel? Je bent niet de enige. Veel ontwikkelaars lopen tegen dit probleem aan wanneer ze proberen **word te converteren naar txt** voor verdere verwerking, vooral wanneer het bronbestand Office Math‑objecten bevat. + +Het goede nieuws? Met een paar regels C# en de juiste opties kun je niet alleen **Word naar txt converteren**, maar ook elke vergelijking behouden als nette LaTeX‑markup. In deze tutorial lopen we het volledige proces door, leggen we uit waarom elke instelling belangrijk is, en laten we zien hoe je het resultaat kunt verifiëren. + +We behandelen: + +* Het installeren van de Aspose.Words for .NET‑bibliotheek +* Het laden van een `.docx` die wiskundige vergelijkingen bevat +* Het configureren van `TxtSaveOptions` zodat **how to export math** een LaTeX‑vriendelijke string wordt +* Het opslaan van het bestand en het controleren van de output + +Aan het einde heb je een herbruikbare snippet die je **docx opslaan als txt** laat doen terwijl elke formule behouden blijft als LaTeX — perfect voor wetenschappelijke pipelines, static site generators, of elke workflow die platte‑tekst‑wiskunde nodig heeft. + +--- + +## Prerequisites + +Voordat we beginnen, zorg dat je het volgende hebt: + +* .NET 6.0 of later (de code werkt ook met .NET Framework 4.6+) +* Visual Studio 2022 (of een IDE naar keuze) +* Het **Aspose.Words for .NET** NuGet‑pakket – installeer het met + +```bash +dotnet add package Aspose.Words +``` + +Er zijn geen extra converters of externe tools nodig; Aspose.Words doet het zware werk intern. + +--- + +## Step 1: Install and reference Aspose.Words + +Eerst voeg je de bibliotheek toe aan je project. Als je de command‑line gebruikt, voer dan het bovenstaande commando uit. In Visual Studio kun je ook met de rechtermuisknop op **Dependencies → Manage NuGet Packages** klikken en zoeken naar *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Gebruik de nieuwste stabiele versie (vanaf april 2026 is dat 24.10). Nieuwere releases bevatten bug‑fixes voor OfficeMath‑verwerking, zodat je verrassende ontbrekende symbolen voorkomt. + +--- + +## Step 2: Load the source document + +Nu halen we de `.docx` op die de vergelijkingen bevat die je wilt behouden. De `Document`‑klasse abstraheert het volledige Word‑bestand en geeft je toegang tot tekst, afbeeldingen en Office Math‑objecten. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Waarom eerst laden? Aspose.Words parseert het bestand naar een objectmodel, waardoor we de inhoud kunnen inspecteren of aanpassen voordat we beslissen hoe we het exporteren. Hier begint **how to export math** van belang te worden. + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +Het hart van de oplossing is de `TxtSaveOptions`‑klasse. Standaard verwijdert het opslaan naar TXT alle Office Math. Door `OfficeMathExportMode` in te stellen op `LaTeX` vertelt je de bibliotheek elke vergelijking te vertalen naar de LaTeX‑representatie. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX is de lingua franca van wetenschappelijke publicaties. Door wiskunde op deze manier te exporteren behoud je de semantiek van de vergelijking in plaats van een platte afbeelding of een onleesbare string. Als je later de TXT in een Markdown‑processor met MathJax stopt, worden de vergelijkingen perfect gerenderd. + +--- + +## Step 4: Save the document as plain‑text + +Met de opties geconfigureerd is de laatste stap een één‑regelige opdracht die het bestand naar schijf schrijft. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Dat is alles — je `.docx` is nu een `.txt`‑bestand waarin elke vergelijking verschijnt als een LaTeX‑fragment, klaar voor downstream‑gebruik. + +--- + +## Verifying the output (How to save txt correctly) + +Open `MathSample.txt` in een teksteditor. Je zou iets moeten zien zoals: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Als je ruwe Word‑specifieke tekens ziet (bijv. `?` of ontbrekende symbolen), controleer dan het volgende: + +* Je gebruikt een recente Aspose.Words‑versie (oudere builds hadden bugs met OfficeMath). +* Het bronbestand bevat daadwerkelijk **OfficeMath**‑objecten — geen legacy Equation Editor‑objecten. Voor die laatste moet je ze mogelijk handmatig converteren of de `ConvertMathToOfficeMath`‑methode vóór het opslaan gebruiken. + +--- + +## Common Variations & Edge Cases + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** objects | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **You need plain Unicode math, not LaTeX** | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **You want to keep the original file name** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +Deze aanpassingen beantwoorden de vraag **how to export math** voor verschillende pipelines, zodat je oplossing robuust blijft ongeacht de bron. + +--- + +## Full Working Example (All steps in one place) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Run the program, open the generated `.txt`, and you’ll see the LaTeX equations embedded right where they belonged. This is the most straightforward way to **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/dutch/net/working-with-fonts/_index.md b/words/dutch/net/working-with-fonts/_index.md index 4195f5f070..630e283ab1 100644 --- a/words/dutch/net/working-with-fonts/_index.md +++ b/words/dutch/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ Of u nu tekst wilt opmaken met verschillende lettertypen, regels voor lettertype | [Waarschuwingsmelding ontvangen](./receive-warning-notification/) Leer hoe u een waarschuwingsmelding ontvangt wanneer u Aspose.Words voor .NET gebruikt en hoe u problemen of waarschuwingen in uw documenten beheert. | | [Bron van Steam-lettertypebronvoorbeeld](./resource-steam-font-source-example/) | Leer hoe u de Resource Stream Font Source gebruikt om aangepaste lettertypen in Aspose.Words voor .NET te laden. | | [Substitutie verkrijgen zonder achtervoegsels](./get-substitution-without-suffixes/) | In deze tutorial leert u hoe u achtervoegselloze overschrijvingen in een Word-document kunt gebruiken met Aspose.Words voor .NET. | - +| [Aspose-lettertypevervanging – Ontdek ontbrekende lettertypen in Word-documenten](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Leer hoe u ontbrekende lettertypen in Word-documenten detecteert met Aspose Font Substitution. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/dutch/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/dutch/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..e49b8470b5 --- /dev/null +++ b/words/dutch/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Aspose gids voor lettertypevervanging om ontbrekende lettertypen te detecteren + bij het laden van een Word‑document. Leer hoe u lettertype‑instellingen configureert + en ontbrekende lettertypen efficiënt afhandelt. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: nl +og_description: Aspose gids voor lettertypevervanging om ontbrekende lettertypen te + detecteren bij het laden van een Word‑document. Leer hoe u lettertype‑instellingen + configureert en ontbrekende lettertypen efficiënt afhandelt. +og_title: Aspose Lettertypevervanging – Detecteer ontbrekende lettertypen in Word-documenten +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose Lettertypevervanging – Detecteer ontbrekende lettertypen in Word-documenten +url: /nl/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Ontdek Ontbrekende Lettertypen in Word-documenten + +Kom je ooit een Word‑bestand tegen dat er perfect uitziet op één computer maar vreemde lettertype‑wijzigingen vertoont op een andere? Dat is het klassieke **aspose font substitution**‑probleem, en het betekent meestal dat er lettertypen ontbreken op het doelsysteem. In deze tutorial laten we je, stap‑voor‑stap, zien hoe je **ontbrekende lettertypen** kunt **detecteren** wanneer je een **Word‑document laadt**, hoe je **lettertype‑instellingen** kunt **configureren**, en wat je moet doen om **ontbrekende lettertypen** op een nette manier af te handelen. + +We lopen een volledig, uitvoerbaar C#‑voorbeeld door, leggen uit waarom elke regel belangrijk is, en laten je zelfs de console‑output zien die je kunt verwachten. Aan het einde kun je lettertype‑substituties direct zien zodra een document wordt geladen—geen giswerk nodig. + +## Wat je zult leren + +- Hoe je de diagnostische collector van Aspose.Words inschakelt voor lettertype‑waarschuwingen. +- De exacte code die nodig is om een **Word‑document te laden** met aangepaste **lettertype‑instellingen**. +- Hoe je over `WarningInfo`‑objecten itereren om elk vervangen lettertype te vermelden. +- Tips om ongewenste waarschuwingen te onderdrukken of fallback‑lettertypen te bieden. +- Een kant‑klaar voorbeeld dat je kunt kopiëren‑plakken in Visual Studio. + +### Vereisten + +- .NET 6.0 of later (de API werkt hetzelfde op .NET Framework). +- Aspose.Words for .NET (NuGet‑pakket `Aspose.Words`). +- Een Word‑bestand dat een lettertype verwijst dat je niet geïnstalleerd hebt (bijv. `MissingFont.docx`). + +Als je die hebt, laten we erin duiken. + +## Stap 1 – Schakel de diagnostische collector in (Configureer lettertype‑instellingen) + +Allereerst: Aspose.Words registreert alleen waarschuwingen voor lettertype‑substitutie als je het vertelt. Dat doe je door een `FontSettings`‑object te maken en dit toe te wijzen aan een `LoadOptions`‑instantie. Beschouw dit als het inschakelen van de “debug‑lampjes” voor lettertype‑afhandeling. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Waarom?** +Zonder een `FontSettings`‑object blijft de waarschuwing‑collector stil, en zul je nooit weten welke lettertypen zijn vervangen. Door het leeg te initialiseren laten we Aspose de standaard systeemlettertypen gebruiken *en* houden we elke substitutie bij. + +> **Pro tip:** Als je weet dat een specifieke map bedrijfslettertypen bevat, wijs `FontSettings` daar naartoe met `SetFontsFolder("path")`. Dat kan het aantal ontbrekende‑lettertype‑waarschuwingen verminderen. + +## Stap 2 – Laad het document met de geconfigureerde opties (Laad Word‑document) + +Nu de collector actief is, laad je je `.docx`‑bestand met dezelfde `LoadOptions`. Dit is het moment waarop Aspose het document scant, elke lettertype‑referentie zoekt, en beslist of een substitutie nodig is. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Waarom is dit belangrijk?** +Als je simpelweg `new Document("MissingFont.docx")` zou aanroepen, zouden de standaardinstellingen worden toegepast *en* zou de waarschuwingslijst leeg blijven. Het doorgeven van `loadOptions` garandeert dat de diagnostische collector is gekoppeld aan de laad‑pipeline. + +## Stap 3 – Haal lettertype‑substitutie‑waarschuwingen op en toon ze (Detecteer ontbrekende lettertypen) + +Nadat het document in het geheugen staat, slaat Aspose eventuele waarschuwingen op in `document.WarningCallback.Warnings`. Loop door die collectie, filter op `WarningType.FontSubstitution`, en print de beschrijving. Elke beschrijving vertelt je welk lettertype ontbrak en welk lettertype in plaats daarvan werd gebruikt. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Verwachte console‑output** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Die output vertelt je precies welke lettertypen ontbreken op de machine die de code uitvoert. Je kunt nu beslissen of je de ontbrekende lettertypen installeert, ze in het document embed, of de substitutie behoudt. + +![Console‑output die aspose lettertype‑substitutie‑waarschuwingen toont](/images/aspose-font-substitution-console.png) + +*Afbeeldings‑alt‑tekst:* aspose font substitution – console‑output met een lijst van vervangen lettertypen + +## Stap 4 – Optioneel: Pas het substitutiegedrag aan (Ontbrekende lettertypen afhandelen) + +Soms wil je niet alleen weten *dat* er een substitutie heeft plaatsgevonden—je wilt *hoe* het gebeurt controleren. Aspose.Words laat je een aangepaste `IFontSubstitutionRule` registreren. Hieronder staat een snel voorbeeld dat elk ontbrekend lettertype dwingt terug te vallen op `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Wanneer zou je dit gebruiken?** +Als je PDF’s genereert voor een webservice en je weet dat elke client `Tahoma` kan weergeven, dan garandeert het forceren van de fallback visuele consistentie zonder tientallen lettertype‑bestanden te hoeven leveren. + +## Volledig werkend voorbeeld (Alle stappen gecombineerd) + +Hier is het volledige programma dat je kunt plakken in een nieuw console‑project. Het compileert direct, ervan uitgaande dat je het Aspose.Words NuGet‑pakket hebt geïnstalleerd. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Voer het programma uit, bekijk de console, en je zult elk ontbrekend‑lettertype‑event zien afgedrukt. Vanaf daar kun je beslissen of je de ontbrekende lettertypen installeert, embed, of de fallback behoudt. + +## Veelgestelde vragen + +**V: Werkt dit met PDF‑conversie?** +Ja. Wanneer je later `doc.Save("output.pdf")` aanroept, worden de lettertypen die tijdens het laden zijn vervangen, ingebed in de PDF. Het vroegtijdig opvangen van de waarschuwingen helpt je onverwachte lettertype‑wijzigingen in de uiteindelijke PDF te voorkomen. + +**V: Wat als ik veel documenten moet verwerken?** +Plaats de laadlogica in een try‑catch‑blok en hergebruik een enkele `FontSettings`‑instantie voor meerdere documenten. Dat vermindert overhead en houdt de waarschuwing‑collector actief voor elk bestand. + +**V: Kan ik de waarschuwingen volledig onderdrukken?** +Je kunt `loadOptions.WarningCallback = null;` instellen vóór het laden, maar je verliest dan de mogelijkheid om **ontbrekende lettertypen te detecteren**—wat meestal niet gewenst is. + +## Conclusie + +We hebben alles behandeld wat je nodig hebt om **aspose font substitution** onder de knie te krijgen: het inschakelen van de diagnostische collector, het laden van een Word‑bestand met aangepaste **lettertype‑instellingen**, het extraheren van de lijst met ontbrekende lettertypen, en zelfs het overschrijven van de standaard substitutieregel om **ontbrekende lettertypen** op jouw manier af te handelen. Met slechts een paar regels C# krijg je volledige zichtbaarheid op lettertype‑problemen die anders verborgen blijven achter subtiele lay‑out‑wijzigingen. + +Volgende stappen? Probeer de originele lettertypen in het document te embedden met `FontSettings.SetFontsFolder` of verken `FontSourceBase` om lettertypen uit een database te laden. Je kunt ook experimenteren met de `Document.BuiltInStyle`‑collectie om te zien hoe stijl‑niveau lettertype‑wijzigingen zich verspreiden. + +Heb je meer vragen over Aspose.Words of lettertype‑beheer? Laat een reactie achter, bekijk de officiële Aspose‑documentatie, of start een nieuw project en speel met de bovenstaande code. Veel plezier met coderen, en moge je documenten altijd precies renderen zoals bedoeld! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/basic-conversions/_index.md b/words/english/net/basic-conversions/_index.md index 0ae161b7d7..ce66169fd2 100644 --- a/words/english/net/basic-conversions/_index.md +++ b/words/english/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Basic Conversions walks you through basic document conversions using the Aspose. | [Save PDF To Word Format (Docx)](./pdf-to-docx/) | Learn how to convert a PDF to a Word document (Docx) using Aspose.Words for .NET in this detailed, step-by-step guide. Perfect for developers. | | [How to Export LaTeX from Word – Step‑by‑Step Guide](./how-to-export-latex-from-word-step-by-step-guide/) | Learn how to export LaTeX from Word using Aspose.Words for .NET. Step‑by‑step guide with code examples for developers. | | [convert word to pdf in C# using Aspose.Words – Guide](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Learn how to convert Word documents to PDF in C# using Aspose.Words. Step‑by‑step guide with code examples for developers. | +| [Convert Word to PDF in C# – Full Guide with Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Learn how to convert Word documents to PDF in C# using Aspose.Words. Detailed step‑by‑step guide with code examples. | | [Save Word as PDF with Aspose.Words – Complete C# Guide](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Learn how to save Word documents as PDF using Aspose.Words in C#. Detailed step‑by‑step guide with code examples. | diff --git a/words/english/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/english/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..72a17208dd --- /dev/null +++ b/words/english/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-05 +description: Convert Word to PDF in C# using Aspose.Words. Learn how to save docx + as PDF, export accessible PDF, and load Word document efficiently. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: en +og_description: Convert Word to PDF in C# with a step‑by‑step guide. Discover how + to save docx as PDF, export accessible PDF, and load Word document using Aspose.Words. +og_title: Convert Word to PDF in C# – Complete Aspose.Words Tutorial +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Convert Word to PDF in C# – Full Guide with Aspose.Words +url: /net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert Word to PDF in C# – Complete Programming Tutorial + +Ever wondered how to **convert word to pdf** without wrestling with fiddly command‑line tools or third‑party services? You're not the only one. Many developers hit that wall when a client asks for an accessible PDF straight from a DOCX file. The good news? With a few lines of C# and the powerful Aspose.Words library, you can turn a Word document into a standards‑compliant PDF in a snap. + +In this guide we’ll walk through everything you need to know: from **load word document** basics, through configuring the right options to **how to export accessible pdf**, and finally saving the result so you can **save docx as pdf** reliably. By the end you’ll have a ready‑to‑run snippet that you can drop into any .NET project. + +> **Pro tip:** If you’re targeting PDF/UA‑2 compliance (the accessibility standard that many government agencies require), the same code works without any extra steps—just set the right `PdfCompliance` flag. + +--- + +## What You’ll Learn + +- How to **load word document** using Aspose.Words in C#. +- The exact settings needed to **how to export accessible pdf** (PDF/UA‑2). +- A complete, runnable example that **save docx as pdf** with one method call. +- Common pitfalls when you **c# convert docx pdf** and how to avoid them. +- Quick ways to verify that the generated PDF meets accessibility expectations. + +No external tools, no obscure configuration files—just pure C# code you can compile today. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +1. **.NET 6.0** (or any recent .NET version) installed. Older frameworks work too, but the syntax below assumes the modern SDK. +2. A **license** for Aspose.Words for .NET. The library offers a free trial, but for production you’ll need a valid key. +3. The **Aspose.Words** NuGet package added to your project: + +```bash +dotnet add package Aspose.Words +``` + +That’s it—no additional binaries, no COM interop, just a clean NuGet reference. + +--- + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +--- + +## Step‑by‑Step Implementation + +Below we break the process into logical chunks. Each step contains a small code snippet, an explanation of **why** it matters, and a tip that comes from real‑world usage. + +### ## Convert Word to PDF – Load the Source Document + +The first thing you need to do is **load word document** into memory. Aspose.Words abstracts away the OpenXML parsing, so you can work with DOCX, DOC, or even RTF files without worrying about format quirks. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +Loading the file creates a `Document` object that represents the entire Word file, including headers, footers, styles, and hidden metadata. If you skip this step or try to read the file as a raw stream, you’ll lose the layout information that later determines how the PDF looks. + +> **Side note:** The same `Document` constructor works for `.doc` and `.rtf`. That means you can **c# convert docx pdf** even when the source isn’t strictly a DOCX. + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +Now that the document is in memory, we tell Aspose.Words how we want the PDF to be generated. For most use‑cases, the default settings are fine, but when you need an **accessible PDF** you must enable the PDF/UA‑2 compliance flag. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +`PdfCompliance.PdfUAXmpA2` tells the library to embed the necessary tags and structures that screen readers rely on. Without this flag, you might get a perfectly looking PDF that fails an accessibility audit. + +> **Tip:** If you only need a regular PDF, you can drop the `Compliance` line. The rest of the options still give you a high‑quality output. + +### ## Convert Word to PDF – Write the File + +With the options ready, the final step is to **save docx as pdf**. This single call does all the heavy lifting: layout conversion, font embedding, and accessibility tagging. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- A PDF file at `outputPath` that mirrors the Word layout. +- If you used the `PdfUAXmpA2` flag, the PDF will be marked as PDF/UA‑2 compliant. +- All fonts are embedded, so the file looks identical on any machine. + +### ## Verify the Accessible PDF (Optional but Recommended) + +After conversion, it’s a good idea to double‑check that the PDF really **how to export accessible pdf** correctly. You can use free tools like Adobe Acrobat Reader’s “Accessibility Check” or the open‑source `pdfcpu` validator. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +If the validator reports no errors, you’ve successfully **convert word to pdf** with full accessibility support. + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| Missing fonts | The source DOCX uses a custom font not installed on the server. | Set `EmbedFullFonts = true` or install the font on the machine. | +| Large file size | Images are embedded at full resolution. | Use `ImageCompression = PdfImageCompression.Jpeg` and set `JpegQuality` to a lower value. | +| Broken hyperlinks | Links point to relative paths that don’t exist on the client. | Ensure URLs are absolute or adjust `HyperlinkTarget` property. | +| Accessibility tags missing | `Compliance` flag not set. | Add `Compliance = PdfCompliance.PdfUAXmpA2` as shown above. | + +Keeping these in mind will make your **c# convert docx pdf** routine robust and production‑ready. + +--- + +## Full Working Example + +Putting it all together, here’s a self‑contained console app you can compile and run right now. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** After running the program, you’ll find `output.pdf` in `C:\Docs`. Open it in any PDF viewer; the layout should match `input.docx` pixel‑for‑pixel, and an accessibility check will confirm PDF/UA‑2 compliance. + +--- + +## Conclusion + +We’ve just walked through a complete, end‑to‑end solution for how to **convert word to pdf** using C# and Aspose.Words. By **load word document**, configuring the right `PdfSaveOptions`, and finally **save docx as pdf**, you get a high‑quality, accessible PDF with minimal code. Whether you’re building a document‑generation microservice, an on‑premise batch converter, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-markdownsaveoptions/_index.md b/words/english/net/programming-with-markdownsaveoptions/_index.md index 530ef54fd0..e686e24bbd 100644 --- a/words/english/net/programming-with-markdownsaveoptions/_index.md +++ b/words/english/net/programming-with-markdownsaveoptions/_index.md @@ -29,7 +29,9 @@ Words Processing with MarkdownSaveOptions is an in-depth resource that walks you | [How to Use Markdown: Convert DOCX to Markdown with LaTeX Equations](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | Learn how to convert DOCX files to Markdown while preserving LaTeX equations using Aspose.Words for .NET. | | [Save docx as markdown – Complete C# Guide with LaTeX Equations](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | Learn how to save DOCX as Markdown with LaTeX equations using Aspose.Words for .NET. | | [save docx as markdown – Full C# Guide with Image Extraction](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Learn how to save DOCX as Markdown with image extraction using Aspose.Words for .NET. | +| [Convert DOCX to Markdown – Extract Images from DOCX with Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Learn how to extract images while converting DOCX to Markdown using Aspose.Words for .NET. | | [Convert docx to markdown – Step‑by‑Step C# Guide](./convert-docx-to-markdown-step-by-step-c-guide/) | Learn how to convert DOCX files to Markdown in C# with a detailed step‑by‑step guide using Aspose.Words for .NET. | +| [Convert Word to Markdown – Full Guide with PDF/UA Export](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Learn how to convert Word documents to Markdown and export PDF/UA using Aspose.Words for .NET in a comprehensive step‑by‑step guide. | | [How to Export Markdown from Word – Complete C# Guide](./how-to-export-markdown-from-word-complete-c-guide/) | | | [How to Export Markdown from DOCX – Complete Guide](./how-to-export-markdown-from-docx-complete-guide/) | | | [How to Save Markdown from DOCX – Step‑by‑Step Guide](./how-to-save-markdown-from-docx-step-by-step-guide/) | Learn how to save DOCX as Markdown with a detailed step‑by‑step guide using Aspose.Words for .NET. | diff --git a/words/english/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/english/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..7d6631f868 --- /dev/null +++ b/words/english/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Learn how to convert DOCX to Markdown and extract images from DOCX in + C#. Step‑by‑step guide with full code and tips. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: en +og_description: Convert DOCX to Markdown and extract images from DOCX using Aspose.Words. + Complete C# tutorial with code, explanation, and best‑practice tips. +og_title: Convert DOCX to Markdown – Extract Images from DOCX in C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Convert DOCX to Markdown – Extract Images from DOCX with Aspose.Words +url: /net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert DOCX to Markdown – Extract Images from DOCX in C# + +Ever needed to **convert DOCX to Markdown** but struggled with the images disappearing in the output? You're not the only one. In many projects the markdown version is perfect for version‑control or static‑site generators, yet the pictures get left behind, turning a rich document into a barren text file. + +The good news? With a few lines of C# and Aspose.Words you can **convert DOCX to Markdown** *and* **extract images from DOCX** automatically. This guide walks you through the whole process, explains why each piece matters, and even shows you how to keep your image folder tidy. + +## What You'll Learn + +- How to load a DOCX that contains pictures. +- How to define a custom `IResourceSavingCallback` that decides where each image lands. +- How to configure `MarkdownSaveOptions` so the generated markdown references the extracted images correctly. +- Tips for handling edge cases like duplicate image names or non‑PNG formats. +- A complete, copy‑and‑paste‑ready code sample you can run today. + +### Prerequisites + +- .NET 6.0 or later (the API works on .NET Core, .NET Framework, and .NET 5+). +- A license for **Aspose.Words for .NET** (the free trial works for testing). +- Basic familiarity with C# and Visual Studio (or your favorite IDE). + +If you’ve got those, let’s dive in. + +--- + +## Step 1: Set Up the Project and Install Aspose.Words + +First, create a new console app (or integrate into an existing solution). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tip:** Use the latest NuGet version (as of April 2026 it’s 24.12) to get the newest markdown export improvements. + +--- + +## Step 2: Create a Callback to Save Images Where You Want Them + +Aspose.Words lets you intercept every resource (images, SVGs, etc.) that gets written during the markdown export. By implementing `IResourceSavingCallback` you can: + +1. Choose a folder that lives next to your markdown file. +2. Generate a unique filename (so you never overwrite an existing image). +3. Decide the format (here we force PNG for consistency). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Why a GUID‑based name? + +If the source DOCX contains two pictures with the same original name, a simple copy‑paste would overwrite one of them. Using `Guid.NewGuid()` guarantees uniqueness, which is especially handy when you run the conversion many times in an automated pipeline. + +--- + +## Step 3: Load the DOCX and Wire Up the Markdown Options + +Now we bring the document into memory and attach the callback we just built. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### What the code does, step by step + +| Step | Purpose | +|------|---------| +| **Define paths** | Keeps your project flexible; you can point to any folder without recompiling. | +| **Load the DOCX** | `Document` parses the Word file, making all elements (paragraphs, tables, pictures) accessible. | +| **Configure `MarkdownSaveOptions`** | The `ResourceSavingCallback` is the hook that extracts images. Without it, Aspose.Words would embed the images as base64 strings or drop them entirely, depending on settings. | +| **Save** | `doc.Save` writes the markdown file and triggers the callback for each image. | + +--- + +## Step 4: Verify the Output – What Should You See? + +After running the program, open `DocWithImages.md`. You’ll notice markdown image links that look like this: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +And in `C:\Docs\MarkdownResources` you’ll find a series of PNG files with GUID names. Open any of them – they should be identical to the pictures that were embedded in the original DOCX. + +If you open the markdown file in a viewer that respects relative paths (e.g., VS Code preview, GitHub, or a static‑site generator), the images will render just as they did in Word. + +### Common Pitfalls & How to Avoid Them + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| Images appear as broken links | The `ResourceFileName` wasn’t set, so the markdown points to a non‑existent file. | Ensure `args.ResourceFileName = newFileName;` inside the callback. | +| PNG files are huge | Original images were JPEG or BMP; converting to PNG can increase size. | Detect the original format via `args.ResourceContentType` and preserve it: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplicate images still appear | You used a static filename instead of a GUID. | Switch back to GUID logic or add a counter per image type. | +| Conversion throws `FileNotFoundException` | The source DOCX path is wrong or the folder lacks read permission. | Verify the path and grant appropriate file‑system rights. | + +--- + +## Step 5: Advanced Tweaks (Optional) + +### 5.1 Preserve Original Image Formats + +If you want the output images to keep their original extensions, modify the callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Embed Images as Base64 (When You *Don’t* Want Separate Files) + +Sometimes a single‑file markdown is preferable (e.g., for sending via email). Change the option: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +But remember: **extract images from DOCX** is the primary goal for most static‑site workflows, so the folder approach is usually the better choice. + +--- + +## Full Working Example (Copy‑Paste Ready) + +Below is the entire program in one file. Just replace the paths with your own and run. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Run it with `dotnet run`. When the console prints the ✅ line, open the markdown file and you should see the images rendered correctly. + +--- + +## Conclusion + +You now have a **complete, production‑ready solution to convert DOCX to Markdown and extract images from DOCX** using Aspose.Words in C#. The primary keyword appears throughout the guide, reinforcing relevance for both search engines and AI assistants. + +In a single pass the code: + +1. Loads a Word document. +2. Intercepts every image via `IResourceSavingCallback`. +3. Saves each image to a predictable folder with a unique name. +4. Generates markdown that references those images. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/english/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..ee6f5b3e87 --- /dev/null +++ b/words/english/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Convert Word to Markdown quickly and also learn how to save as PDF/UA + in C#. Step‑by‑step code, tips and edge‑case handling. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: en +og_description: Convert Word to Markdown and save as PDF/UA with Aspose.Words. Learn + the why, the how, and best‑practice tips in one concise guide. +og_title: Convert Word to Markdown – Complete C# Tutorial +tags: +- Aspose.Words +- C# +- Document Conversion +title: Convert Word to Markdown – Full Guide with PDF/UA Export +url: /net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert Word to Markdown – Full Guide with PDF/UA Export + +Ever wondered how to **convert Word to Markdown** without losing equations or images? You're not the only one. Many developers need a reliable way to turn `.docx` files into clean Markdown while still being able to **save as PDF/UA** for accessibility‑compliant PDFs. In this tutorial we’ll walk through a complete, ready‑to‑run solution using Aspose.Words for .NET, explain why each setting matters, and show you how to handle the trickier parts like OfficeMath and floating shapes. + +By the end of this guide you’ll have a single C# program that: + +1. Loads a Word document with relaxed recovery (so corrupted files don’t break the run). +2. Exports it to Markdown, turning equations into LaTeX and storing images via a custom callback. +3. Saves the same document as a PDF/UA‑2 compliant file, embedding floating shapes as inline tags. + +Sounds like a lot? No sweat—let’s dive in. + +## What You’ll Need + +- **Aspose.Words for .NET** (latest version, 23.x at the time of writing). +- A .NET development environment (Visual Studio 2022, Rider, or the `dotnet` CLI). +- A sample Word file (`input.docx`) placed in a folder you can reference. +- Basic familiarity with C# syntax—nothing exotic, just a few `using` statements. + +> **Pro tip:** If you’re using a NuGet package manager, add the library with +> `dotnet add package Aspose.Words` or via the Visual Studio NuGet UI. + +## Step 1 – Load the Word Document with Relaxed Recovery + +When you receive Word files from external sources they might contain minor corruption. Enabling **Relaxed** recovery tells Aspose.Words to keep going instead of throwing an exception. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Why this matters:** +- `RecoveryMode.Relaxed` prevents a single malformed paragraph from aborting the whole conversion. +- Providing a `FontSettings` object ensures that any missing fonts are substituted gracefully, which is crucial when you later render equations as LaTeX. + +## Step 2 – Export to Markdown (OfficeMath → LaTeX, Images via Callback) + +Markdown doesn’t have a native way to represent Word equations. Aspose.Words can translate **OfficeMath** objects into LaTeX, which most Markdown renderers understand. Images, however, need to be saved somewhere; a custom **resource‑saving callback** gives you full control over the folder structure and naming. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### The Resource‑Saving Callback + +Below is a tiny implementation that stores every image in a sub‑folder called `images` and names the files `img001.png`, `img002.png`, etc. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Why you need this:** +- Without a callback, Aspose.Words creates a flat folder with random GUID names, which makes version control messy. +- By controlling the naming scheme you keep the Markdown repository tidy and reproducible. + +### Expected Markdown Output + +Open `doc.md` after the run and you’ll see: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Equations appear as LaTeX wrapped in `$$ … $$`, and images reference the `images` folder you just created. + +## Step 3 – Export to PDF/UA‑2 (Accessibility‑Ready) + +If you need to share the document with users who rely on screen readers or other assistive tech, **PDF/UA‑2** compliance is the gold standard. Aspose.Words can enforce this with a single flag, and it can also flatten floating shapes into inline tags so they’re not lost during the conversion. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Why PDF/UA matters:** +- PDF/UA (Universal Accessibility) guarantees that the resulting PDF contains proper tagging, logical reading order, and alternative text for images. +- Setting `ExportFloatingShapesAsInlineTag` ensures that shapes like text boxes or callouts are not omitted or misplaced—a common pitfall when converting complex layouts. + +### Verifying PDF/UA Compliance + +After the export, open the PDF in Adobe Acrobat Pro and run **“Accessibility Check”** (Tools → Accessibility → Full Check). If the tool reports **0 errors**, you’ve succeeded. + +## Edge Cases & Common Pitfalls + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word file contains **unsupported fonts** | Fonts may be substituted, breaking equation layout | Supply a custom `FontSettings` with fallback fonts. | +| Large documents (> 100 MB) | Memory pressure during conversion | Use `LoadOptions` with `LoadFormat.Docx` and stream the file. | +| Images are **EMF/WMF** vector graphics | They may be rasterized unintentionally | Convert them to PNG via `ImageSaveOptions` before saving. | +| PDF/UA fails validation on **nested tables** | Tagging can become ambiguous | Enable `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` to help the engine. | +| Need to **preserve custom styles** | Markdown has limited styling capabilities | Export a CSS file alongside the Markdown and reference it. | + +## Full Working Example (All Code Together) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Run the program, and you’ll find both `doc.md` (with LaTeX equations and clean image links) and `doc.pdf` (fully PDF/UA‑2 compliant) sitting in `YOUR_DIRECTORY`. + +## Visual Overview + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Alt text:* **convert word to markdown example** – diagram of the conversion pipeline from a Word file to Markdown and PDF/UA. + +## Recap & Next Steps + +We’ve just **converted Word to Markdown** while keeping equations intact, stored images in a tidy folder, and produced a **save as PDF/UA** file that passes accessibility checks. The key takeaways are: + +- Use `LoadOptions.RecoveryMode.Relaxed` to tolerate imperfect Word files. +- Set `OfficeMathExportMode` to `LaTeX` for clean equation rendering. +- Implement a `ResourceSavingCallback` to control image output. +- Enable `PdfCompliance.PdfUAXmpA2` and `ExportFloatingShapesAsInlineTag` for a standards‑compliant PDF. + +### What to Explore Next? + +- **Custom CSS for Markdown** – generate a stylesheet that mirrors your Word styles. +- **Batch processing** – loop over a directory of `.docx` files to automate large migrations. +- **Advanced PDF/UA features** – add custom tags, set language attributes, or embed audio descriptions. +- **Integration with CI/CD** – ensure every build produces accessible PDFs automatically. + +If you hit a snag, double‑check that your Aspose.Words version matches the API used here, and remember that the library’s own docs are a solid secondary reference. + +Happy coding, and may your documents stay both beautiful **and** accessible! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/programming-with-txtsaveoptions/_index.md b/words/english/net/programming-with-txtsaveoptions/_index.md index 4c280c244a..a843e121c3 100644 --- a/words/english/net/programming-with-txtsaveoptions/_index.md +++ b/words/english/net/programming-with-txtsaveoptions/_index.md @@ -28,6 +28,7 @@ Thanks to these tutorials, you will be able to fully exploit the functionalities | [Add Bidi Marks in Word Document](./add-bidi-marks/) | Learn how to add bidirectional (Bidi) marks in Word documents using Aspose.Words for .NET with this guide. Ensure proper text direction for multi-language content. | | [Use Tab Character Per Level For List Indentation](./use-tab-character-per-level-for-list-indentation/) | Learn how to create multi-level lists with tabbed indentation using Aspose.Words for .NET. Follow this guide for precise list formatting in your documents. | | [Use Space Character Per Level For List Indentation](./use-space-character-per-level-for-list-indentation/) | Learn how to create multi-level lists with space character indentation in Aspose.Words for .NET. Step-by-step guide for precise document formatting. | +| [save docx as txt – Export Word equations to LaTeX with C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Learn how to export Word equations to LaTeX while saving a DOCX as TXT using Aspose.Words for .NET and C#. | {{< /blocks/products/pf/tutorial-page-section >}} @@ -38,4 +39,4 @@ Thanks to these tutorials, you will be able to fully exploit the functionalities {{< /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/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/english/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..2daf0ccbce --- /dev/null +++ b/words/english/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-04-05 +description: save docx as txt with Aspose.Words – quickly convert Word to txt and + learn how to export math equations as LaTeX. Simple C# code, no extra tools needed. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: en +og_description: save docx as txt in C# and see how to export math to LaTeX. Follow + this step‑by‑step guide to convert Word to txt with equations intact. +og_title: save docx as txt – Export Word equations to LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: save docx as txt – Export Word equations to LaTeX with C# +url: /net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# save docx as txt – Export Word equations to LaTeX with C# + +Ever needed to **save docx as txt** but worried that your equations would disappear or turn into unreadable gibberish? You're not the only one. Many developers hit that wall when they try to **convert word to txt** for downstream processing, especially when the source file contains Office Math objects. + +The good news? With a few lines of C# and the right options, you can not only **convert Word to txt** but also keep every equation as clean LaTeX markup. In this tutorial we’ll walk through the whole process, explain why each setting matters, and show you how to verify the result. + +We'll cover: + +* Installing the Aspose.Words for .NET library +* Loading a `.docx` that contains math equations +* Configuring `TxtSaveOptions` so that **how to export math** becomes a LaTeX‑friendly string +* Saving the file and checking the output + +By the end, you’ll have a reusable snippet that lets you **save docx as txt** while preserving every formula as LaTeX—perfect for scientific pipelines, static site generators, or any workflow that needs plain‑text math. + +--- + +## Prerequisites + +Before we dive in, make sure you have: + +* .NET 6.0 or later (the code works with .NET Framework 4.6+ as well) +* Visual Studio 2022 (or any IDE you prefer) +* The **Aspose.Words for .NET** NuGet package – install it with + +```bash +dotnet add package Aspose.Words +``` + +No additional converters or external tools are required; Aspose.Words handles the heavy lifting internally. + +--- + +## Step 1: Install and reference Aspose.Words + +First, add the library to your project. If you’re using the command line, run the command above. In Visual Studio you can also right‑click **Dependencies → Manage NuGet Packages** and search for *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Use the latest stable version (as of April 2026 it’s 24.10). Newer releases bring bug fixes for OfficeMath handling, so you’ll avoid surprising missing symbols. + +--- + +## Step 2: Load the source document + +Now we pull the `.docx` that contains the equations you want to keep. The `Document` class abstracts the whole Word file, giving you access to text, images, and Office Math objects. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Why load it first? Aspose.Words parses the file into an object model, allowing us to inspect or modify content before we decide how to export it. This is where **how to export math** decisions start to matter. + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +The heart of the solution is the `TxtSaveOptions` class. By default, saving to TXT strips out Office Math entirely. Setting `OfficeMathExportMode` to `LaTeX` tells the library to translate each equation into its LaTeX representation. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX is the lingua franca of scientific publishing. By exporting math this way, you keep the semantics of the equation instead of a flat image or a garbled string. If you later feed the TXT into a Markdown processor that supports MathJax, the equations will render perfectly. + +--- + +## Step 4: Save the document as plain‑text + +With the options configured, the final step is a one‑liner that writes the file to disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +That’s it—your `.docx` is now a `.txt` file where every equation appears as a LaTeX snippet, ready for downstream consumption. + +--- + +## Verifying the output (How to save txt correctly) + +Open `MathSample.txt` in any text editor. You should see something like: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +If you spot raw Word‑specific characters (e.g., `?` or missing symbols), double‑check that: + +* You’re using a recent Aspose.Words version (older builds had bugs with OfficeMath). +* The source document actually contains **OfficeMath** objects—not legacy Equation Editor objects. For the latter, you may need to convert them manually or use the `ConvertMathToOfficeMath` method before saving. + +--- + +## Common Variations & Edge Cases + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** objects | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **You need plain Unicode math, not LaTeX** | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **You want to keep the original file name** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +These tweaks answer the “**how to export math**” question for different pipelines, ensuring your solution is robust no matter the source. + +--- + +## Full Working Example (All steps in one place) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Run the program, open the generated `.txt`, and you’ll see the LaTeX equations embedded right where they belonged. This is the most straightforward way to **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/english/net/working-with-fonts/_index.md b/words/english/net/working-with-fonts/_index.md index 96816bbca5..5bc797a23e 100644 --- a/words/english/net/working-with-fonts/_index.md +++ b/words/english/net/working-with-fonts/_index.md @@ -46,6 +46,7 @@ Whether you want to format text with different fonts, set font substitution rule | [Font Settings Default Instance](./font-settings-default-instance/) | In this tutorial, learn how to configure default font settings in a Word document with Aspose.Words for .NET. | | [Get List Of Available Fonts](./get-list-of-available-fonts/) | Discover how to get a list of available fonts using Aspose.Words for .NET in this detailed step-by-step tutorial. Boost your font management skills. | | [Receive Notifications Of Fonts](./receive-notifications-of-fonts/) | Learn how to receive missing or substituted font notifications when using Aspose.Words for .NET. | +| [Aspose Font Substitution – Detect Missing Fonts in Word Documents](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Learn how to detect missing fonts in Word documents using Aspose.Words for .NET with this step-by-step tutorial. | | [Receive Warning Notification](./receive-warning-notification/) | Learn how to receive a warning notification when using Aspose.Words for .NET and manage any issues or warnings in your documents. | | [Resource Steam Font Source Example](./resource-steam-font-source-example/) | Learn how to use the Resource Stream Font Source to load custom fonts into Aspose.Words for .NET. | | [Get Substitution Without Suffixes](./get-substitution-without-suffixes/) | In this tutorial, learn how to get suffixless overrides in a Word document with Aspose.Words for .NET. | @@ -59,4 +60,4 @@ Whether you want to format text with different fonts, set font substitution rule {{< /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/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/english/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..cd966002e9 --- /dev/null +++ b/words/english/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-04-05 +description: Aspose font substitution guide to detect missing fonts while loading + a Word document. Learn to configure font settings and handle missing fonts efficiently. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: en +og_description: Aspose font substitution guide to detect missing fonts while loading + a Word document. Learn to configure font settings and handle missing fonts efficiently. +og_title: Aspose Font Substitution – Detect Missing Fonts in Word Documents +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose Font Substitution – Detect Missing Fonts in Word Documents +url: /net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Detect Missing Fonts in Word Documents + +Ever run into a Word file that looks perfect on one machine but shows odd font changes on another? That's the classic **aspose font substitution** problem, and it usually means some fonts are missing on the target system. In this tutorial we’ll show you, step‑by‑step, how to **detect missing fonts** when you **load a Word document**, how to **configure font settings**, and what to do to **handle missing fonts** gracefully. + +We'll walk through a complete, runnable C# example, explain why each line matters, and even show you the console output you should expect. By the end you’ll be able to spot font substitutions the moment a document is loaded—no guesswork required. + +## What You’ll Learn + +- How to enable Aspose.Words’ diagnostic collector for font warnings. +- The exact code needed to **load a Word document** with custom **font settings**. +- How to iterate over `WarningInfo` objects to list every substituted font. +- Tips for suppressing unwanted warnings or providing fallback fonts. +- A ready‑to‑run sample you can copy‑paste into Visual Studio. + +### Prerequisites + +- .NET 6.0 or later (the API works the same on .NET Framework). +- Aspose.Words for .NET (NuGet package `Aspose.Words`). +- A Word file that references a font you don’t have installed (e.g., `MissingFont.docx`). + +If you’ve got those, let’s dive in. + +## Step 1 – Enable the Diagnostic Collector (Configure Font Settings) + +First things first: Aspose.Words only records font substitution warnings if you tell it to. That’s done by creating a `FontSettings` object and assigning it to a `LoadOptions` instance. Think of this as turning on the “debug lights” for font handling. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Why?** +Without a `FontSettings` object the warning collector stays silent, and you’ll never know which fonts were swapped. By initializing it empty we let Aspose use the default system fonts *and* keep track of any substitutions. + +> **Pro tip:** If you know a specific folder contains corporate fonts, point `FontSettings` there with `SetFontsFolder("path")`. That can reduce the number of missing‑font warnings. + +## Step 2 – Load the Document with the Configured Options (Load Word Document) + +Now that the collector is active, load your `.docx` file using the same `LoadOptions`. This is the moment where Aspose scans the document, looks for every font reference, and decides whether a substitution is needed. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Why does this matter?** +If you simply called `new Document("MissingFont.docx")`, the default settings would apply *and* the warning list would stay empty. Passing `loadOptions` guarantees that the diagnostic collector is hooked into the loading pipeline. + +## Step 3 – Retrieve and Display Font Substitution Warnings (Detect Missing Fonts) + +After the document is in memory, Aspose stores any warnings in `document.WarningCallback.Warnings`. Loop through that collection, filter for `WarningType.FontSubstitution`, and print the description. Each description tells you which font was missing and which one was used instead. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Expected console output** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +That output tells you exactly which fonts are missing on the machine running the code. You can now decide whether to install the missing fonts, embed them in the document, or keep the substitution. + +![Console output showing aspose font substitution warnings](/images/aspose-font-substitution-console.png) + +*Image alt text:* aspose font substitution – console output listing substituted fonts + +## Step 4 – Optional: Customize the Substitution Behavior (Handle Missing Fonts) + +Sometimes you don’t just want to know *that* a substitution happened—you want to control *how* it happens. Aspose.Words lets you register a custom `IFontSubstitutionRule`. Below is a quick example that forces any missing font to fall back to `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**When would you use this?** +If you’re generating PDFs for a web service and you know every client can render `Tahoma`, forcing the fallback guarantees visual consistency without having to ship dozens of font files. + +## Full Working Example (All Steps Combined) + +Here’s the entire program you can paste into a new console project. It compiles as‑is, assuming you’ve installed the Aspose.Words NuGet package. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Run the program, watch the console, and you’ll see every missing‑font event printed out. From there you can decide whether to install the missing fonts, embed them, or keep the fallback. + +## Frequently Asked Questions + +**Q: Does this work with PDF conversion?** +Yes. When you later call `doc.Save("output.pdf")`, any fonts that were substituted during loading will be the ones embedded in the PDF. So catching the warnings early helps you avoid surprise font changes in the final PDF. + +**Q: What if I have many documents to process?** +Wrap the loading logic in a try‑catch block and reuse a single `FontSettings` instance across documents. That reduces overhead and keeps the warning collector active for each file. + +**Q: Can I suppress the warnings entirely?** +You can set `loadOptions.WarningCallback = null;` before loading, but you’ll lose the ability to **detect missing fonts**—which is usually not what you want. + +## Conclusion + +We’ve covered everything you need to master **aspose font substitution**: enabling the diagnostic collector, loading a Word file with custom **font settings**, extracting the list of missing fonts, and even overriding the default substitution rule to **handle missing fonts** your way. With just a few lines of C# you gain full visibility into font issues that would otherwise hide behind subtle layout changes. + +Next steps? Try embedding the original fonts into the document with `FontSettings.SetFontsFolder` or explore `FontSourceBase` to load fonts from a database. You might also experiment with the `Document.BuiltInStyle` collection to see how style‑level font changes propagate. + +Got more questions about Aspose.Words or font management? Drop a comment, explore the official Aspose documentation, or fire up a new project and play around with the code above. Happy coding, and may your documents always render exactly as intended! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/basic-conversions/_index.md b/words/french/net/basic-conversions/_index.md index b7640635ad..dc2a8db394 100644 --- a/words/french/net/basic-conversions/_index.md +++ b/words/french/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Conversions de base vous guide dans les conversions de documents de base avec la | [Enregistrer un PDF au format Word (Docx)](./pdf-to-docx/) | Découvrez comment convertir un PDF en document Word (Docx) avec Aspose.Words pour .NET grâce à ce guide détaillé, étape par étape. Idéal pour les développeurs. | | [Convertir Word en PDF en C# avec Aspose.Words – Guide](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Apprenez à convertir un document Word en PDF en C# avec Aspose.Words grâce à ce guide étape par étape. | | [Comment exporter LaTeX depuis Word – Guide étape par étape](./how-to-export-latex-from-word-step-by-step-guide/) | Apprenez à exporter le contenu d'un document Word au format LaTeX avec Aspose.Words pour .NET grâce à ce guide détaillé étape par étape. | +| [Convertir Word en PDF en C# – Guide complet avec Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Apprenez à convertir un document Word en PDF en C# avec Aspose.Words grâce à un guide complet étape par étape. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/french/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..9b10c5a517 --- /dev/null +++ b/words/french/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,195 @@ +--- +category: general +date: 2026-04-05 +description: Convertir Word en PDF en C# avec Aspose.Words. Apprenez comment enregistrer + un docx en PDF, exporter un PDF accessible et charger efficacement un document Word. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: fr +og_description: Convertir Word en PDF en C# avec un guide étape par étape. Découvrez + comment enregistrer un docx en PDF, exporter un PDF accessible et charger un document + Word à l’aide d’Aspose.Words. +og_title: Convertir Word en PDF en C# – Tutoriel complet Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Convertir Word en PDF en C# – Guide complet avec Aspose.Words +url: /fr/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir Word en PDF en C# – Tutoriel de programmation complet + +Vous vous êtes déjà demandé comment **convert word to pdf** sans vous battre avec des outils en ligne de commande compliqués ou des services tiers ? Vous n'êtes pas le seul. De nombreux développeurs rencontrent ce problème lorsqu'un client demande un PDF accessible directement à partir d'un fichier DOCX. La bonne nouvelle ? Avec quelques lignes de C# et la puissante bibliothèque Aspose.Words, vous pouvez transformer un document Word en un PDF conforme aux normes en un clin d'œil. + +Dans ce guide, nous passerons en revue tout ce que vous devez savoir : des bases du **load word document**, en passant par la configuration des bonnes options pour **how to export accessible pdf**, et enfin en enregistrant le résultat afin que vous puissiez **save docx as pdf** de manière fiable. À la fin, vous disposerez d’un extrait prêt à l’emploi que vous pourrez intégrer à n’importe quel projet .NET. + +> **Conseil pro :** Si vous visez la conformité PDF/UA‑2 (la norme d'accessibilité requise par de nombreuses agences gouvernementales), le même code fonctionne sans étapes supplémentaires — il suffit de définir le bon drapeau `PdfCompliance`. + +## Ce que vous apprendrez + +- Comment **load word document** avec Aspose.Words en C#. +- Les paramètres exacts nécessaires pour **how to export accessible pdf** (PDF/UA‑2). +- Un exemple complet et exécutable qui **save docx as pdf** avec un seul appel de méthode. +- Les pièges courants lorsque vous **c# convert docx pdf** et comment les éviter. +- Des méthodes rapides pour vérifier que le PDF généré répond aux attentes d'accessibilité. + +Pas d'outils externes, pas de fichiers de configuration obscurs—juste du code C# pur que vous pouvez compiler dès aujourd'hui. + +## Prérequis + +Avant de commencer, assurez‑vous d'avoir : + +1. **.NET 6.0** (ou toute version .NET récente) installé. Les anciens frameworks fonctionnent aussi, mais la syntaxe ci‑dessous suppose le SDK moderne. +2. Une **licence** pour Aspose.Words for .NET. La bibliothèque propose un essai gratuit, mais pour la production vous aurez besoin d’une clé valide. +3. Le package NuGet **Aspose.Words** ajouté à votre projet : + +```bash +dotnet add package Aspose.Words +``` + +C’est tout—pas de binaires supplémentaires, pas d’interop COM, juste une référence NuGet propre. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## Implémentation étape par étape + +Ci‑dessus, nous décomposons le processus en blocs logiques. Chaque étape contient un petit extrait de code, une explication du **pourquoi** c’est important, et un conseil issu de l’expérience réelle. + +### ## Convertir Word en PDF – Charger le document source + +La première chose à faire est de **load word document** en mémoire. Aspose.Words masque le parsing OpenXML, vous permettant de travailler avec des fichiers DOCX, DOC ou même RTF sans vous soucier des particularités de format. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Pourquoi c’est important :** +Le chargement du fichier crée un objet `Document` qui représente l’ensemble du fichier Word, y compris les en‑têtes, pieds de page, styles et métadonnées cachées. Si vous sautez cette étape ou essayez de lire le fichier comme un flux brut, vous perdrez les informations de mise en page qui déterminent plus tard l’apparence du PDF. + +> **Note :** Le même constructeur `Document` fonctionne pour `.doc` et `.rtf`. Cela signifie que vous pouvez **c# convert docx pdf** même lorsque la source n’est pas strictement un DOCX. + +### ## Enregistrer le DOCX en PDF – Configurer la conformité PDF/UA‑2 + +Maintenant que le document est en mémoire, nous indiquons à Aspose.Words comment nous souhaitons que le PDF soit généré. Pour la plupart des cas d’utilisation, les paramètres par défaut conviennent, mais lorsque vous avez besoin d’un **accessible PDF**, vous devez activer le drapeau de conformité PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Pourquoi c’est important :** +`PdfCompliance.PdfUAXmpA2` indique à la bibliothèque d’intégrer les balises et structures nécessaires dont les lecteurs d’écran ont besoin. Sans ce drapeau, vous pourriez obtenir un PDF parfaitement présentable qui échoue à un audit d’accessibilité. + +> **Conseil :** Si vous n’avez besoin que d’un PDF ordinaire, vous pouvez supprimer la ligne `Compliance`. Le reste des options vous fournit toujours une sortie de haute qualité. + +### ## Convertir Word en PDF – Écrire le fichier + +Avec les options prêtes, l’étape finale consiste à **save docx as pdf**. Cet appel unique effectue tout le travail lourd : conversion de la mise en page, incorporation des polices et balisage d’accessibilité. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Ce que vous obtenez :** +- Un fichier PDF à `outputPath` qui reproduit la mise en page du Word. +- Si vous avez utilisé le drapeau `PdfUAXmpA2`, le PDF sera marqué comme conforme PDF/UA‑2. +- Toutes les polices sont incorporées, de sorte que le fichier apparaît identique sur n’importe quelle machine. + +### ## Vérifier le PDF accessible (Optionnel mais recommandé) + +Après la conversion, il est judicieux de revérifier que le PDF **how to export accessible pdf** correctement. Vous pouvez utiliser des outils gratuits comme la fonction “Vérification d’accessibilité” d’Adobe Acrobat Reader ou le validateur open‑source `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Si le validateur ne signale aucune erreur, vous avez réussi à **convert word to pdf** avec un support complet d’accessibilité. + +### ## Pièges courants lors de la conversion C# de DOCX en PDF + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| Missing fonts | The source DOCX uses a custom font not installed on the server. | Set `EmbedFullFonts = true` or install the font on the machine. | +| Large file size | Images are embedded at full resolution. | Use `ImageCompression = PdfImageCompression.Jpeg` and set `JpegQuality` to a lower value. | +| Broken hyperlinks | Links point to relative paths that don’t exist on the client. | Ensure URLs are absolute or adjust `HyperlinkTarget` property. | +| Accessibility tags missing | `Compliance` flag not set. | Add `Compliance = PdfCompliance.PdfUAXmpA2` as shown above. | + +Garder cela à l’esprit rendra votre routine **c# convert docx pdf** robuste et prête pour la production. + +## Exemple complet fonctionnel + +En rassemblant le tout, voici une application console autonome que vous pouvez compiler et exécuter dès maintenant. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Résultat attendu :** Après avoir exécuté le programme, vous trouverez `output.pdf` dans `C:\Docs`. Ouvrez-le avec n’importe quel lecteur PDF ; la mise en page doit correspondre pixel à pixel à `input.docx`, et une vérification d’accessibilité confirmera la conformité PDF/UA‑2. + +## Conclusion + +Nous venons de parcourir une solution complète, de bout en bout, pour **convert word to pdf** en utilisant C# et Aspose.Words. En **load word document**, en configurant les bons `PdfSaveOptions`, et enfin en **save docx as pdf**, vous obtenez un PDF de haute qualité et accessible avec un code minimal. Que vous construisiez un micro‑service de génération de documents, un convertisseur batch sur site, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-markdownsaveoptions/_index.md b/words/french/net/programming-with-markdownsaveoptions/_index.md index 0439984b15..6d215cca82 100644 --- a/words/french/net/programming-with-markdownsaveoptions/_index.md +++ b/words/french/net/programming-with-markdownsaveoptions/_index.md @@ -42,12 +42,18 @@ Apprenez à convertir des fichiers DOCX en Markdown avec un guide complet étape Apprenez à enregistrer des fichiers DOCX en Markdown tout en conservant les équations LaTeX avec Aspose.Words pour .NET. +### [Convertir Word en Markdown – Guide complet avec export PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) + +Apprenez à convertir des documents Word en Markdown tout en exportant un PDF conforme aux normes PDF/UA avec Aspose.Words pour .NET. + ### [Comment exporter Markdown depuis Word – Guide complet C#](./how-to-export-markdown-from-word-complete-c-guide/) ### [Comment enregistrer le Markdown depuis DOCX – Guide étape par étape](./how-to-save-markdown-from-docx-step-by-step-guide/) ### [Comment exporter Markdown depuis DOCX – Guide complet](./how-to-export-markdown-from-docx-complete-guide/) +### [Convertir DOCX en Markdown – Extraire les images du DOCX avec Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/french/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..8e92a88921 --- /dev/null +++ b/words/french/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-04-05 +description: Apprenez à convertir DOCX en Markdown et à extraire les images d’un DOCX + en C#. Guide étape par étape avec le code complet et des astuces. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: fr +og_description: Convertir DOCX en Markdown et extraire les images du DOCX à l’aide + d’Aspose.Words. Tutoriel complet C# avec code, explication et conseils de bonnes + pratiques. +og_title: Convertir DOCX en Markdown – Extraire les images d’un DOCX en C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Convertir DOCX en Markdown – Extraire les images d’un DOCX avec Aspose.Words +url: /fr/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir DOCX en Markdown – Extraire les images du DOCX en C# + +Vous avez déjà eu besoin de **convertir DOCX en Markdown** mais avez eu du mal avec les images qui disparaissent dans le résultat ? Vous n'êtes pas le seul. Dans de nombreux projets, la version markdown est parfaite pour le contrôle de version ou les générateurs de sites statiques, mais les images sont laissées de côté, transformant un document riche en un fichier texte aride. + +Bonne nouvelle ? Avec quelques lignes de C# et Aspose.Words, vous pouvez **convertir DOCX en Markdown** *et* **extraire les images du DOCX** automatiquement. Ce guide vous accompagne à travers tout le processus, explique pourquoi chaque élément est important, et montre même comment garder votre dossier d'images bien organisé. + +## Ce que vous allez apprendre + +- Comment charger un DOCX contenant des images. +- Comment définir un `IResourceSavingCallback` personnalisé qui décide où chaque image est enregistrée. +- Comment configurer `MarkdownSaveOptions` afin que le markdown généré référence correctement les images extraites. +- Conseils pour gérer les cas particuliers comme les noms d'images en double ou les formats non‑PNG. +- Un exemple de code complet, prêt à copier‑coller, que vous pouvez exécuter dès aujourd'hui. + +### Prérequis + +- .NET 6.0 ou ultérieur (l'API fonctionne sur .NET Core, .NET Framework et .NET 5+). +- Une licence pour **Aspose.Words for .NET** (l'essai gratuit suffit pour les tests). +- Une connaissance de base du C# et de Visual Studio (ou de votre IDE préféré). + +Si vous avez tout cela, plongeons‑y. + +--- + +## Étape 1 : Configurer le projet et installer Aspose.Words + +Tout d'abord, créez une nouvelle application console (ou intégrez‑la dans une solution existante). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Astuce :** Utilisez la dernière version NuGet (en date d’avril 2026, c’est la 24.12) pour bénéficier des dernières améliorations d’exportation markdown. + +--- + +## Étape 2 : Créer un rappel pour enregistrer les images où vous le souhaitez + +Aspose.Words vous permet d’intercepter chaque ressource (images, SVG, etc.) qui est écrite lors de l’exportation markdown. En implémentant `IResourceSavingCallback`, vous pouvez : + +1. Choisir un dossier qui se trouve à côté de votre fichier markdown. +2. Générer un nom de fichier unique (pour ne jamais écraser une image existante). +3. Déterminer le format (ici nous imposons le PNG pour la cohérence). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Pourquoi un nom basé sur GUID ? + +Si le DOCX source contient deux images avec le même nom d'origine, un simple copier‑coller écraserait l'une d'elles. Utiliser `Guid.NewGuid()` garantit l'unicité, ce qui est particulièrement pratique lorsque vous exécutez la conversion de nombreuses fois dans un pipeline automatisé. + +--- + +## Étape 3 : Charger le DOCX et configurer les options Markdown + +Nous chargeons maintenant le document en mémoire et attachons le rappel que nous venons de créer. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Ce que fait le code, étape par étape + +| Étape | Objectif | +|------|---------| +| **Définir les chemins** | Garde votre projet flexible ; vous pouvez pointer vers n'importe quel dossier sans recompilation. | +| **Charger le DOCX** | `Document` analyse le fichier Word, rendant tous les éléments (paragraphes, tableaux, images) accessibles. | +| **Configurer `MarkdownSaveOptions`** | Le `ResourceSavingCallback` est le crochet qui extrait les images. Sans lui, Aspose.Words incorporerait les images sous forme de chaînes base64 ou les supprimerait complètement, selon les paramètres. | +| **Enregistrer** | `doc.Save` écrit le fichier markdown et déclenche le rappel pour chaque image. | + +--- + +## Étape 4 : Vérifier la sortie – Que devez‑vous voir ? + +Après avoir exécuté le programme, ouvrez `DocWithImages.md`. Vous verrez des liens d'image markdown qui ressemblent à ceci : + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Et dans `C:\Docs\MarkdownResources` vous trouverez une série de fichiers PNG avec des noms GUID. Ouvrez‑en un – il devrait être identique aux images qui étaient intégrées dans le DOCX original. + +Si vous ouvrez le fichier markdown dans un visualiseur qui respecte les chemins relatifs (par ex., l'aperçu de VS Code, GitHub ou un générateur de site statique), les images s’afficheront exactement comme dans Word. + +### Problèmes courants & comment les éviter + +| Symptôme | Cause probable | Solution | +|---------|----------------|----------| +| Images appear as broken links | Le `ResourceFileName` n’a pas été défini, donc le markdown pointe vers un fichier inexistant. | Assurez‑vous que `args.ResourceFileName = newFileName;` soit présent dans le rappel. | +| PNG files are huge | Les images originales étaient JPEG ou BMP ; les convertir en PNG peut augmenter la taille. | Détectez le format original via `args.ResourceContentType` et conservez‑le : `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplicate images still appear | Vous avez utilisé un nom de fichier statique au lieu d’un GUID. | Revenez à la logique GUID ou ajoutez un compteur par type d’image. | +| Conversion throws `FileNotFoundException` | Le chemin du DOCX source est incorrect ou le dossier n’a pas les permissions de lecture. | Vérifiez le chemin et accordez les droits d’accès au système de fichiers appropriés. | + +--- + +## Étape 5 : Ajustements avancés (optionnel) + +### 5.1 Conserver les formats d’image d’origine + +Si vous souhaitez que les images de sortie conservent leurs extensions d'origine, modifiez le rappel : + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Incorporer les images en Base64 (Lorsque vous *ne* voulez *pas* de fichiers séparés) + +Parfois, un markdown en un seul fichier est préférable (par ex., pour l’envoi par email). Modifiez l’option : + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Mais rappelez‑vous : **extraire les images du DOCX** est l’objectif principal pour la plupart des flux de travail de sites statiques, donc l’approche par dossier est généralement la meilleure option. + +--- + +## Exemple complet fonctionnel (prêt à copier‑coller) + +Voici le programme complet dans un seul fichier. Remplacez simplement les chemins par les vôtres et exécutez. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Exécutez‑le avec `dotnet run`. Lorsque la console affiche la ligne ✅, ouvrez le fichier markdown et vous devriez voir les images correctement affichées. + +--- + +## Conclusion + +Vous disposez maintenant d’une **solution complète, prête pour la production, pour convertir DOCX en Markdown et extraire les images du DOCX** en utilisant Aspose.Words en C#. Le mot‑clé principal apparaît tout au long du guide, renforçant la pertinence tant pour les moteurs de recherche que pour les assistants IA. + +En une seule passe, le code : + +1. Charge un document Word. +2. Intercepte chaque image via `IResourceSavingCallback`. +3. Enregistre chaque image dans un dossier prévisible avec un nom unique. +4. Génère du markdown qui référence ces images. + +À partir de là, vous pouvez : + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/french/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..d7ba65a352 --- /dev/null +++ b/words/french/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-05 +description: Convertir Word en Markdown rapidement et apprendre également comment + enregistrer en PDF/UA en C#. Code étape par étape, astuces et gestion des cas limites. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: fr +og_description: Convertir Word en Markdown et enregistrer en PDF/UA avec Aspose.Words. + Découvrez le pourquoi, le comment et les conseils de bonnes pratiques dans un guide + concis. +og_title: Convertir Word en Markdown – Tutoriel complet C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Convertir Word en Markdown – Guide complet avec export PDF/UA +url: /fr/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir Word en Markdown – Guide complet avec export PDF/UA + +Vous vous êtes déjà demandé comment **convertir Word en Markdown** sans perdre les équations ou les images ? Vous n'êtes pas le seul. De nombreux développeurs ont besoin d'une méthode fiable pour transformer des fichiers `.docx` en Markdown propre tout en pouvant **enregistrer en PDF/UA** pour des PDF conformes à l'accessibilité. Dans ce tutoriel, nous parcourrons une solution complète, prête à l’emploi, utilisant Aspose.Words pour .NET, expliquerons pourquoi chaque paramètre est important et vous montrerons comment gérer les parties les plus complexes comme OfficeMath et les formes flottantes. + +À la fin de ce guide, vous disposerez d’un programme C# unique qui : + +1. Charge un document Word avec une récupération détendue (pour que les fichiers corrompus ne cassent pas l’exécution). +2. L’exporte en Markdown, transformant les équations en LaTeX et enregistrant les images via un rappel personnalisé. +3. Enregistre le même document en tant que fichier PDF/UA‑2 conforme, en incorporant les formes flottantes sous forme de balises en ligne. + +Ça semble beaucoup ? Pas de souci—plongeons‑y. + +## Ce dont vous avez besoin + +- **Aspose.Words for .NET** (dernière version, 23.x au moment de la rédaction). +- Un environnement de développement .NET (Visual Studio 2022, Rider ou le CLI `dotnet`). +- Un fichier Word d’exemple (`input.docx`) placé dans un dossier que vous pouvez référencer. +- Une connaissance de base de la syntaxe C#—rien d’exotique, juste quelques instructions `using`. + +> **Astuce pro :** Si vous utilisez un gestionnaire de paquets NuGet, ajoutez la bibliothèque avec +> `dotnet add package Aspose.Words` ou via l’interface NuGet de Visual Studio. + +## Étape 1 – Charger le document Word avec récupération détendue + +Lorsque vous recevez des fichiers Word provenant de sources externes, ils peuvent contenir de légères corruptions. Activer la récupération **Relaxed** indique à Aspose.Words de continuer au lieu de lever une exception. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Pourquoi c’est important :** +- `RecoveryMode.Relaxed` empêche un seul paragraphe malformé d’interrompre toute la conversion. +- Fournir un objet `FontSettings` garantit que les polices manquantes sont substituées de façon souple, ce qui est crucial lorsque vous rendez plus tard les équations en LaTeX. + +## Étape 2 – Exporter en Markdown (OfficeMath → LaTeX, images via rappel) + +Markdown ne possède pas de façon native de représenter les équations Word. Aspose.Words peut traduire les objets **OfficeMath** en LaTeX, que la plupart des rendus Markdown comprennent. Les images, en revanche, doivent être enregistrées quelque part ; un **rappel d’enregistrement des ressources** personnalisé vous donne un contrôle total sur la structure des dossiers et la nomenclature. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Le rappel d’enregistrement des ressources + +Voici une petite implémentation qui stocke chaque image dans un sous‑dossier nommé `images` et nomme les fichiers `img001.png`, `img002.png`, etc. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Pourquoi vous en avez besoin :** +- Sans rappel, Aspose.Words crée un dossier plat avec des noms GUID aléatoires, ce qui complique le contrôle de version. +- En contrôlant le schéma de nommage, vous gardez le dépôt Markdown propre et reproductible. + +### Sortie Markdown attendue + +Ouvrez `doc.md` après l’exécution et vous verrez : + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Les équations apparaissent sous forme de LaTeX encadrées par `$$ … $$`, et les images référencent le dossier `images` que vous venez de créer. + +## Étape 3 – Exporter en PDF/UA‑2 (Accessibilité prête) + +Si vous devez partager le document avec des utilisateurs qui s’appuient sur des lecteurs d’écran ou d’autres technologies d’assistance, la conformité **PDF/UA‑2** est la référence. Aspose.Words peut l’imposer avec un seul drapeau, et il peut également aplatir les formes flottantes en balises en ligne afin qu’elles ne soient pas perdues lors de la conversion. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Pourquoi le PDF/UA est important :** +- PDF/UA (Universal Accessibility) garantit que le PDF résultant contient un balisage correct, un ordre de lecture logique et du texte alternatif pour les images. +- Le paramètre `ExportFloatingShapesAsInlineTag` assure que les formes comme les zones de texte ou les bulles d’appel ne sont pas omises ou mal placées—un piège fréquent lors de la conversion de mises en page complexes. + +### Vérifier la conformité PDF/UA + +Après l’export, ouvrez le PDF dans Adobe Acrobat Pro et lancez le **« Accessibility Check »** (Outils → Accessibilité → Vérification complète). Si l’outil indique **0 erreur**, vous avez réussi. + +## Cas limites & pièges courants + +| Situation | Points d’attention | Solution / Recommandation | +|----------------------------------------|------------------------------------------------------|-------------------------------------------------------------| +| Le fichier Word contient **des polices non prises en charge** | Les polices peuvent être substituées, perturbant la mise en forme des équations | Fournir un `FontSettings` personnalisé avec des polices de secours. | +| Documents volumineux (> 100 Mo) | Pression mémoire pendant la conversion | Utiliser `LoadOptions` avec `LoadFormat.Docx` et diffuser le fichier. | +| Les images sont des graphiques vectoriels **EMF/WMF** | Elles peuvent être rasterisées involontairement | Les convertir en PNG via `ImageSaveOptions` avant l’enregistrement. | +| La validation PDF/UA échoue sur **des tableaux imbriqués** | Le balisage peut devenir ambigu | Activer `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` pour aider le moteur. | +| Besoin de **conserver des styles personnalisés** | Markdown possède des capacités de style limitées | Exporter un fichier CSS à côté du Markdown et le référencer. | + +## Exemple complet fonctionnel (tout le code ensemble) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Exécutez le programme, et vous trouverez à la fois `doc.md` (avec les équations LaTeX et des liens d’image propres) et `doc.pdf` (entièrement conforme PDF/UA‑2) dans `YOUR_DIRECTORY`. + +## Vue d’ensemble visuelle + +![convert word to markdown example](https://example.com/placeholder.png "exemple de conversion Word en Markdown – montre le fichier Word d’entrée, la sortie Markdown et le fichier PDF/UA") + +*Texte alternatif :* **exemple de conversion Word en Markdown** – diagramme du pipeline de conversion d’un fichier Word vers Markdown et PDF/UA. + +## Récapitulatif & étapes suivantes + +Nous venons de **convertir Word en Markdown** tout en conservant les équations intactes, de stocker les images dans un dossier ordonné, et de produire un fichier **enregistrement PDF/UA** qui passe les contrôles d’accessibilité. Les points clés sont : + +- Utiliser `LoadOptions.RecoveryMode.Relaxed` pour tolérer les fichiers Word imparfaits. +- Définir `OfficeMathExportMode` sur `LaTeX` pour un rendu d’équation propre. +- Implémenter un `ResourceSavingCallback` afin de contrôler la sortie des images. +- Activer `PdfCompliance.PdfUAXmpA2` et `ExportFloatingShapesAsInlineTag` pour un PDF conforme aux normes. + +### Que explorer ensuite ? + +- **CSS personnalisé pour Markdown** – générer une feuille de style qui reflète vos styles Word. +- **Traitement par lots** – parcourir un répertoire de fichiers `.docx` pour automatiser de grandes migrations. +- **Fonctionnalités avancées PDF/UA** – ajouter des balises personnalisées, définir des attributs de langue ou intégrer des descriptions audio. +- **Intégration CI/CD** – garantir que chaque build produit automatiquement des PDF accessibles. + +Si vous rencontrez un problème, revérifiez que votre version d’Aspose.Words correspond à l’API utilisée ici, et souvenez‑vous que la documentation officielle de la bibliothèque constitue une excellente référence secondaire. + +Bon codage, et que vos documents restent à la fois beaux **et** accessibles ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/programming-with-txtsaveoptions/_index.md b/words/french/net/programming-with-txtsaveoptions/_index.md index d904155850..f711cc289b 100644 --- a/words/french/net/programming-with-txtsaveoptions/_index.md +++ b/words/french/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Grâce à ces tutoriels, vous pourrez exploiter pleinement les fonctionnalités | [Ajouter des marques Bidi dans un document Word](./add-bidi-marks/) | Découvrez comment ajouter des marques bidirectionnelles (Bidi) dans vos documents Word avec Aspose.Words pour .NET grâce à ce guide. Assurez un sens de texte correct pour les contenus multilingues. | | [Utiliser le caractère de tabulation par niveau pour l'indentation de la liste](./use-tab-character-per-level-for-list-indentation/) | Apprenez à créer des listes à plusieurs niveaux avec indentation tabulée avec Aspose.Words pour .NET. Suivez ce guide pour une mise en forme précise des listes dans vos documents. | | [Utiliser un caractère d'espace par niveau pour l'indentation de la liste](./use-space-character-per-level-for-list-indentation/) | Apprenez à créer des listes à plusieurs niveaux avec indentation par espace dans Aspose.Words pour .NET. Guide étape par étape pour une mise en forme précise des documents. | - +| [Enregistrer docx en txt – Exporter les équations Word en LaTeX avec C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Apprenez à convertir des documents DOCX en fichiers TXT tout en exportant les équations Word au format LaTeX à l'aide de C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/french/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..e8438cb339 --- /dev/null +++ b/words/french/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Enregistrez un docx en txt avec Aspose.Words – convertissez rapidement + Word en txt et apprenez comment exporter les équations mathématiques en LaTeX. Code + C# simple, aucun outil supplémentaire requis. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: fr +og_description: Enregistrez le docx en txt en C# et découvrez comment exporter les + mathématiques vers LaTeX. Suivez ce guide étape par étape pour convertir Word en + txt avec les équations intactes. +og_title: Enregistrer le docx en txt – Exporter les équations Word vers LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Enregistrer le docx en txt – Exporter les équations Word vers LaTeX avec C# +url: /fr/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# enregistrer docx en txt – Exporter les équations Word en LaTeX avec C# + +Vous avez déjà eu besoin de **save docx as txt** mais vous craigniez que vos équations disparaissent ou se transforment en charabia illisible ? Vous n'êtes pas le seul. De nombreux développeurs rencontrent ce problème lorsqu'ils essaient de **convert word to txt** pour un traitement en aval, surtout lorsque le fichier source contient des objets Office Math. + +Bonne nouvelle ? Avec quelques lignes de C# et les bonnes options, vous pouvez non seulement **convert Word to txt** mais aussi conserver chaque équation sous forme de balisage LaTeX propre. Dans ce tutoriel, nous parcourrons l'ensemble du processus, expliquerons pourquoi chaque paramètre est important et vous montrerons comment vérifier le résultat. + +Nous couvrirons : + +* Installation de la bibliothèque Aspose.Words for .NET +* Chargement d'un `.docx` contenant des équations mathématiques +* Configuration de `TxtSaveOptions` afin que **how to export math** devienne une chaîne compatible LaTeX‑friendly +* Enregistrement du fichier et vérification de la sortie + +À la fin, vous disposerez d'un extrait réutilisable qui vous permet de **save docx as txt** tout en préservant chaque formule en LaTeX — parfait pour les pipelines scientifiques, les générateurs de sites statiques ou tout flux de travail nécessitant des mathématiques en texte brut. + +--- + +## Prérequis + +Avant de plonger, assurez‑vous d'avoir : + +* .NET 6.0 ou ultérieur (le code fonctionne également avec .NET Framework 4.6+) +* Visual Studio 2022 (ou tout IDE de votre choix) +* Le package NuGet **Aspose.Words for .NET** – installez-le avec + +```bash +dotnet add package Aspose.Words +``` + +Aucun convertisseur supplémentaire ou outil externe n'est requis ; Aspose.Words gère la lourde tâche en interne. + +--- + +## Étape 1 : Installer et référencer Aspose.Words + +Tout d'abord, ajoutez la bibliothèque à votre projet. Si vous utilisez la ligne de commande, exécutez la commande ci‑dessus. Dans Visual Studio, vous pouvez également faire un clic droit sur **Dependencies → Manage NuGet Packages** et rechercher *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Astuce :** Utilisez la dernière version stable (en avril 2026, c’est la 24.10). Les versions plus récentes apportent des corrections de bugs pour la gestion d'OfficeMath, ce qui vous évitera des symboles manquants inattendus. + +--- + +## Étape 2 : Charger le document source + +Nous chargeons maintenant le `.docx` qui contient les équations que vous souhaitez conserver. La classe `Document` abstrait l'ensemble du fichier Word, vous donnant accès au texte, aux images et aux objets Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Pourquoi le charger d'abord ? Aspose.Words analyse le fichier en un modèle d'objets, ce qui nous permet d'inspecter ou de modifier le contenu avant de décider comment l'exporter. C’est à ce moment que les décisions concernant **how to export math** commencent à compter. + +--- + +## Étape 3 : Configurer TxtSaveOptions pour l'exportation LaTeX + +Le cœur de la solution est la classe `TxtSaveOptions`. Par défaut, l'enregistrement au format TXT supprime complètement Office Math. Définir `OfficeMathExportMode` à `LaTeX` indique à la bibliothèque de traduire chaque équation en sa représentation LaTeX. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Pourquoi LaTeX ?** LaTeX est la lingua franca de la publication scientifique. En exportant les mathématiques de cette façon, vous conservez la sémantique de l'équation au lieu d'une image plate ou d'une chaîne illisible. Si vous alimentez ensuite le TXT dans un processeur Markdown qui supporte MathJax, les équations s'afficheront parfaitement. + +--- + +## Étape 4 : Enregistrer le document en texte brut + +Avec les options configurées, l'étape finale est une simple ligne de code qui écrit le fichier sur le disque. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +C’est tout — votre `.docx` est maintenant un fichier `.txt` où chaque équation apparaît sous forme d'extrait LaTeX, prête pour une consommation en aval. + +--- + +## Vérification de la sortie (Comment enregistrer correctement le txt) + +Ouvrez `MathSample.txt` dans n'importe quel éditeur de texte. Vous devriez voir quelque chose comme : + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Si vous repérez des caractères spécifiques à Word (par ex., `?` ou des symboles manquants), vérifiez que : + +* Vous utilisez une version récente d'Aspose.Words (les versions plus anciennes comportaient des bugs avec OfficeMath). +* Le document source contient réellement des objets **OfficeMath** — et non des objets de l’ancien Éditeur d’équations. Pour ces derniers, vous devrez peut‑être les convertir manuellement ou utiliser la méthode `ConvertMathToOfficeMath` avant l’enregistrement. + +--- + +## Variations courantes et cas limites + +| Situation | Que faire | +|-----------|-----------| +| **Legacy Equation Editor** objects | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **You need plain Unicode math, not LaTeX** | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Large documents (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **You want to keep the original file name** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +Ces ajustements répondent à la question « **how to export math** » pour différents pipelines, garantissant que votre solution reste robuste quel que soit le source. + +--- + +## Exemple complet fonctionnel (Toutes les étapes en un seul endroit) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Exécutez le programme, ouvrez le `.txt` généré, et vous verrez les équations LaTeX intégrées exactement à l'endroit où elles devaient être. C’est la façon la plus simple de **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/french/net/working-with-fonts/_index.md b/words/french/net/working-with-fonts/_index.md index 84a3f00a8a..401901256a 100644 --- a/words/french/net/working-with-fonts/_index.md +++ b/words/french/net/working-with-fonts/_index.md @@ -43,11 +43,12 @@ Que vous souhaitiez formater du texte avec différentes polices, définir des r | [Paramètres de police avec options de chargement](./font-settings-with-load-options/) Apprenez à gérer les paramètres de police avec les options de chargement dans Aspose.Words pour .NET. Guide étape par étape pour les développeurs afin de garantir une apparence cohérente des polices dans les documents Word. | [Définir le dossier des polices](./set-fonts-folder/) | Apprenez à définir un dossier de polices personnalisé dans Aspose.Words pour .NET pour garantir que vos documents Word sont rendus correctement sans polices manquantes. | | [Paramètres de police Instance par défaut](./font-settings-default-instance/) | Dans ce didacticiel, découvrez comment configurer les paramètres de police par défaut dans un document Word avec Aspose.Words pour .NET. | -| [Obtenir la liste des polices disponibles](./get-list-of-available-fonts/) Découvrez comment obtenir la liste des polices disponibles avec Aspose.Words pour .NET grâce à ce tutoriel détaillé, étape par étape. Améliorez vos compétences en gestion des polices. +| [Obtenir la liste des polices disponibles](./get-list-of-available-fonts/) Découvrez comment obtenir la liste des polices disponibles avec Aspose.Words pour .NET grâce à ce tutoriel détaillé, étape par étape. Améliorez vos compétences en gestion des polices. | | [Recevoir des notifications de polices](./receive-notifications-of-fonts/) | Découvrez comment recevoir des notifications de polices manquantes ou remplacées lors de l'utilisation d'Aspose.Words pour .NET. | | [Recevoir une notification d'avertissement](./receive-warning-notification/) Apprenez à recevoir une notification d'avertissement lors de l'utilisation d'Aspose.Words pour .NET et à gérer les problèmes ou les avertissements dans vos documents. | | [Exemple de source de police Steam](./resource-steam-font-source-example/) | Apprenez à utiliser la source de polices Resource Stream pour charger des polices personnalisées dans Aspose.Words pour .NET. | | [Obtenir une substitution sans suffixes](./get-substitution-without-suffixes/) | Dans ce didacticiel, découvrez comment obtenir des remplacements sans suffixe dans un document Word avec Aspose.Words pour .NET. | +| [Substitution de polices Aspose – Détecter les polices manquantes dans les documents Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Apprenez à détecter les polices manquantes lors de la substitution de polices dans les documents Word avec Aspose.Words pour .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/french/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/french/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..b477a2987c --- /dev/null +++ b/words/french/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Guide de substitution de polices Aspose pour détecter les polices manquantes + lors du chargement d’un document Word. Apprenez à configurer les paramètres de police + et à gérer efficacement les polices manquantes. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: fr +og_description: Guide de substitution de polices Aspose pour détecter les polices + manquantes lors du chargement d’un document Word. Apprenez à configurer les paramètres + de police et à gérer les polices manquantes efficacement. +og_title: Substitution de polices Aspose – Détecter les polices manquantes dans les + documents Word +tags: +- Aspose.Words +- C# +- Font Management +title: Substitution de polices Aspose – Détecter les polices manquantes dans les documents + Word +url: /fr/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Substitution de polices Aspose – Détecter les polices manquantes dans les documents Word + +Vous êtes déjà tombé sur un fichier Word qui semble parfait sur une machine mais qui présente d’étranges changements de police sur une autre ? C’est le problème classique de **aspose font substitution**, qui signifie généralement que certaines polices sont absentes sur le système cible. Dans ce tutoriel, nous vous montrerons, étape par étape, comment **détecter les polices manquantes** lors du **chargement d’un document Word**, comment **configurer les paramètres de police**, et quoi faire pour **gérer les polices manquantes** de manière élégante. + +Nous parcourrons un exemple complet et exécutable en C#, expliquerons pourquoi chaque ligne est importante, et vous montrerons même la sortie console attendue. À la fin, vous pourrez repérer les substitutions de police dès le chargement d’un document—sans aucune supposition. + +## Ce que vous apprendrez + +- Comment activer le collecteur de diagnostic d’Aspose.Words pour les avertissements de police. +- Le code exact nécessaire pour **charger un document Word** avec des **paramètres de police** personnalisés. +- Comment parcourir les objets `WarningInfo` pour lister chaque police substituée. +- Conseils pour supprimer les avertissements indésirables ou fournir des polices de secours. +- Un exemple prêt à l’emploi que vous pouvez copier‑coller dans Visual Studio. + +### Prérequis + +- .NET 6.0 ou version ultérieure (l’API fonctionne de la même façon sur .NET Framework). +- Aspose.Words pour .NET (package NuGet `Aspose.Words`). +- Un fichier Word qui référence une police que vous n’avez pas installée (par ex., `MissingFont.docx`). + +Si vous avez tout cela, plongeons‑y. + +## Étape 1 – Activer le collecteur de diagnostic (Configurer les paramètres de police) + +Première chose à faire : Aspose.Words n’enregistre les avertissements de substitution de police que si vous le lui indiquez. Cela se fait en créant un objet `FontSettings` et en l’assignant à une instance `LoadOptions`. Considérez cela comme l’allumage des « voyants de débogage » pour la gestion des polices. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Pourquoi ?** +Sans objet `FontSettings`, le collecteur d’avertissements reste silencieux et vous ne saurez jamais quelles polices ont été remplacées. En l’initialisant vide, nous laissons Aspose utiliser les polices système par défaut *et* suivre toutes les substitutions. + +> **Astuce :** Si vous savez qu’un dossier spécifique contient les polices de l’entreprise, indiquez‑le à `FontSettings` avec `SetFontsFolder("path")`. Cela peut réduire le nombre d’avertissements de polices manquantes. + +## Étape 2 – Charger le document avec les options configurées (Charger le document Word) + +Maintenant que le collecteur est actif, chargez votre fichier `.docx` en utilisant les mêmes `LoadOptions`. C’est le moment où Aspose analyse le document, recherche chaque référence de police, et décide si une substitution est nécessaire. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Pourquoi est‑ce important ?** +Si vous appelez simplement `new Document("MissingFont.docx")`, les paramètres par défaut s’appliqueraient *et* la liste des avertissements resterait vide. Passer `loadOptions` garantit que le collecteur de diagnostic est intégré au processus de chargement. + +## Étape 3 – Récupérer et afficher les avertissements de substitution de police (Détecter les polices manquantes) + +Après que le document soit en mémoire, Aspose stocke les avertissements dans `document.WarningCallback.Warnings`. Parcourez cette collection, filtrez sur `WarningType.FontSubstitution`, et affichez la description. Chaque description indique quelle police était manquante et laquelle a été utilisée à la place. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Sortie console attendue** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Cette sortie indique exactement quelles polices sont manquantes sur la machine exécutant le code. Vous pouvez maintenant décider d’installer les polices manquantes, de les incorporer dans le document, ou de conserver la substitution. + +![Sortie console affichant les avertissements de substitution de police aspose](/images/aspose-font-substitution-console.png) + +*Texte alternatif de l’image :* substitution de police aspose – sortie console listant les polices substituées + +## Étape 4 – Optionnel : Personnaliser le comportement de substitution (Gérer les polices manquantes) + +Parfois, vous ne voulez pas seulement savoir *qu*’une substitution a eu lieu—vous voulez contrôler *comment* elle se produit. Aspose.Words vous permet d’enregistrer une règle personnalisée `IFontSubstitutionRule`. Voici un exemple rapide qui force toute police manquante à revenir à `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Dans quel cas utiliseriez‑vous cela ?** +Si vous générez des PDF pour un service web et que vous savez que chaque client peut rendre `Tahoma`, forcer le repli garantit une cohérence visuelle sans avoir à distribuer des dizaines de fichiers de polices. + +## Exemple complet fonctionnel (Toutes les étapes combinées) + +Voici le programme complet que vous pouvez coller dans un nouveau projet console. Il se compile tel quel, en supposant que vous avez installé le package NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Exécutez le programme, observez la console, et vous verrez chaque événement de police manquante affiché. À partir de là, vous pouvez décider d’installer les polices manquantes, de les incorporer, ou de conserver le repli. + +## Questions fréquemment posées + +**Q : Cette méthode fonctionne‑t‑elle avec la conversion PDF ?** +Oui. Lorsque vous appelez plus tard `doc.Save("output.pdf")`, les polices qui ont été substituées lors du chargement seront celles incorporées dans le PDF. Ainsi, intercepter les avertissements tôt vous aide à éviter des changements de police inattendus dans le PDF final. + +**Q : Et si j’ai de nombreux documents à traiter ?** +Enveloppez la logique de chargement dans un bloc try‑catch et réutilisez une seule instance `FontSettings` pour tous les documents. Cela réduit la surcharge et maintient le collecteur d’avertissements actif pour chaque fichier. + +**Q : Puis‑je supprimer complètement les avertissements ?** +Vous pouvez définir `loadOptions.WarningCallback = null;` avant le chargement, mais vous perdrez la capacité de **détecter les polices manquantes**—ce qui n’est généralement pas souhaitable. + +## Conclusion + +Nous avons couvert tout ce dont vous avez besoin pour maîtriser **aspose font substitution** : activer le collecteur de diagnostic, charger un fichier Word avec des **paramètres de police** personnalisés, extraire la liste des polices manquantes, et même remplacer la règle de substitution par défaut pour **gérer les polices manquantes** à votre façon. Avec seulement quelques lignes de C#, vous obtenez une visibilité complète sur les problèmes de police qui autrement seraient cachés derrière des changements de mise en page subtils. + +Prochaines étapes ? Essayez d’incorporer les polices originales dans le document avec `FontSettings.SetFontsFolder` ou explorez `FontSourceBase` pour charger des polices depuis une base de données. Vous pouvez également expérimenter avec la collection `Document.BuiltInStyle` pour voir comment les changements de police au niveau du style se propagent. + +Vous avez d’autres questions sur Aspose.Words ou la gestion des polices ? Laissez un commentaire, explorez la documentation officielle d’Aspose, ou lancez un nouveau projet et testez le code ci‑dessus. Bon codage, et que vos documents s’affichent toujours exactement comme prévu ! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/basic-conversions/_index.md b/words/german/net/basic-conversions/_index.md index de0998541a..72a29d0d99 100644 --- a/words/german/net/basic-conversions/_index.md +++ b/words/german/net/basic-conversions/_index.md @@ -24,12 +24,13 @@ | [Doc in Docx konvertieren](./doc-to-docx/) | Erfahren Sie, wie Sie DOC mit Aspose.Words für .NET in DOCX konvertieren. Schritt-für-Schritt-Anleitung mit Codebeispielen. Perfekt für Entwickler. | | [Konvertieren Sie Docx in RTF](./docx-to-rtf/) | Erfahren Sie in unserer Schritt-für-Schritt-Anleitung, wie Sie DOCX mit Aspose.Words für .NET in RTF konvertieren. Einfache Konvertierung für nahtlose Dokumentenverarbeitung. | | [Word-Datei in PDF konvertieren](./docx-to-pdf/) Erfahren Sie in unserem Leitfaden, wie Sie Word-Dateien mit Aspose.Words für .NET einfach in PDF konvertieren. Perfekt für Entwickler, die eine schnelle und zuverlässige Dokumentkonvertierung wünschen. | +| [Word in PDF konvertieren in C# – Vollständige Anleitung mit Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Erfahren Sie, wie Sie mit Aspose.Words in C# Word-Dokumente vollständig in PDF konvertieren – Schritt‑für‑Schritt‑Anleitung. | | [Word in PDF konvertieren in C# mit Aspose.Words – Anleitung](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Erfahren Sie, wie Sie Word-Dokumente mit Aspose.Words in C# einfach in PDF konvertieren. | | [Konvertieren Sie Docx in Byte](./docx-to-byte/) | Erfahren Sie, wie Sie Docx mit Aspose.Words in .NET in ein Byte-Array konvertieren, um eine effiziente Dokumentverarbeitung zu gewährleisten. Schritt-für-Schritt-Anleitung enthalten. | | [Docx in Epub konvertieren](./docx-to-epub/) | Konvertieren Sie DOCX einfach in EPUB mit Aspose.Words für .NET. Folgen Sie unserem Tutorial für die nahtlose Integration in Ihre .NET-Anwendungen. | | [Konvertieren Sie Docx in Mhtml und senden Sie E-Mails](./docx-to-mhtml-and-sending-email/) | Erfahren Sie in dieser Schritt-für-Schritt-Anleitung, wie Sie DOCX in MHTML konvertieren und E-Mails mit Aspose.Words für .NET versenden. Steigern Sie Ihre Produktivität durch einfache Automatisierung. | | [Docx-Datei in Markdown konvertieren](./docx-to-markdown/) | Erfahren Sie, wie Sie DOCX-Dateien mit Aspose.Words für .NET in Markdown konvertieren. Folgen Sie unserer ausführlichen Anleitung für die nahtlose Integration in Ihre .NET-Anwendungen. | -| [Konvertieren Sie Docx in Txt](./docx-to-txt/) Konvertieren Sie DOCX mit Aspose.Words für .NET in TXT mit unserer Schritt-für-Schritt-Anleitung. Lernen Sie, Dokumente effizient und mühelos zu transformieren. | +| [Konvertieren Sie Docx in Txt](./docx-to-txt/) Konvertieren Sie DOCX mit Aspose.Words für .NET in TXT mit unserer Schritt‑für‑Schritt‑Anleitung. Lernen Sie, Dokumente effizient und mühelos zu transformieren. | | [Textdatei in Word-Dokument konvertieren](./txt-to-docx/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET Textdateien in Word-Dokumente konvertieren. Verwalten Sie Dokumentkonvertierungen effizient mit unserem umfassenden Leitfaden. | | [PDF als JPEG speichern](./pdf-to-jpeg/) | Konvertieren Sie PDFs mühelos in JPEGs mit Aspose.Words für .NET. Folgen Sie unserer ausführlichen Anleitung mit Beispielen und FAQs. Ideal für Entwickler und Enthusiasten. | | [PDF im Word-Format (Docx) speichern](./pdf-to-docx/) | Erfahren Sie in dieser detaillierten Schritt-für-Schritt-Anleitung, wie Sie mit Aspose.Words für .NET ein PDF in ein Word-Dokument (Docx) konvertieren. Perfekt für Entwickler. | diff --git a/words/german/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/german/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..71b09ce083 --- /dev/null +++ b/words/german/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,194 @@ +--- +category: general +date: 2026-04-05 +description: Word in PDF mit C# und Aspose.Words konvertieren. Erfahren Sie, wie Sie + docx als PDF speichern, ein barrierefreies PDF exportieren und Word‑Dokumente effizient + laden. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: de +og_description: Konvertieren Sie Word in PDF mit C# anhand einer Schritt‑für‑Schritt‑Anleitung. + Erfahren Sie, wie Sie docx als PDF speichern, ein barrierefreies PDF exportieren + und ein Word‑Dokument mit Aspose.Words laden. +og_title: Word in PDF mit C# konvertieren – Vollständiges Aspose.Words‑Tutorial +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Word in PDF konvertieren in C# – Vollständiger Leitfaden mit Aspose.Words +url: /de/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word in PDF konvertieren in C# – Vollständiges Programmier‑Tutorial + +Haben Sie sich jemals gefragt, wie man **convert word to pdf** ohne umständliche Befehlszeilen‑Tools oder Drittanbieterdienste erledigt? Sie sind nicht allein. Viele Entwickler stoßen an diese Grenze, wenn ein Kunde ein barrierefreies PDF direkt aus einer DOCX‑Datei verlangt. Die gute Nachricht? Mit ein paar Zeilen C# und der leistungsstarken Aspose.Words‑Bibliothek können Sie ein Word‑Dokument in ein standardkonformes PDF im Handumdrehen verwandeln. + +In diesem Leitfaden gehen wir alles durch, was Sie wissen müssen: von den Grundlagen des **load word document**, über das Konfigurieren der richtigen Optionen bis hin zu **how to export accessible pdf**, und schließlich das Speichern des Ergebnisses, damit Sie **save docx as pdf** zuverlässig durchführen können. Am Ende haben Sie ein einsatzbereites Snippet, das Sie in jedes .NET‑Projekt einbinden können. + +> **Pro Tipp:** Wenn Sie PDF/UA‑2‑Konformität anstreben (der Barrierefreiheitsstandard, den viele Regierungsbehörden verlangen), funktioniert derselbe Code ohne zusätzliche Schritte – setzen Sie einfach das richtige `PdfCompliance`‑Flag. + +## Was Sie lernen werden + +- Wie man **load word document** mit Aspose.Words in C# verwendet. +- Die genauen Einstellungen, die für **how to export accessible pdf** (PDF/UA‑2) erforderlich sind. +- Ein vollständiges, ausführbares Beispiel, das **save docx as pdf** mit einem Methodenaufruf erledigt. +- Häufige Fallstricke beim **c# convert docx pdf** und wie man sie vermeidet. +- Schnelle Methoden, um zu überprüfen, ob das erzeugte PDF die Barrierefreiheits‑Anforderungen erfüllt. + +Keine externen Werkzeuge, keine obskuren Konfigurationsdateien – nur reiner C#‑Code, den Sie noch heute kompilieren können. + +## Voraussetzungen + +Bevor wir loslegen, stellen Sie sicher, dass Sie Folgendes haben: + +1. **.NET 6.0** (oder jede aktuelle .NET‑Version) installiert. Ältere Frameworks funktionieren ebenfalls, aber die nachfolgende Syntax geht von einem modernen SDK aus. +2. Eine **license** für Aspose.Words for .NET. Die Bibliothek bietet eine kostenlose Testversion, aber für die Produktion benötigen Sie einen gültigen Schlüssel. +3. Das **Aspose.Words**‑NuGet‑Paket zu Ihrem Projekt hinzugefügt: + +```bash +dotnet add package Aspose.Words +``` + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## Schritt‑für‑Schritt‑Implementierung + +Im Folgenden zerlegen wir den Prozess in logische Abschnitte. Jeder Schritt enthält ein kleines Code‑Snippet, eine Erklärung, **warum** er wichtig ist, und einen Tipp aus der Praxis. + +### ## Word in PDF konvertieren – Quell‑Dokument laden + +Das Erste, was Sie tun müssen, ist **load word document** in den Speicher zu laden. Aspose.Words abstrahiert das OpenXML‑Parsing, sodass Sie mit DOCX-, DOC- oder sogar RTF‑Dateien arbeiten können, ohne sich um Format‑Eigenheiten sorgen zu müssen. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Warum das wichtig ist:** +Das Laden der Datei erzeugt ein `Document`‑Objekt, das die gesamte Word‑Datei repräsentiert, einschließlich Kopf‑ und Fußzeilen, Formatvorlagen und versteckter Metadaten. Wenn Sie diesen Schritt überspringen oder die Datei als rohen Stream lesen, verlieren Sie die Layout‑Informationen, die später bestimmen, wie das PDF aussieht. + +> **Hinweis:** Der gleiche `Document`‑Konstruktor funktioniert für `.doc` und `.rtf`. Das bedeutet, Sie können **c# convert docx pdf** selbst dann, wenn die Quelle nicht strikt eine DOCX ist. + +### ## DOCX als PDF speichern – PDF/UA‑2‑Konformität konfigurieren + +Jetzt, wo das Dokument im Speicher ist, teilen wir Aspose.Words mit, wie das PDF erzeugt werden soll. Für die meisten Anwendungsfälle reichen die Standardeinstellungen, aber wenn Sie ein **accessible PDF** benötigen, müssen Sie das PDF/UA‑2‑Konformitäts‑Flag aktivieren. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Warum das wichtig ist:** +`PdfCompliance.PdfUAXmpA2` weist die Bibliothek an, die notwendigen Tags und Strukturen einzubetten, die Bildschirmleser benötigen. Ohne dieses Flag erhalten Sie möglicherweise ein optisch einwandfreies PDF, das bei einer Barrierefreiheits‑Prüfung durchfällt. + +> **Tipp:** Wenn Sie nur ein normales PDF benötigen, können Sie die Zeile `Compliance` weglassen. Die übrigen Optionen liefern weiterhin ein hochwertiges Ergebnis. + +### ## Word in PDF konvertieren – Datei schreiben + +Mit den konfigurierten Optionen ist der letzte Schritt, **save docx as pdf**. Dieser einzelne Aufruf übernimmt die gesamte schwere Arbeit: Layout‑Konvertierung, Schrift‑Einbettung und Barrierefreiheits‑Tagging. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Was Sie erhalten:** +- Eine PDF‑Datei unter `outputPath`, die das Word‑Layout exakt widerspiegelt. +- Wenn Sie das `PdfUAXmpA2`‑Flag verwendet haben, wird das PDF als PDF/UA‑2‑konform gekennzeichnet. +- Alle Schriften sind eingebettet, sodass die Datei auf jedem Rechner identisch aussieht. + +### ## Barrierefreies PDF überprüfen (optional, aber empfohlen) + +Nach der Konvertierung ist es sinnvoll, zu überprüfen, ob das PDF wirklich **how to export accessible pdf** korrekt umsetzt. Sie können kostenlose Werkzeuge wie den „Accessibility Check“ von Adobe Acrobat Reader oder den Open‑Source‑Validator `pdfcpu` verwenden. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Wenn der Validator keine Fehler meldet, haben Sie **convert word to pdf** erfolgreich mit voller Barrierefreiheitsunterstützung durchgeführt. + +### ## Häufige Fallstricke beim C#‑Konvertieren von DOCX zu PDF + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| Fehlende Schriften | Das Quell‑DOCX verwendet eine benutzerdefinierte Schrift, die auf dem Server nicht installiert ist. | Setzen Sie `EmbedFullFonts = true` oder installieren Sie die Schrift auf dem Rechner. | +| Große Dateigröße | Bilder werden in voller Auflösung eingebettet. | Verwenden Sie `ImageCompression = PdfImageCompression.Jpeg` und setzen Sie `JpegQuality` auf einen niedrigeren Wert. | +| Defekte Hyperlinks | Links verweisen auf relative Pfade, die beim Client nicht existieren. | Stellen Sie sicher, dass URLs absolut sind, oder passen Sie die Eigenschaft `HyperlinkTarget` an. | +| Barrierefreiheits‑Tags fehlen | `Compliance`‑Flag nicht gesetzt. | Fügen Sie `Compliance = PdfCompliance.PdfUAXmpA2` wie oben gezeigt hinzu. | + +Wenn Sie diese Punkte berücksichtigen, wird Ihre **c# convert docx pdf**‑Routine robust und produktionsreif. + +## Voll funktionsfähiges Beispiel + +Wenn wir alles zusammenfügen, erhalten Sie eine eigenständige Konsolen‑App, die Sie sofort kompilieren und ausführen können. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Erwartetes Ergebnis:** Nach dem Ausführen des Programms finden Sie `output.pdf` in `C:\Docs`. Öffnen Sie es in einem beliebigen PDF‑Betrachter; das Layout sollte `input.docx` pixelgenau entsprechen, und ein Barrierefreiheits‑Check bestätigt die PDF/UA‑2‑Konformität. + +## Fazit + +Wir haben gerade eine vollständige End‑zu‑End‑Lösung für das **convert word to pdf** mit C# und Aspose.Words durchgegangen. Durch **load word document**, die richtige Konfiguration von `PdfSaveOptions` und schließlich **save docx as pdf** erhalten Sie ein hochwertiges, barrierefreies PDF mit minimalem Code. Egal, ob Sie einen Dokument‑Generierungs‑Microservice, einen On‑Premise‑Batch‑Konverter bauen, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-markdownsaveoptions/_index.md b/words/german/net/programming-with-markdownsaveoptions/_index.md index 13224e8603..8e725ddbc6 100644 --- a/words/german/net/programming-with-markdownsaveoptions/_index.md +++ b/words/german/net/programming-with-markdownsaveoptions/_index.md @@ -21,7 +21,7 @@ ## Anleitungen | Titel | Beschreibung | | --- | --- | -| [Exportieren in Markdown mit Ausrichtung des Tabelleninhalts](./export-into-markdown-with-table-content-alignment/) | Erfahren Sie, wie Sie Word-Dokumente mit ausgerichteten Tabellen mit Aspose.Words für .NET in Markdown exportieren. Folgen Sie unserer Schritt-für-Schritt-Anleitung für perfekte Markdown-Tabellen. | +| [Exportieren in Markdown mit Ausrichtung des Tabelleninhalts](./export-into-markdown-with-table-content-alignment/) | Erfahren Sie, wie Sie Word-Dokumente mit ausgerichteten Tabellen mit Aspose.Words für .NET in Markdown exportieren. Folgen Sie unserer Schritt‑für‑Schritt‑Anleitung für perfekte Markdown-Tabellen. | | [Bilderordner festlegen](./set-images-folder/) Konvertieren Sie Word-Dokumente mit Aspose.Words für .NET in Markdown mit korrekter Tabellenausrichtung. Folgen Sie unserer ausführlichen Anleitung für perfekte Ergebnisse. | | [Wie man Markdown verwendet: DOCX in Markdown mit LaTeX‑Gleichungen konvertieren](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | Erfahren Sie, wie Sie DOCX‑Dateien mit LaTeX‑Formeln in Markdown konvertieren, um mathematische Inhalte korrekt zu erhalten. | @@ -49,6 +49,12 @@ Erfahren Sie, wie Sie DOCX‑Dateien in Markdown speichern – vollständige Sch ### [Wie man Markdown aus DOCX exportiert – Vollständige Anleitung](./how-to-export-markdown-from-docx-complete-guide/) Erfahren Sie, wie Sie DOCX‑Dateien vollständig in Markdown exportieren – Schritt‑für‑Schritt‑Anleitung in C#. +### [DOCX in Markdown konvertieren – Bildextraktion aus DOCX mit Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Erfahren Sie, wie Sie Bilder aus DOCX‑Dateien extrahieren und das Dokument in Markdown konvertieren – vollständige Anleitung in C#. + +### [Word in Markdown konvertieren – Vollständige Anleitung mit PDF/UA-Export](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +Erfahren Sie, wie Sie Word‑Dokumente in Markdown konvertieren und gleichzeitig einen PDF/UA‑Export für barrierefreie PDFs erstellen. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/german/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..35fd3c09ea --- /dev/null +++ b/words/german/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Erfahren Sie, wie Sie DOCX in Markdown konvertieren und Bilder aus DOCX + in C# extrahieren. Schritt‑für‑Schritt‑Anleitung mit vollständigem Code und Tipps. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: de +og_description: DOCX in Markdown konvertieren und Bilder aus DOCX mit Aspose.Words + extrahieren. Vollständiges C#‑Tutorial mit Code, Erklärung und Best‑Practice‑Tipps. +og_title: DOCX in Markdown konvertieren – Bilder aus DOCX in C# extrahieren +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX in Markdown konvertieren – Bilder aus DOCX mit Aspose.Words extrahieren +url: /de/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX in Markdown konvertieren – Bilder aus DOCX in C# extrahieren + +Haben Sie jemals **DOCX in Markdown konvertieren** müssen, aber hatten Probleme, dass die Bilder in der Ausgabe verschwinden? Sie sind nicht allein. In vielen Projekten ist die Markdown‑Version perfekt für Versions‑Control oder Static‑Site‑Generatoren, doch die Bilder bleiben zurück und verwandeln ein reichhaltiges Dokument in eine karge Textdatei. + +Die gute Nachricht? Mit ein paar Zeilen C# und Aspose.Words können Sie **DOCX in Markdown konvertieren** *und* **Bilder aus DOCX extrahieren** automatisch. Dieser Leitfaden führt Sie durch den gesamten Prozess, erklärt, warum jedes Teil wichtig ist, und zeigt Ihnen sogar, wie Sie Ihren Bildordner ordentlich halten. + +## Was Sie lernen werden + +- Wie man ein DOCX lädt, das Bilder enthält. +- Wie man ein benutzerdefiniertes `IResourceSavingCallback` definiert, das entscheidet, wo jedes Bild abgelegt wird. +- Wie man `MarkdownSaveOptions` konfiguriert, sodass das erzeugte Markdown die extrahierten Bilder korrekt referenziert. +- Tipps zum Umgang mit Sonderfällen wie doppelten Bildnamen oder Nicht‑PNG‑Formaten. +- Ein vollständiges, sofort kopier‑und‑einfügbares Code‑Beispiel, das Sie noch heute ausführen können. + +### Voraussetzungen + +- .NET 6.0 oder höher (die API funktioniert auf .NET Core, .NET Framework und .NET 5+). +- Eine Lizenz für **Aspose.Words for .NET** (die kostenlose Testversion funktioniert zum Testen). +- Grundlegende Kenntnisse in C# und Visual Studio (oder Ihrer bevorzugten IDE). + +Wenn Sie das haben, lassen Sie uns loslegen. + +--- + +## Schritt 1: Projekt einrichten und Aspose.Words installieren + +Zuerst erstellen Sie eine neue Konsolenanwendung (oder integrieren sie in eine bestehende Lösung). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro Tipp:** Verwenden Sie die neueste NuGet‑Version (Stand April 2026 ist es 24.12), um die neuesten Verbesserungen beim Markdown‑Export zu erhalten. + +--- + +## Schritt 2: Einen Callback erstellen, um Bilder dort zu speichern, wo Sie sie haben möchten + +Aspose.Words ermöglicht es Ihnen, jede Ressource (Bilder, SVGs usw.), die während des Markdown‑Exports geschrieben wird, abzufangen. Durch Implementierung von `IResourceSavingCallback` können Sie: + +1. Einen Ordner auswählen, der neben Ihrer Markdown‑Datei liegt. +2. Einen eindeutigen Dateinamen erzeugen (damit Sie nie ein vorhandenes Bild überschreiben). +3. Das Format festlegen (hier erzwingen wir PNG für Konsistenz). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Warum ein GUID‑basierter Name? + +Wenn das Quell‑DOCX zwei Bilder mit demselben ursprünglichen Namen enthält, würde ein einfaches Kopieren‑Einfügen eines von ihnen überschreiben. Die Verwendung von `Guid.NewGuid()` garantiert Eindeutigkeit, was besonders praktisch ist, wenn Sie die Konvertierung häufig in einer automatisierten Pipeline ausführen. + +--- + +## Schritt 3: Das DOCX laden und die Markdown‑Optionen konfigurieren + +Jetzt laden wir das Dokument in den Speicher und hängen den gerade erstellten Callback an. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Was der Code Schritt für Schritt macht + +| Schritt | Zweck | +|------|---------| +| **Pfade definieren** | Hält Ihr Projekt flexibel; Sie können auf jeden Ordner zeigen, ohne neu zu kompilieren. | +| **DOCX laden** | `Document` analysiert die Word‑Datei und macht alle Elemente (Absätze, Tabellen, Bilder) zugänglich. | +| **`MarkdownSaveOptions` konfigurieren** | Der `ResourceSavingCallback` ist der Hook, der Bilder extrahiert. Ohne ihn würde Aspose.Words die Bilder als Base64‑Strings einbetten oder sie je nach Einstellung ganz weglassen. | +| **Speichern** | `doc.Save` schreibt die Markdown‑Datei und löst den Callback für jedes Bild aus. | + +--- + +## Schritt 4: Ausgabe überprüfen – Was sollten Sie sehen? + +Nach dem Ausführen des Programms öffnen Sie `DocWithImages.md`. Sie werden Markdown‑Bildlinks sehen, die etwa so aussehen: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Und in `C:\Docs\MarkdownResources` finden Sie eine Reihe von PNG‑Dateien mit GUID‑Namen. Öffnen Sie eine beliebige – sie sollte identisch sein mit den Bildern, die im ursprünglichen DOCX eingebettet waren. + +Wenn Sie die Markdown‑Datei in einem Viewer öffnen, der relative Pfade respektiert (z. B. VS Code‑Vorschau, GitHub oder ein Static‑Site‑Generator), werden die Bilder genau so angezeigt wie in Word. + +### Häufige Fallstricke & wie man sie vermeidet + +| Symptom | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| Bilder erscheinen als defekte Links | `ResourceFileName` wurde nicht gesetzt, sodass das Markdown auf eine nicht vorhandene Datei verweist. | Stellen Sie sicher, dass `args.ResourceFileName = newFileName;` im Callback gesetzt ist. | +| PNG‑Dateien sind sehr groß | Ursprüngliche Bilder waren JPEG oder BMP; die Konvertierung zu PNG kann die Größe erhöhen. | Erkennen Sie das Originalformat über `args.ResourceContentType` und bewahren Sie es: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Doppelte Bilder erscheinen weiterhin | Sie haben einen statischen Dateinamen anstelle einer GUID verwendet. | Wechseln Sie zurück zur GUID‑Logik oder fügen Sie einen Zähler pro Bildtyp hinzu. | +| Konvertierung wirft `FileNotFoundException` | Der Pfad zum Quell‑DOCX ist falsch oder der Ordner hat keine Leseberechtigung. | Überprüfen Sie den Pfad und gewähren Sie die entsprechenden Dateisystemrechte. | + +--- + +## Schritt 5: Erweiterte Anpassungen (optional) + +### 5.1 Originale Bildformate beibehalten + +Wenn Sie möchten, dass die Ausgabebilder ihre ursprünglichen Erweiterungen behalten, passen Sie den Callback an: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Bilder als Base64 einbetten (wenn Sie *keine* separaten Dateien wollen) + +Manchmal ist ein einseitiges Markdown vorzuziehen (z. B. zum Versand per E‑Mail). Ändern Sie die Option: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Aber denken Sie daran: **Bilder aus DOCX extrahieren** ist das Hauptziel für die meisten Static‑Site‑Workflows, daher ist der Ordner‑Ansatz in der Regel die bessere Wahl. + +--- + +## Vollständiges funktionierendes Beispiel (kopier‑und‑einfüg‑bereit) + +Unten finden Sie das gesamte Programm in einer Datei. Ersetzen Sie einfach die Pfade durch Ihre eigenen und führen Sie es aus. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Führen Sie es mit `dotnet run` aus. Wenn die Konsole die ✅‑Zeile ausgibt, öffnen Sie die Markdown‑Datei und Sie sollten die Bilder korrekt dargestellt sehen. + +--- + +## Fazit + +Sie haben nun eine **vollständige, produktionsreife Lösung, um DOCX in Markdown zu konvertieren und Bilder aus DOCX zu extrahieren** mit Aspose.Words in C#. Das Hauptkeyword erscheint durchgehend im Leitfaden und stärkt die Relevanz sowohl für Suchmaschinen als auch für KI‑Assistenten. + +In einem Durchlauf tut der Code: + +1. Lädt ein Word‑Dokument. +2. Fängt jedes Bild über `IResourceSavingCallback` ab. +3. Speichert jedes Bild in einem vorhersehbaren Ordner mit einem eindeutigen Namen. +4. Generiert Markdown, das diese Bilder referenziert. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/german/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..0be0b0ef1b --- /dev/null +++ b/words/german/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-05 +description: Schnelles Konvertieren von Word zu Markdown und lerne, wie man in C# + als PDF/UA speichert. Schritt‑für‑Schritt‑Code, Tipps und Umgang mit Randfällen. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: de +og_description: Konvertieren Sie Word in Markdown und speichern Sie als PDF/UA mit + Aspose.Words. Erfahren Sie das Warum, das Wie und Best‑Practice‑Tipps in einem kompakten + Leitfaden. +og_title: Word in Markdown konvertieren – Komplettes C#‑Tutorial +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word in Markdown konvertieren – Vollständige Anleitung mit PDF/UA‑Export +url: /de/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word in Markdown konvertieren – Vollständige Anleitung mit PDF/UA‑Export + +Haben Sie sich jemals gefragt, wie man **Word in Markdown konvertiert** ohne Gleichungen oder Bilder zu verlieren? Sie sind nicht allein. Viele Entwickler benötigen eine zuverlässige Methode, `.docx`‑Dateien in sauberes Markdown zu verwandeln und gleichzeitig **als PDF/UA** speichern zu können, um barrierefreie PDFs zu erzeugen. In diesem Tutorial führen wir Sie durch eine komplette, sofort einsatzbereite Lösung mit Aspose.Words für .NET, erklären, warum jede Einstellung wichtig ist, und zeigen, wie man die kniffligeren Teile wie OfficeMath und schwebende Formen handhabt. + +Am Ende dieses Leitfadens haben Sie ein einzelnes C#‑Programm, das: + +1. Lädt ein Word‑Dokument mit entspannter Wiederherstellung (damit beschädigte Dateien den Durchlauf nicht abbrechen). +2. Exportiert es nach Markdown, wandelt Gleichungen in LaTeX um und speichert Bilder über einen benutzerdefinierten Callback. +3. Speichert dasselbe Dokument als PDF/UA‑2‑konforme Datei und bettet schwebende Formen als Inline‑Tags ein. + +Klingt nach viel? Kein Problem – lassen Sie uns eintauchen. + +## Was Sie benötigen + +- **Aspose.Words for .NET** (neueste Version, 23.x zum Zeitpunkt des Schreibens). +- Eine .NET‑Entwicklungsumgebung (Visual Studio 2022, Rider oder die `dotnet`‑CLI). +- Eine Beispiel‑Word‑Datei (`input.docx`) in einem Ordner, auf den Sie verweisen können. +- Grundlegende Vertrautheit mit C#‑Syntax – nichts Exotisches, nur ein paar `using`‑Anweisungen. + +> **Pro Tipp:** Wenn Sie einen NuGet‑Paket‑Manager verwenden, fügen Sie die Bibliothek hinzu mit +> `dotnet add package Aspose.Words` oder über die Visual Studio NuGet‑UI. + +## Schritt 1 – Laden des Word‑Dokuments mit Relaxed Recovery + +Wenn Sie Word‑Dateien aus externen Quellen erhalten, können diese leichte Beschädigungen enthalten. Das Aktivieren der **Relaxed**‑Wiederherstellung veranlasst Aspose.Words, weiterzumachen, anstatt eine Ausnahme zu werfen. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Warum das wichtig ist:** +- `RecoveryMode.Relaxed` verhindert, dass ein einzelner fehlerhafter Absatz die gesamte Konvertierung abbricht. +- Das Bereitstellen eines `FontSettings`‑Objekts stellt sicher, dass fehlende Schriftarten elegant ersetzt werden, was entscheidend ist, wenn Sie später Gleichungen als LaTeX rendern. + +## Schritt 2 – Export nach Markdown (OfficeMath → LaTeX, Bilder über Callback) + +Markdown hat keine native Möglichkeit, Word‑Gleichungen darzustellen. Aspose.Words kann **OfficeMath**‑Objekte in LaTeX übersetzen, was die meisten Markdown‑Renderer verstehen. Bilder müssen jedoch irgendwo gespeichert werden; ein benutzerdefinierter **resource‑saving callback** gibt Ihnen die volle Kontrolle über Ordnerstruktur und Namensgebung. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Der Resource‑Saving‑Callback + +Unten finden Sie eine kleine Implementierung, die jedes Bild in einem Unterordner namens `images` speichert und die Dateien `img001.png`, `img002.png` usw. nennt. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Warum Sie das benötigen:** +- Ohne einen Callback erstellt Aspose.Words einen flachen Ordner mit zufälligen GUID‑Namen, was die Versionskontrolle unübersichtlich macht. +- Durch die Kontrolle des Namensschemas halten Sie das Markdown‑Repository ordentlich und reproduzierbar. + +### Erwartete Markdown‑Ausgabe + +Öffnen Sie `doc.md` nach dem Durchlauf und Sie sehen: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Gleichungen erscheinen als LaTeX, umschlossen von `$$ … $$`, und Bilder verweisen auf den gerade erstellten `images`‑Ordner. + +## Schritt 3 – Export nach PDF/UA‑2 (Barrierefrei‑bereit) + +Wenn Sie das Dokument mit Benutzern teilen müssen, die auf Screen‑Reader oder andere Hilfstechnologien angewiesen sind, ist die **PDF/UA‑2**‑Konformität der Goldstandard. Aspose.Words kann dies mit einem einzigen Flag erzwingen und zudem schwebende Formen in Inline‑Tags flachlegen, sodass sie bei der Konvertierung nicht verloren gehen. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Warum PDF/UA wichtig ist:** +- PDF/UA (Universal Accessibility) garantiert, dass das resultierende PDF korrekte Tags, logische Lesereihenfolge und Alternativtexte für Bilder enthält. +- Das Setzen von `ExportFloatingShapesAsInlineTag` stellt sicher, dass Formen wie Textfelder oder Callouts nicht ausgelassen oder verschoben werden – ein häufiges Problem bei komplexen Layouts. + +### Überprüfung der PDF/UA‑Konformität + +Nach dem Export öffnen Sie das PDF in Adobe Acrobat Pro und führen **„Accessibility Check“** aus (Tools → Accessibility → Full Check). Wenn das Tool **0 Fehler** meldet, haben Sie Erfolg. + +## Randfälle & häufige Stolperfallen + +| Situation | Worauf zu achten ist | Lösung / Empfehlung | +|----------------------------------------|--------------------------------------------------------|--------------------------------------------------------| +| Word‑Datei enthält **nicht unterstützte Schriftarten** | Schriftarten können ersetzt werden, wodurch das Gleichungs‑Layout beschädigt wird | Stellen Sie ein benutzerdefiniertes `FontSettings` mit Ersatz‑Schriftarten bereit. | +| Große Dokumente (> 100 MB) | Speicherbelastung während der Konvertierung | Verwenden Sie `LoadOptions` mit `LoadFormat.Docx` und streamen Sie die Datei. | +| Bilder sind **EMF/WMF** Vektorgrafiken | Sie könnten unbeabsichtigt gerastert werden | Konvertieren Sie sie vor dem Speichern über `ImageSaveOptions` in PNG. | +| PDF/UA schlägt bei **verschachtelten Tabellen** die Validierung fehl | Tagging kann mehrdeutig werden | Aktivieren Sie `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit`, um der Engine zu helfen. | +| Benötigt **benutzerdefinierte Stile zu erhalten** | Markdown hat eingeschränkte Styling‑Möglichkeiten | Exportieren Sie eine CSS‑Datei zusammen mit dem Markdown und referenzieren Sie sie. | + +## Vollständiges funktionierendes Beispiel (Gesamter Code zusammen) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Führen Sie das Programm aus, und Sie finden sowohl `doc.md` (mit LaTeX‑Gleichungen und sauberen Bild‑Links) als auch `doc.pdf` (vollständig PDF/UA‑2‑konform) im Ordner `YOUR_DIRECTORY`. + +## Visuelle Übersicht + +![Word in Markdown konvertieren Beispiel](https://example.com/placeholder.png "Word in Markdown konvertieren Beispiel – zeigt Eingabe‑Word, Markdown‑Ausgabe und PDF/UA‑Datei") + +*Alt‑Text:* **Word in Markdown konvertieren Beispiel** – Diagramm der Konvertierungspipeline von einer Word‑Datei zu Markdown und PDF/UA. + +## Zusammenfassung & nächste Schritte + +Wir haben gerade **Word in Markdown konvertiert**, dabei Gleichungen intakt gehalten, Bilder in einem ordentlichen Ordner gespeichert und eine **als PDF/UA speichern**‑Datei erzeugt, die Barrierefreiheits‑Checks besteht. Die wichtigsten Erkenntnisse sind: + +- Verwenden Sie `LoadOptions.RecoveryMode.Relaxed`, um unvollkommene Word‑Dateien zu tolerieren. +- Setzen Sie `OfficeMathExportMode` auf `LaTeX` für sauberes Gleichungs‑Rendering. +- Implementieren Sie einen `ResourceSavingCallback`, um die Bildausgabe zu steuern. +- Aktivieren Sie `PdfCompliance.PdfUAXmpA2` und `ExportFloatingShapesAsInlineTag` für ein standardkonformes PDF. + +### Was Sie als Nächstes erkunden können? + +- **Custom CSS for Markdown** – erzeugen Sie ein Stylesheet, das Ihre Word‑Stile widerspiegelt. +- **Batch processing** – durchlaufen Sie ein Verzeichnis von `.docx`‑Dateien, um große Migrationen zu automatisieren. +- **Advanced PDF/UA features** – fügen Sie benutzerdefinierte Tags hinzu, setzen Sie Sprachattribute oder betten Sie Audio‑Beschreibungen ein. +- **Integration with CI/CD** – stellen Sie sicher, dass jeder Build automatisch barrierefreie PDFs erzeugt. + +Wenn Sie auf ein Problem stoßen, prüfen Sie doppelt, ob Ihre Aspose.Words‑Version mit der hier verwendeten API übereinstimmt, und denken Sie daran, dass die Dokumentation der Bibliothek eine solide sekundäre Referenz ist. + +Viel Spaß beim Programmieren, und mögen Ihre Dokumente sowohl schön **und** zugänglich bleiben! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/programming-with-txtsaveoptions/_index.md b/words/german/net/programming-with-txtsaveoptions/_index.md index ff26c12810..225aad12ad 100644 --- a/words/german/net/programming-with-txtsaveoptions/_index.md +++ b/words/german/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Dank dieser Tutorials können Sie die Funktionalitäten von Aspose.Words für .N | [Bidi-Markierungen in Word-Dokumente einfügen](./add-bidi-marks/) | Erfahren Sie in dieser Anleitung, wie Sie mit Aspose.Words für .NET bidirektionale (Bidi) Markierungen in Word-Dokumenten hinzufügen. Stellen Sie die korrekte Textrichtung für mehrsprachige Inhalte sicher. | | [Tabulatorzeichen pro Ebene für Listeneinrückung verwenden](./use-tab-character-per-level-for-list-indentation/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET mehrstufige Listen mit Tabulatoreinrückung erstellen. Folgen Sie dieser Anleitung für eine präzise Listenformatierung in Ihren Dokumenten. | | [Leerzeichen pro Ebene für Listeneinrückung verwenden](./use-space-character-per-level-for-list-indentation/) | Erfahren Sie, wie Sie in Aspose.Words für .NET mehrstufige Listen mit Leerzeicheneinrückung erstellen. Schritt-für-Schritt-Anleitung zur präzisen Dokumentformatierung. | - +| [DOCX als TXT speichern – Word‑Gleichungen nach LaTeX exportieren mit C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Erfahren Sie, wie Sie Word‑Gleichungen beim Exportieren von DOCX nach TXT in LaTeX mit C# konvertieren. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/german/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..10244ef38d --- /dev/null +++ b/words/german/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: docx als txt speichern mit Aspose.Words – Word schnell in txt konvertieren + und lernen, wie man mathematische Gleichungen als LaTeX exportiert. Einfacher C#‑Code, + keine zusätzlichen Werkzeuge nötig. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: de +og_description: Speichere docx als txt in C# und sieh, wie man Mathematik nach LaTeX + exportiert. Folge dieser Schritt‑für‑Schritt‑Anleitung, um Word in txt mit erhaltenen + Gleichungen zu konvertieren. +og_title: docx als txt speichern – Word‑Gleichungen nach LaTeX exportieren +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx als txt speichern – Word‑Gleichungen nach LaTeX exportieren mit C# +url: /de/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx als txt speichern – Word‑Gleichungen nach LaTeX exportieren mit C# + +Haben Sie jemals **docx als txt speichern** müssen, waren aber besorgt, dass Ihre Gleichungen verschwinden oder in unleserlichen Kauderwelsch verwandelt werden? Sie sind nicht allein. Viele Entwickler stoßen an diese Grenze, wenn sie versuchen, **word in txt zu konvertieren** für die nachgelagerte Verarbeitung, insbesondere wenn die Quelldatei Office‑Math‑Objekte enthält. + +Die gute Nachricht? Mit ein paar Zeilen C# und den richtigen Optionen können Sie nicht nur **Word in txt konvertieren**, sondern jede Gleichung als sauberes LaTeX‑Markup beibehalten. In diesem Tutorial führen wir Sie durch den gesamten Prozess, erklären, warum jede Einstellung wichtig ist, und zeigen Ihnen, wie Sie das Ergebnis überprüfen. + +Wir behandeln: + +* Installation der Aspose.Words for .NET‑Bibliothek +* Laden einer `.docx`, die mathematische Gleichungen enthält +* Konfiguration von `TxtSaveOptions`, sodass **how to export math** zu einer LaTeX‑freundlichen Zeichenkette wird +* Speichern der Datei und Überprüfen der Ausgabe + +Am Ende haben Sie ein wiederverwendbares Snippet, das Ihnen ermöglicht, **docx als txt zu speichern**, während jede Formel als LaTeX erhalten bleibt – perfekt für wissenschaftliche Pipelines, Static‑Site‑Generatoren oder jeden Workflow, der Klartext‑Mathematik benötigt. + +--- + +## Voraussetzungen + +Bevor wir starten, stellen Sie sicher, dass Sie folgendes haben: + +* .NET 6.0 oder höher (der Code funktioniert auch mit .NET Framework 4.6+) +* Visual Studio 2022 (oder jede IDE Ihrer Wahl) +* Das **Aspose.Words for .NET** NuGet‑Paket – installieren Sie es mit + +```bash +dotnet add package Aspose.Words +``` + +Es werden keine zusätzlichen Konverter oder externen Tools benötigt; Aspose.Words übernimmt das schwere Heben intern. + +--- + +## Schritt 1: Aspose.Words installieren und referenzieren + +Fügen Sie zunächst die Bibliothek zu Ihrem Projekt hinzu. Wenn Sie die Befehlszeile benutzen, führen Sie den oben stehenden Befehl aus. In Visual Studio können Sie außerdem mit Rechtsklick **Dependencies → Manage NuGet Packages** auswählen und nach *Aspose.Words* suchen. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro‑Tipp:** Verwenden Sie die neueste stabile Version (Stand April 2026 ist das 24.10). Neuere Releases bringen Bug‑Fixes für die OfficeMath‑Verarbeitung, sodass Sie überraschend fehlende Symbole vermeiden. + +--- + +## Schritt 2: Das Quell‑Dokument laden + +Jetzt holen wir das `.docx`, das die Gleichungen enthält, die Sie behalten möchten. Die Klasse `Document` abstrahiert die gesamte Word‑Datei und gibt Ihnen Zugriff auf Text, Bilder und Office‑Math‑Objekte. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Warum zuerst laden? Aspose.Words parsed die Datei in ein Objektmodell, sodass wir Inhalte inspizieren oder ändern können, bevor wir entscheiden, wie wir sie exportieren. Hier beginnen die Entscheidungen zu **how to export math** eine Rolle zu spielen. + +--- + +## Schritt 3: TxtSaveOptions für LaTeX‑Export konfigurieren + +Das Herzstück der Lösung ist die Klasse `TxtSaveOptions`. Standardmäßig entfernt das Speichern als TXT Office Math vollständig. Durch Setzen von `OfficeMathExportMode` auf `LaTeX` weist man die Bibliothek an, jede Gleichung in ihre LaTeX‑Darstellung zu übersetzen. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Warum LaTeX?** LaTeX ist die Lingua franca des wissenschaftlichen Publizierens. Durch den Export von Mathematik auf diese Weise erhalten Sie die Semantik der Gleichung statt eines flachen Bildes oder einer wirren Zeichenkette. Wenn Sie die TXT‑Datei später in einen Markdown‑Prozessor einspeisen, der MathJax unterstützt, werden die Gleichungen perfekt gerendert. + +--- + +## Schritt 4: Das Dokument als Klartext speichern + +Mit den konfigurierten Optionen ist der letzte Schritt ein Einzeiler, der die Datei auf die Festplatte schreibt. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Das war’s – Ihr `.docx` ist jetzt eine `.txt`‑Datei, in der jede Gleichung als LaTeX‑Snippet erscheint, bereit für die Weiterverarbeitung. + +--- + +## Ausgabe überprüfen (Wie man txt korrekt speichert) + +Öffnen Sie `MathSample.txt` in einem beliebigen Texteditor. Sie sollten etwas Ähnliches sehen: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Falls Sie rohe Word‑spezifische Zeichen (z. B. `?` oder fehlende Symbole) entdecken, prüfen Sie folgendes: + +* Sie verwenden eine aktuelle Aspose.Words‑Version (ältere Builds hatten Bugs mit OfficeMath). +* Das Quell‑Dokument enthält tatsächlich **OfficeMath**‑Objekte – nicht die veralteten Equation‑Editor‑Objekte. Letztere müssen Sie ggf. manuell konvertieren oder die Methode `ConvertMathToOfficeMath` vor dem Speichern verwenden. + +--- + +## Häufige Varianten & Sonderfälle + +| Situation | Was zu tun ist | +|-----------|----------------| +| **Legacy Equation Editor**‑Objekte | Rufen Sie `doc.ConvertMathToOfficeMath()` vor Schritt 3 auf. | +| **Sie benötigen plain Unicode‑Mathematik, nicht LaTeX** | Setzen Sie `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Große Dokumente (100 + MB)** | Streamen Sie den Speicher‑Vorgang mit `doc.Save(Stream, txtOptions)`, um hohen Speicherverbrauch zu vermeiden. | +| **Sie wollen den ursprünglichen Dateinamen beibehalten** | Verwenden Sie `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` beim Erzeugen des Ausgabepfads. | + +Diese Anpassungen beantworten die Frage „**how to export math**“ für verschiedene Pipelines und stellen sicher, dass Ihre Lösung unabhängig von der Quelle robust bleibt. + +--- + +## Vollständiges Beispiel (Alle Schritte an einem Ort) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Führen Sie das Programm aus, öffnen Sie die erzeugte `.txt`‑Datei, und Sie werden die LaTeX‑Gleichungen genau dort eingebettet sehen, wo sie hingehören. Dies ist der unkomplizierteste Weg, um **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/german/net/working-with-fonts/_index.md b/words/german/net/working-with-fonts/_index.md index f87fa7a1b5..33057b0853 100644 --- a/words/german/net/working-with-fonts/_index.md +++ b/words/german/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ Egal, ob Sie Text mit unterschiedlichen Schriftarten formatieren, Regeln für di | [Warnbenachrichtigung erhalten](./receive-warning-notification/) Erfahren Sie, wie Sie bei der Verwendung von Aspose.Words für .NET eine Warnbenachrichtigung erhalten und etwaige Probleme oder Warnungen in Ihren Dokumenten verwalten. | | [Beispiel für eine Steam-Schriftartquelle für Ressourcen](./resource-steam-font-source-example/) | Erfahren Sie, wie Sie mit der Resource Stream Font Source benutzerdefinierte Schriftarten in Aspose.Words für .NET laden. | | [Substitution ohne Suffixe erhalten](./get-substitution-without-suffixes/) | In diesem Lernprogramm erfahren Sie, wie Sie mit Aspose.Words für .NET suffixlose Überschreibungen in einem Word-Dokument erhalten. | - +| [Aspose-Schriftartenersetzung – Fehlende Schriftarten in Word-Dokumenten erkennen](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Erfahren Sie, wie Sie mit Aspose.Words für .NET fehlende Schriftarten in Word-Dokumenten erkennen und behandeln. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/german/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/german/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..3ae7f07af7 --- /dev/null +++ b/words/german/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Aspose-Schriftart-Substitutionsleitfaden zum Erkennen fehlender Schriftarten + beim Laden eines Word-Dokuments. Erfahren Sie, wie Sie Schriftarteinstellungen konfigurieren + und fehlende Schriftarten effizient handhaben. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: de +og_description: Aspose-Schriftartenersatzleitfaden zum Erkennen fehlender Schriftarten + beim Laden eines Word-Dokuments. Erfahren Sie, wie Sie Schriftarteinstellungen konfigurieren + und fehlende Schriftarten effizient handhaben. +og_title: Aspose-Schriftartenersetzung – Fehlende Schriftarten in Word-Dokumenten + erkennen +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose-Schriftarten-Substitution – Fehlende Schriftarten in Word-Dokumenten + erkennen +url: /de/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Fehlende Schriftarten in Word-Dokumenten erkennen + +Sind Sie schon einmal auf eine Word‑Datei gestoßen, die auf einem Rechner perfekt aussieht, auf einem anderen jedoch merkwürdige Schriftarten‑Änderungen zeigt? Das ist das klassische **aspose font substitution**‑Problem und bedeutet in der Regel, dass einige Schriftarten auf dem Zielsystem fehlen. In diesem Tutorial zeigen wir Ihnen Schritt für Schritt, wie Sie **fehlende Schriftarten** erkennen, wenn Sie ein **Word‑Dokument laden**, wie Sie **Schrifteinstellungen konfigurieren** und was Sie tun können, um **fehlende Schriftarten** elegant zu **handhaben**. + +Wir gehen ein komplettes, ausführbares C#‑Beispiel durch, erklären, warum jede Zeile wichtig ist, und zeigen Ihnen sogar die Konsolenausgabe, die Sie erwarten sollten. Am Ende können Sie Schriftarten‑Substitutionen im Moment des Ladens eines Dokuments erkennen – ohne Rätselraten. + +## Was Sie lernen werden + +- Wie Sie den Diagnose‑Collector von Aspose.Words für Schriftarten‑Warnungen aktivieren. +- Den genauen Code, der benötigt wird, um ein **Word‑Dokument zu laden** mit benutzerdefinierten **Schrifteinstellungen**. +- Wie Sie über `WarningInfo`‑Objekte iterieren, um jede ersetzte Schriftart aufzulisten. +- Tipps zum Unterdrücken unerwünschter Warnungen oder zum Bereitstellen von Ersatzschriftarten. +- Ein sofort ausführbares Beispiel, das Sie in Visual Studio kopieren‑und‑einfügen können. + +### Voraussetzungen + +- .NET 6.0 oder höher (die API funktioniert genauso unter .NET Framework). +- Aspose.Words für .NET (NuGet‑Paket `Aspose.Words`). +- Eine Word‑Datei, die eine Schriftart referenziert, die Sie nicht installiert haben (z. B. `MissingFont.docx`). + +Wenn Sie das haben, legen wir los. + +## Schritt 1 – Diagnose‑Collector aktivieren (Schrifteinstellungen konfigurieren) + +Zuerst: Aspose.Words zeichnet Schriftarten‑Substitutions‑Warnungen nur auf, wenn Sie es ihm sagen. Das geschieht, indem Sie ein `FontSettings`‑Objekt erstellen und es einer `LoadOptions`‑Instanz zuweisen. Denken Sie dabei an das Einschalten der „Debug‑Lichter“ für die Schriftarten‑Verarbeitung. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Warum?** +Ohne ein `FontSettings`‑Objekt bleibt der Warn‑Collector stumm, und Sie erfahren nie, welche Schriftarten ausgetauscht wurden. Durch die leere Initialisierung lassen wir Aspose die Standardsystem‑Schriftarten verwenden *und* jede Substitution nachverfolgen. + +> **Pro‑Tipp:** Wenn Sie wissen, dass ein bestimmter Ordner Unternehmens‑Schriftarten enthält, verweisen Sie `FontSettings` mit `SetFontsFolder("path")` darauf. Das kann die Anzahl der Fehlermeldungen reduzieren. + +## Schritt 2 – Dokument mit den konfigurierten Optionen laden (Word‑Dokument laden) + +Jetzt, wo der Collector aktiv ist, laden Sie Ihre `.docx`‑Datei mit denselben `LoadOptions`. In diesem Moment scannt Aspose das Dokument, sucht jede Schriftarten‑Referenz und entscheidet, ob eine Substitution nötig ist. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Warum ist das wichtig?** +Wenn Sie einfach `new Document("MissingFont.docx")` aufrufen, gelten die Standardeinstellungen *und* die Warnliste bleibt leer. Das Übergeben von `loadOptions` stellt sicher, dass der Diagnose‑Collector in die Ladeschleife eingebunden ist. + +## Schritt 3 – Schriftarten‑Substitutions‑Warnungen abrufen und anzeigen (fehlende Schriftarten erkennen) + +Nachdem das Dokument im Speicher ist, speichert Aspose alle Warnungen in `document.WarningCallback.Warnings`. Durchlaufen Sie diese Sammlung, filtern Sie nach `WarningType.FontSubstitution` und geben Sie die Beschreibung aus. Jede Beschreibung sagt Ihnen, welche Schriftart fehlte und welche stattdessen verwendet wurde. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Erwartete Konsolenausgabe** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Das Ergebnis zeigt genau, welche Schriftarten auf dem Rechner, auf dem der Code läuft, fehlen. Sie können nun entscheiden, ob Sie die fehlenden Schriftarten installieren, sie ins Dokument einbetten oder die Substitution beibehalten. + +![Konsolenausgabe, die Aspose‑Schriftarten‑Substitutions‑Warnungen zeigt](/images/aspose-font-substitution-console.png) + +*Bild‑Alt‑Text:* aspose font substitution – console output listing substituted fonts + +## Schritt 4 – Optional: Substitutions‑Verhalten anpassen (fehlende Schriftarten handhaben) + +Manchmal wollen Sie nicht nur wissen, *dass* eine Substitution stattgefunden hat – Sie wollen steuern, *wie* sie erfolgt. Aspose.Words lässt Sie eine benutzerdefinierte `IFontSubstitutionRule` registrieren. Das folgende Beispiel zwingt jede fehlende Schriftart, auf `Tahoma` zurückzugreifen. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Wann würden Sie das verwenden?** +Wenn Sie PDFs für einen Web‑Service erzeugen und wissen, dass jeder Client `Tahoma` rendern kann, garantiert das Erzwingen des Fallbacks visuelle Konsistenz, ohne Dutzende von Schriftdateien ausliefern zu müssen. + +## Vollständiges funktionierendes Beispiel (Alle Schritte kombiniert) + +Hier ist das gesamte Programm, das Sie in ein neues Konsolen‑Projekt einfügen können. Es kompiliert sofort, vorausgesetzt, Sie haben das Aspose.Words‑NuGet‑Paket installiert. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Starten Sie das Programm, beobachten Sie die Konsole, und Sie sehen jedes Ereignis einer fehlenden Schriftart. Anschließend können Sie entscheiden, ob Sie die fehlenden Schriftarten installieren, einbetten oder das Fallback beibehalten. + +## Häufig gestellte Fragen + +**F: Funktioniert das mit PDF‑Konvertierung?** +Ja. Wenn Sie später `doc.Save("output.pdf")` aufrufen, werden die während des Ladens substituierten Schriftarten in das PDF eingebettet. Das frühzeitige Abfangen der Warnungen hilft, überraschende Schriftarten‑Änderungen im finalen PDF zu vermeiden. + +**F: Was, wenn ich viele Dokumente verarbeiten muss?** +Packen Sie die Ladelogik in einen `try‑catch`‑Block und verwenden Sie eine einzige `FontSettings`‑Instanz für mehrere Dokumente. Das reduziert den Overhead und hält den Warn‑Collector für jede Datei aktiv. + +**F: Kann ich die Warnungen komplett unterdrücken?** +Sie können `loadOptions.WarningCallback = null;` setzen, bevor Sie laden, aber dann verlieren Sie die Möglichkeit, **fehlende Schriftarten zu erkennen** – was in den meisten Fällen nicht gewünscht ist. + +## Fazit + +Wir haben alles behandelt, was Sie benötigen, um **aspose font substitution** zu meistern: den Diagnose‑Collector aktivieren, ein Word‑Dokument mit benutzerdefinierten **Schrifteinstellungen** laden, die Liste fehlender Schriftarten extrahieren und sogar die Standard‑Substitutions‑Regel überschreiben, um **fehlende Schriftarten** nach Ihren Vorgaben zu **handhaben**. Mit nur wenigen Zeilen C# erhalten Sie volle Transparenz über Schriftarten‑Probleme, die sonst hinter subtilen Layout‑Änderungen verborgen bleiben. + +Nächste Schritte? Versuchen Sie, die Original‑Schriftarten mit `FontSettings.SetFontsFolder` ins Dokument einzubetten oder erkunden Sie `FontSourceBase`, um Schriftarten aus einer Datenbank zu laden. Sie können auch mit der `Document.BuiltInStyle`‑Sammlung experimentieren, um zu sehen, wie Stil‑ebene Schriftarten‑Änderungen sich auswirken. + +Haben Sie weitere Fragen zu Aspose.Words oder zum Schriftarten‑Management? Hinterlassen Sie einen Kommentar, stöbern Sie in der offiziellen Aspose‑Dokumentation oder starten Sie ein neues Projekt und probieren Sie den obigen Code aus. Viel Spaß beim Coden, und möge Ihr Dokument stets exakt wie beabsichtigt dargestellt werden! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/basic-conversions/_index.md b/words/greek/net/basic-conversions/_index.md index b8bb182fcb..0a273d38e3 100644 --- a/words/greek/net/basic-conversions/_index.md +++ b/words/greek/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [Πώς να εξάγετε LaTeX από το Word – Οδηγός βήμα‑βήμα](./how-to-export-latex-from-word-step-by-step-guide/) | Μάθετε πώς να εξάγετε έγγραφα Word σε μορφή LaTeX χρησιμοποιώντας το Aspose.Words για .NET με βήμα‑βήμα οδηγίες. | | [Μετατροπή Word σε PDF σε C# χρησιμοποιώντας το Aspose.Words – Οδηγός](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Μάθετε πώς να μετατρέπετε αρχεία Word σε PDF χρησιμοποιώντας το Aspose.Words για .NET σε C# με οδηγίες βήμα‑βήμα. | | [Αποθήκευση Word ως PDF με Aspose.Words – Πλήρης Οδηγός C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Μάθετε πώς να αποθηκεύετε έγγραφα Word ως PDF χρησιμοποιώντας το Aspose.Words σε C# με πλήρη οδηγό βήμα‑βήμα. | +| [Μετατροπή Word σε PDF σε C# – Πλήρης Οδηγός με Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Μάθετε πώς να μετατρέπετε αρχεία Word σε PDF χρησιμοποιώντας το Aspose.Words για .NET σε C# με πλήρη οδηγό βήμα‑βήμα. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/greek/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..e8d7d87e93 --- /dev/null +++ b/words/greek/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,196 @@ +--- +category: general +date: 2026-04-05 +description: Μετατροπή Word σε PDF σε C# χρησιμοποιώντας το Aspose.Words. Μάθετε πώς + να αποθηκεύετε docx ως PDF, να εξάγετε προσβάσιμο PDF και να φορτώνετε έγγραφο Word + αποδοτικά. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: el +og_description: Μετατρέψτε το Word σε PDF σε C# με έναν οδηγό βήμα‑βήμα. Ανακαλύψτε + πώς να αποθηκεύσετε docx ως PDF, να εξάγετε προσβάσιμο PDF και να φορτώσετε έγγραφο + Word χρησιμοποιώντας το Aspose.Words. +og_title: Μετατροπή Word σε PDF σε C# – Πλήρης Εκπαιδευτικό Σεμινάριο Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Μετατροπή Word σε PDF σε C# – Πλήρης Οδηγός με το Aspose.Words +url: /el/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή Word σε PDF με C# – Πλήρης Προγραμματιστικό Εγχειρίδιο + +Έχετε αναρωτηθεί ποτέ πώς να **convert word to pdf** χωρίς να παλεύετε με περίπλοκα εργαλεία γραμμής εντολών ή υπηρεσίες τρίτων; Δεν είστε οι μόνοι. Πολλοί προγραμματιστές συναντούν αυτό το πρόβλημα όταν ένας πελάτης ζητά ένα προσβάσιμο PDF απευθείας από ένα αρχείο DOCX. Τα καλά νέα; Με λίγες γραμμές C# και τη δυνατή βιβλιοθήκη Aspose.Words, μπορείτε να μετατρέψετε ένα έγγραφο Word σε ένα PDF που συμμορφώνεται με τα πρότυπα σε ελάχιστο χρόνο. + +Σε αυτόν τον οδηγό θα περάσουμε από όλα όσα χρειάζεται να γνωρίζετε: από τα βασικά του **load word document**, μέσω της ρύθμισης των σωστών επιλογών για **how to export accessible pdf**, και τέλος την αποθήκευση του αποτελέσματος ώστε να μπορείτε αξιόπιστα να **save docx as pdf**. Στο τέλος θα έχετε ένα έτοιμο προς εκτέλεση απόσπασμα κώδικα που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET. + +> **Pro tip:** Εάν στοχεύετε στη συμμόρφωση PDF/UA‑2 (το πρότυπο προσβασιμότητας που απαιτούν πολλές κυβερνητικές υπηρεσίες), ο ίδιος κώδικας λειτουργεί χωρίς επιπλέον βήματα — απλώς ορίστε τη σωστή σημαία `PdfCompliance`. + +--- + +## Τι Θα Μάθετε + +- Πώς να **load word document** χρησιμοποιώντας το Aspose.Words σε C#. +- Οι ακριβείς ρυθμίσεις που απαιτούνται για **how to export accessible pdf** (PDF/UA‑2). +- Ένα πλήρες, εκτελέσιμο παράδειγμα που **save docx as pdf** με μία κλήση μεθόδου. +- Συνηθισμένες παγίδες όταν **c# convert docx pdf** και πώς να τις αποφύγετε. +- Γρήγοροι τρόποι επαλήθευσης ότι το παραγόμενο PDF πληροί τις απαιτήσεις προσβασιμότητας. + +Χωρίς εξωτερικά εργαλεία, χωρίς ασαφή αρχεία ρυθμίσεων — μόνο καθαρός κώδικας C# που μπορείτε να μεταγλωττίσετε σήμερα. + +## Προαπαιτούμενα + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +1. **.NET 6.0** (ή οποιαδήποτε πρόσφατη έκδοση .NET) εγκατεστημένο. Παλαιότερα πλαίσια λειτουργούν επίσης, αλλά η σύνταξη παρακάτω υποθέτει το σύγχρονο SDK. +2. Μία **license** για το Aspose.Words for .NET. Η βιβλιοθήκη προσφέρει δωρεάν δοκιμή, αλλά για παραγωγή θα χρειαστείτε ένα έγκυρο κλειδί. +3. Το πακέτο **Aspose.Words** NuGet προστέθηκε στο έργο σας: + +```bash +dotnet add package Aspose.Words +``` + +Αυτό είναι όλο — χωρίς επιπλέον δυαδικά αρχεία, χωρίς COM interop, μόνο μια καθαρή αναφορά NuGet. + +![μετατροπή word σε pdf χρησιμοποιώντας Aspose.Words σε C#](image-placeholder.png "μετατροπή word σε pdf χρησιμοποιώντας Aspose.Words σε C#") + +## Υλοποίηση Βήμα‑βήμα + +Παρακάτω χωρίζουμε τη διαδικασία σε λογικά τμήματα. Κάθε βήμα περιέχει ένα μικρό απόσπασμα κώδικα, μια εξήγηση του **why** που είναι σημαντικό, και μια συμβουλή που προέρχεται από πραγματική χρήση. + +### ## Μετατροπή Word σε PDF – Φόρτωση του Πηγαίου Εγγράφου + +Το πρώτο πράγμα που πρέπει να κάνετε είναι **load word document** στη μνήμη. Το Aspose.Words αφαιρεί την πολυπλοκότητα του OpenXML parsing, ώστε να μπορείτε να εργάζεστε με αρχεία DOCX, DOC ή ακόμη και RTF χωρίς να ανησυχείτε για ιδιαιτερότητες μορφής. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +Η φόρτωση του αρχείου δημιουργεί ένα αντικείμενο `Document` που αντιπροσωπεύει ολόκληρο το αρχείο Word, συμπεριλαμβανομένων των κεφαλίδων, υποσέλιδων, στυλ και κρυφών μεταδεδομένων. Αν παραλείψετε αυτό το βήμα ή προσπαθήσετε να διαβάσετε το αρχείο ως ακατέργαστο ρεύμα, θα χάσετε τις πληροφορίες διάταξης που αργότερα καθορίζουν την εμφάνιση του PDF. + +> **Side note:** Ο ίδιος κατασκευαστής `Document` λειτουργεί για `.doc` και `.rtf`. Αυτό σημαίνει ότι μπορείτε να **c# convert docx pdf** ακόμη και όταν η πηγή δεν είναι αυστηρά DOCX. + +### ## Αποθήκευση DOCX ως PDF – Ρύθμιση Συμμόρφωσης PDF/UA‑2 + +Τώρα που το έγγραφο βρίσκεται στη μνήμη, λέμε στο Aspose.Words πώς θέλουμε να δημιουργηθεί το PDF. Για τις περισσότερες περιπτώσεις, οι προεπιλεγμένες ρυθμίσεις είναι επαρκείς, αλλά όταν χρειάζεστε ένα **accessible PDF** πρέπει να ενεργοποιήσετε τη σημαία συμμόρφωσης PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +Το `PdfCompliance.PdfUAXmpA2` λέει στη βιβλιοθήκη να ενσωματώσει τις απαραίτητες ετικέτες και δομές που εξαρτώνται οι αναγνώστες οθόνης. Χωρίς αυτή τη σημαία, μπορεί να έχετε ένα PDF που φαίνεται τέλεια αλλά αποτυγχάνει σε έλεγχο προσβασιμότητας. + +> **Tip:** Εάν χρειάζεστε μόνο ένα κανονικό PDF, μπορείτε να παραλείψετε τη γραμμή `Compliance`. Οι υπόλοιπες επιλογές εξακολουθούν να παρέχουν υψηλής ποιότητας έξοδο. + +### ## Μετατροπή Word σε PDF – Εγγραφή του Αρχείου + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- Ένα αρχείο PDF στο `outputPath` που αντικατοπτρίζει τη διάταξη του Word. +- Εάν χρησιμοποιήσατε τη σημαία `PdfUAXmpA2`, το PDF θα είναι σημειωμένο ως συμμορφωμένο με PDF/UA‑2. +- Όλες οι γραμματοσειρές ενσωματώνονται, ώστε το αρχείο να φαίνεται ταυτόσημο σε οποιονδήποτε υπολογιστή. + +### ## Επαλήθευση του Προσβάσιμου PDF (Προαιρετικό αλλά Συνιστώμενο) + +Μετά τη μετατροπή, είναι καλή ιδέα να ελέγξετε ξανά ότι το PDF πραγματικά **how to export accessible pdf** σωστά. Μπορείτε να χρησιμοποιήσετε δωρεάν εργαλεία όπως το “Accessibility Check” του Adobe Acrobat Reader ή τον ανοιχτού κώδικα επικυρωτή `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Εάν ο επικυρωτής δεν αναφέρει σφάλματα, έχετε επιτυχώς **convert word to pdf** με πλήρη υποστήριξη προσβασιμότητας. + +### ## Συνηθισμένες Παγίδες Όταν C# Μετατρέπετε DOCX σε PDF + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|------------------|----------| +| Απουσία γραμματοσειρών | Το αρχικό DOCX χρησιμοποιεί προσαρμοσμένη γραμματοσειρά που δεν είναι εγκατεστημένη στον διακομιστή. | Ορίστε `EmbedFullFonts = true` ή εγκαταστήστε τη γραμματοσειρά στο μηχάνημα. | +| Μεγάλο μέγεθος αρχείου | Οι εικόνες ενσωματώνονται σε πλήρη ανάλυση. | Χρησιμοποιήστε `ImageCompression = PdfImageCompression.Jpeg` και ορίστε το `JpegQuality` σε χαμηλότερη τιμή. | +| Κατεστραμμένοι υπερσύνδεσμοι | Οι σύνδεσμοι δείχνουν σε σχετικές διαδρομές που δεν υπάρχουν στον πελάτη. | Βεβαιωθείτε ότι τα URLs είναι απόλυτα ή προσαρμόστε την ιδιότητα `HyperlinkTarget`. | +| Λείπουν ετικέτες προσβασιμότητας | Η σημαία `Compliance` δεν έχει οριστεί. | Προσθέστε `Compliance = PdfCompliance.PdfUAXmpA2` όπως φαίνεται παραπάνω. | + +Κρατώντας αυτά στο μυαλό, η ρουτίνα **c# convert docx pdf** θα είναι ανθεκτική και έτοιμη για παραγωγή. + +## Πλήρες Παράδειγμα Εργασίας + +Συνδυάζοντας όλα τα παραπάνω, εδώ είναι μια αυτόνομη εφαρμογή κονσόλας που μπορείτε να μεταγλωττίσετε και να εκτελέσετε αμέσως. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** Μετά την εκτέλεση του προγράμματος, θα βρείτε το `output.pdf` στο `C:\Docs`. Ανοίξτε το σε οποιονδήποτε προβολέα PDF· η διάταξη θα ταιριάζει με το `input.docx` pixel‑for‑pixel, και ένας έλεγχος προσβασιμότητας θα επιβεβαιώσει τη συμμόρφωση PDF/UA‑2. + +## Συμπέρασμα + +Μόλις περάσαμε από μια πλήρη, ολοκληρωμένη λύση για το πώς να **convert word to pdf** χρησιμοποιώντας C# και Aspose.Words. Με το **load word document**, τη ρύθμιση των σωστών `PdfSaveOptions` και τέλος το **save docx as pdf**, λαμβάνετε ένα υψηλής ποιότητας, προσβάσιμο PDF με ελάχιστο κώδικα. Είτε δημιουργείτε μια μικροϋπηρεσία δημιουργίας εγγράφων, είτε έναν τοπικό μετατροπέα παρτίδας, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-markdownsaveoptions/_index.md b/words/greek/net/programming-with-markdownsaveoptions/_index.md index 4d29db5c00..fea5641e62 100644 --- a/words/greek/net/programming-with-markdownsaveoptions/_index.md +++ b/words/greek/net/programming-with-markdownsaveoptions/_index.md @@ -34,6 +34,8 @@ | [Πώς να αποθηκεύσετε Markdown από DOCX – Οδηγός βήμα‑βήμα](./how-to-save-markdown-from-docx-step-by-step-guide/) | Μάθετε πώς να αποθηκεύσετε αρχεία DOCX ως Markdown με οδηγίες βήμα‑βήμα χρησιμοποιώντας Aspose.Words για .NET. | | [Πώς να εξάγετε Markdown από το Word – Πλήρης οδηγός C#](./how-to-export-markdown-from-word-complete-c-guide/) | Μάθετε πώς να εξάγετε έγγραφα Word σε μορφή Markdown με πλήρη οδηγό C# χρησιμοποιώντας Aspose.Words. | | [Πώς να αποθηκεύσετε Markdown από DOCX – Οδηγός βήμα‑βήμα](./how-to-save-markdown-from-docx-step-by-step-guide/) | Μάθετε πώς να αποθηκεύσετε αρχεία DOCX ως Markdown με οδηγίες βήμα‑βήμα χρησιμοποιώντας Aspose.Words για .NET. | +| [Μετατροπή DOCX σε Markdown – Εξαγωγή εικόνων από DOCX με Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Μάθετε πώς να εξάγετε εικόνες από αρχεία DOCX κατά τη μετατροπή σε Markdown χρησιμοποιώντας Aspose.Words για .NET. | +| [Μετατροπή Word σε Markdown – Πλήρης Οδηγός με Εξαγωγή PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Μάθετε πώς να μετατρέψετε έγγραφα Word σε Markdown και να εξάγετε PDF/UA με πλήρη οδηγό C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/greek/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..1cd1fcbc9d --- /dev/null +++ b/words/greek/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Μάθετε πώς να μετατρέπετε DOCX σε Markdown και να εξάγετε εικόνες από + DOCX σε C#. Οδηγός βήμα‑προς‑βήμα με πλήρη κώδικα και συμβουλές. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: el +og_description: Μετατρέψτε DOCX σε Markdown και εξάγετε εικόνες από DOCX χρησιμοποιώντας + το Aspose.Words. Πλήρες tutorial C# με κώδικα, εξήγηση και συμβουλές βέλτιστων πρακτικών. +og_title: Μετατροπή DOCX σε Markdown – Εξαγωγή εικόνων από DOCX σε C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Μετατροπή DOCX σε Markdown – Εξαγωγή εικόνων από DOCX με το Aspose.Words +url: /el/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή DOCX σε Markdown – Εξαγωγή Εικόνων από DOCX σε C# + +Έχετε ποτέ χρειαστεί να **μετατρέψετε DOCX σε Markdown** αλλά να αντιμετωπίζετε το πρόβλημα των εικόνων που εξαφανίζονται στο αποτέλεσμα; Δεν είστε ο μόνος. Σε πολλά έργα η έκδοση markdown είναι ιδανική για έλεγχο εκδόσεων ή στατικούς δημιουργούς ιστοσελίδων, ωστόσο οι εικόνες μένουν πίσω, μετατρέποντας ένα πλούσιο έγγραφο σε ένα άδειο αρχείο κειμένου. + +Τα καλά νέα; Με λίγες γραμμές C# και Aspose.Words μπορείτε να **μετατρέψετε DOCX σε Markdown** *και* **εξάγετε εικόνες από DOCX** αυτόματα. Αυτός ο οδηγός σας καθοδηγεί σε όλη τη διαδικασία, εξηγεί γιατί κάθε μέρος είναι σημαντικό, και ακόμη σας δείχνει πώς να διατηρείτε τον φάκελο εικόνων τακτοποιημένο. + +## Τι Θα Μάθετε + +- Πώς να φορτώσετε ένα DOCX που περιέχει εικόνες. +- Πώς να ορίσετε ένα προσαρμοσμένο `IResourceSavingCallback` που αποφασίζει πού θα αποθηκευτεί κάθε εικόνα. +- Πώς να διαμορφώσετε το `MarkdownSaveOptions` ώστε το παραγόμενο markdown να αναφέρει σωστά τις εξαγόμενες εικόνες. +- Συμβουλές για τη διαχείριση ειδικών περιπτώσεων όπως διπλότυπα ονόματα εικόνων ή μορφές μη‑PNG. +- Ένα πλήρες, έτοιμο για αντιγραφή‑επικόλληση δείγμα κώδικα που μπορείτε να εκτελέσετε σήμερα. + +### Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (το API λειτουργεί σε .NET Core, .NET Framework και .NET 5+). +- Άδεια για **Aspose.Words for .NET** (η δωρεάν δοκιμή λειτουργεί για δοκιμές). +- Βασική εξοικείωση με C# και Visual Studio (ή το αγαπημένο σας IDE). + +Αν τα έχετε, ας βουτήξουμε. + +--- + +## Βήμα 1: Ρύθμιση του Έργου και Εγκατάσταση του Aspose.Words + +Πρώτα, δημιουργήστε μια νέα εφαρμογή κονσόλας (ή ενσωματώστε την σε μια υπάρχουσα λύση). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Συμβουλή:** Χρησιμοποιήστε την πιο πρόσφατη έκδοση του NuGet (από Απρίλιο 2026 είναι η 24.12) για να λάβετε τις νεότερες βελτιώσεις εξαγωγής markdown. + +--- + +## Βήμα 2: Δημιουργία Callback για Αποθήκευση Εικόνων Στο Θέση που Θέλετε + +Το Aspose.Words σας επιτρέπει να παρεμβείτε σε κάθε πόρο (εικόνες, SVG κ.λπ.) που γράφεται κατά την εξαγωγή markdown. Με την υλοποίηση του `IResourceSavingCallback` μπορείτε: + +1. Επιλέξτε έναν φάκελο που βρίσκεται δίπλα στο αρχείο markdown. +2. Δημιουργήστε ένα μοναδικό όνομα αρχείου (ώστε να μην αντικαταστήσετε ποτέ μια υπάρχουσα εικόνα). +3. Αποφασίστε τη μορφή (εδώ επιβάλλουμε PNG για συνέπεια). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Γιατί όνομα βασισμένο σε GUID; + +Αν το πηγαίο DOCX περιέχει δύο εικόνες με το ίδιο αρχικό όνομα, μια απλή αντιγραφή‑επικόλληση θα αντικατέστησε μία από αυτές. Η χρήση του `Guid.NewGuid()` εγγυάται μοναδικότητα, κάτι που είναι ιδιαίτερα χρήσιμο όταν εκτελείτε τη μετατροπή πολλές φορές σε αυτοματοποιημένο pipeline. + +--- + +## Βήμα 3: Φόρτωση του DOCX και Σύνδεση των Επιλογών Markdown + +Τώρα φέρνουμε το έγγραφο στη μνήμη και συνδέουμε το callback που μόλις δημιουργήσαμε. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Τι κάνει ο κώδικας, βήμα προς βήμα + +| Βήμα | Σκοπός | +|------|--------| +| **Ορισμός διαδρομών** | Κρατά το έργο σας ευέλικτο· μπορείτε να δείξετε σε οποιονδήποτε φάκελο χωρίς επαναμεταγλώττιση. | +| **Φόρτωση του DOCX** | `Document` αναλύει το αρχείο Word, καθιστώντας όλα τα στοιχεία (παράγραφοι, πίνακες, εικόνες) προσβάσιμα. | +| **Διαμόρφωση `MarkdownSaveOptions`** | Το `ResourceSavingCallback` είναι το σημείο που εξάγει τις εικόνες. Χωρίς αυτό, το Aspose.Words θα ενσωμάτωνε τις εικόνες ως αλφαριθμητικά base64 ή θα τις αγνοούσε εντελώς, ανάλογα με τις ρυθμίσεις. | +| **Αποθήκευση** | `doc.Save` γράφει το αρχείο markdown και ενεργοποιεί το callback για κάθε εικόνα. | + +--- + +## Βήμα 4: Επαλήθευση του Αποτελέσματος – Τι Πρέπει να Δείτε; + +Μετά την εκτέλεση του προγράμματος, ανοίξτε το `DocWithImages.md`. Θα παρατηρήσετε συνδέσμους εικόνων markdown που φαίνονται ως εξής: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Και στο `C:\Docs\MarkdownResources` θα βρείτε μια σειρά από αρχεία PNG με ονόματα GUID. Ανοίξτε οποιοδήποτε – θα πρέπει να είναι ταυτόσημα με τις εικόνες που ήταν ενσωματωμένες στο αρχικό DOCX. + +Αν ανοίξετε το αρχείο markdown σε έναν προβολέα που σέβεται τις σχετικές διαδρομές (π.χ., προεπισκόπηση VS Code, GitHub ή στατικό δημιουργό ιστοσελίδων), οι εικόνες θα εμφανιστούν ακριβώς όπως στο Word. + +### Συνηθισμένα Προβλήματα & Πώς να τα Αποφύγετε + +| Συμπτωμα | Πιθανή Αιτία | Διόρθωση | +|----------|--------------|----------| +| Οι εικόνες εμφανίζονται ως σπασμένοι σύνδεσμοι | Το `ResourceFileName` δεν είχε οριστεί, έτσι το markdown δείχνει σε ένα ανύπαρκτο αρχείο. | Βεβαιωθείτε ότι `args.ResourceFileName = newFileName;` μέσα στο callback. | +| Τα αρχεία PNG είναι τεράστια | Οι αρχικές εικόνες ήταν JPEG ή BMP· η μετατροπή σε PNG μπορεί να αυξήσει το μέγεθος. | Ανιχνεύστε την αρχική μορφή μέσω `args.ResourceContentType` και διατηρήστε την: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Οι διπλότυπες εικόνες εξακολουθούν να εμφανίζονται | Χρησιμοποιήσατε στατικό όνομα αρχείου αντί για GUID. | Επιστρέψτε στη λογική GUID ή προσθέστε έναν μετρητή ανά τύπο εικόνας. | +| Η μετατροπή προκαλεί `FileNotFoundException` | Η διαδρομή του πηγαίου DOCX είναι λανθασμένη ή ο φάκελος δεν έχει δικαίωμα ανάγνωσης. | Επαληθεύστε τη διαδρομή και δώστε τα κατάλληλα δικαιώματα στο σύστημα αρχείων. | + +--- + +## Βήμα 5: Προχωρημένες Ρυθμίσεις (Προαιρετικό) + +### 5.1 Διατήρηση Αρχικών Μορφών Εικόνας + +Αν θέλετε οι εξαγόμενες εικόνες να διατηρούν τις αρχικές τους επεκτάσεις, τροποποιήστε το callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Ενσωμάτωση Εικόνων ως Base64 (Όταν *Δεν* Θέλετε Ξεχωριστά Αρχεία) + +Μερικές φορές ένα markdown σε ένα μόνο αρχείο είναι προτιμότερο (π.χ., για αποστολή μέσω email). Αλλάξτε την επιλογή: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Αλλά θυμηθείτε: **η εξαγωγή εικόνων από DOCX** είναι ο κύριος στόχος για τις περισσότερες ροές εργασίας στατικών ιστοσελίδων, έτσι η προσέγγιση με φάκελο είναι συνήθως η καλύτερη επιλογή. + +--- + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + +Παρακάτω είναι ολόκληρο το πρόγραμμα σε ένα αρχείο. Απλώς αντικαταστήστε τις διαδρομές με τις δικές σας και εκτελέστε. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Τρέξτε το με `dotnet run`. Όταν η κονσόλα εμφανίσει τη γραμμή ✅, ανοίξτε το αρχείο markdown και θα πρέπει να δείτε τις εικόνες σωστά αποδομένες. + +--- + +## Συμπέρασμα + +Τώρα έχετε μια **πλήρη, έτοιμη για παραγωγή λύση για μετατροπή DOCX σε Markdown και εξαγωγή εικόνων από DOCX** χρησιμοποιώντας το Aspose.Words σε C#. Η κύρια λέξη-κλειδί εμφανίζεται σε όλο τον οδηγό, ενισχύοντας τη σχετικότητα τόσο για τις μηχανές αναζήτησης όσο και για τους βοηθούς AI. + +Σε μία μόνο εκτέλεση ο κώδικας: + +1. Φορτώνει ένα έγγραφο Word. +2. Παρεμβαίνει σε κάθε εικόνα μέσω `IResourceSavingCallback`. +3. Αποθηκεύει κάθε εικόνα σε έναν προβλέψιμο φάκελο με μοναδικό όνομα. +4. Δημιουργεί markdown που αναφέρει αυτές τις εικόνες. + +Από εδώ μπορείτε: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/greek/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..972be8e59a --- /dev/null +++ b/words/greek/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Μετατρέψτε το Word σε Markdown γρήγορα και μάθετε επίσης πώς να αποθηκεύετε + ως PDF/UA σε C#. Κώδικας βήμα‑βήμα, συμβουλές και διαχείριση ειδικών περιπτώσεων. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: el +og_description: Μετατρέψτε το Word σε Markdown και αποθηκεύστε ως PDF/UA με το Aspose.Words. + Μάθετε το γιατί, το πώς και συμβουλές βέλτιστων πρακτικών σε έναν σύντομο οδηγό. +og_title: Μετατροπή Word σε Markdown – Πλήρης οδηγός C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Μετατροπή Word σε Markdown – Πλήρης Οδηγός με Εξαγωγή PDF/UA +url: /el/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Μετατροπή Word σε Markdown – Πλήρης Οδηγός με Εξαγωγή PDF/UA + +Σας έχετε αναρωτηθεί ποτέ πώς να **convert Word to Markdown** χωρίς να χάσετε εξισώσεις ή εικόνες; Δεν είστε μόνοι. Πολλοί προγραμματιστές χρειάζονται έναν αξιόπιστο τρόπο να μετατρέπουν αρχεία `.docx` σε καθαρό Markdown, ενώ εξακολουθούν να μπορούν να **save as PDF/UA** για PDFs που συμμορφώνονται με την προσβασιμότητα. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από μια πλήρη, έτοιμη‑για‑εκτέλεση λύση χρησιμοποιώντας το Aspose.Words for .NET, θα εξηγήσουμε γιατί κάθε ρύθμιση είναι σημαντική και θα σας δείξουμε πώς να διαχειριστείτε τα πιο δύσκολα μέρη όπως το OfficeMath και τα floating shapes. + +Στο τέλος αυτού του οδηγού θα έχετε ένα ενιαίο πρόγραμμα C# που: + +1. Φορτώνει ένα έγγραφο Word με χαλαρή ανάκτηση (ώστε τα κατεστραμμένα αρχεία να μην διακόπτουν την εκτέλεση). +2. Το εξάγει σε Markdown, μετατρέποντας τις εξισώσεις σε LaTeX και αποθηκεύοντας τις εικόνες μέσω μιας προσαρμοσμένης callback. +3. Αποθηκεύει το ίδιο έγγραφο ως αρχείο PDF/UA‑2 συμμορφωμένο, ενσωματώνοντας τα floating shapes ως inline tags. + +Ακούγεται πολύ; Καμία ανησυχία—ας βουτήξουμε. + +## Τι Θα Χρειαστεί + +- **Aspose.Words for .NET** (τελευταία έκδοση, 23.x τη στιγμή της συγγραφής). +- Ένα περιβάλλον ανάπτυξης .NET (Visual Studio 2022, Rider ή το `dotnet` CLI). +- Ένα δείγμα αρχείου Word (`input.docx`) τοποθετημένο σε φάκελο που μπορείτε να αναφέρετε. +- Βασική εξοικείωση με τη σύνταξη C#—τίποτα εξωπραγματικό, μόνο μερικές δηλώσεις `using`. + +> **Pro tip:** Αν χρησιμοποιείτε διαχειριστή πακέτων NuGet, προσθέστε τη βιβλιοθήκη με +> `dotnet add package Aspose.Words` ή μέσω του Visual Studio NuGet UI. + +## Βήμα 1 – Φόρτωση του Εγγράφου Word με Χαλαρή Ανάκτηση + +Όταν λαμβάνετε αρχεία Word από εξωτερικές πηγές, μπορεί να περιέχουν μικρή κατεστραμμένη δομή. Η ενεργοποίηση της **Relaxed** ανάκτησης λέει στο Aspose.Words να συνεχίσει αντί να ρίξει εξαίρεση. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Γιατί είναι σημαντικό:** +- `RecoveryMode.Relaxed` αποτρέπει ένα μόνο κατεστραμμένο παράγραφο να διακόψει ολόκληρη τη μετατροπή. +- Η παροχή ενός αντικειμένου `FontSettings` διασφαλίζει ότι τυχόν ελλείπουσες γραμματοσειρές αντικαθίστανται ομαλά, κάτι που είναι κρίσιμο όταν αργότερα αποδίδετε εξισώσεις ως LaTeX. + +## Βήμα 2 – Εξαγωγή σε Markdown (OfficeMath → LaTeX, Εικόνες μέσω Callback) + +Το Markdown δεν διαθέτει ενσωματωμένο τρόπο να αναπαραστήσει εξισώσεις Word. Το Aspose.Words μπορεί να μεταφράσει αντικείμενα **OfficeMath** σε LaTeX, το οποίο καταλαβαίνουν οι περισσότεροι renderers του Markdown. Οι εικόνες, όμως, πρέπει να αποθηκευτούν κάπου· μια προσαρμοσμένη **resource‑saving callback** σας δίνει πλήρη έλεγχο πάνω στη δομή των φακέλων και στην ονομασία. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Η Callback Αποθήκευσης Πόρων + +Παρακάτω υπάρχει μια μικρή υλοποίηση που αποθηκεύει κάθε εικόνα σε υπο‑φάκελο με όνομα `images` και ονομάζει τα αρχεία `img001.png`, `img002.png`, κ.λπ. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Γιατί τη χρειάζεστε:** +- Χωρίς μια callback, το Aspose.Words δημιουργεί έναν επίπεδο φάκελο με τυχαία ονόματα GUID, κάτι που κάνει το version control ακατάστατο. +- Ελέγχοντας το σχήμα ονομασίας διατηρείτε το αποθετήριο Markdown τακτοποιημένο και αναπαραγώγιμο. + +### Αναμενόμενη Έξοδος Markdown + +Ανοίξτε το `doc.md` μετά την εκτέλεση και θα δείτε: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Οι εξισώσεις εμφανίζονται ως LaTeX τυλιγμένες σε `$$ … $$`, και οι εικόνες αναφέρονται στον φάκελο `images` που μόλις δημιουργήσατε. + +## Βήμα 3 – Εξαγωγή σε PDF/UA‑2 (Έτοιμο για Προσβασιμότητα) + +Αν χρειάζεται να μοιραστείτε το έγγραφο με χρήστες που εξαρτώνται από προγράμματα ανάγνωσης οθόνης ή άλλη βοηθητική τεχνολογία, η συμμόρφωση με **PDF/UA‑2** είναι το χρυσό πρότυπο. Το Aspose.Words μπορεί να το επιβάλει με μία μόνο σημαία, και μπορεί επίσης να «ισιώσει» τα floating shapes σε inline tags ώστε να μην χαθούν κατά τη μετατροπή. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Γιατί είναι σημαντικό το PDF/UA:** +- Το PDF/UA (Universal Accessibility) εγγυάται ότι το παραγόμενο PDF περιέχει σωστή σήμανση, λογική σειρά ανάγνωσης και εναλλακτικό κείμενο για τις εικόνες. +- Η ρύθμιση `ExportFloatingShapesAsInlineTag` εξασφαλίζει ότι σχήματα όπως πλαίσια κειμένου ή callouts δεν παραλείπονται ή τοποθετούνται λανθασμένα—ένα κοινό πρόβλημα κατά τη μετατροπή σύνθετων διατάξεων. + +### Επαλήθευση Συμμόρφωσης PDF/UA + +Μετά την εξαγωγή, ανοίξτε το PDF στο Adobe Acrobat Pro και εκτελέστε **“Accessibility Check”** (Tools → Accessibility → Full Check). Αν το εργαλείο αναφέρει **0 errors**, έχετε πετύχει. + +## Περιπτώσεις Άκρων & Συνηθισμένα Πίπτα + +| Κατάσταση | Τι Πρέπει Να Προσέξετε | Διόρθωση / Σύσταση | +|-----------|------------------------|--------------------| +| Το αρχείο Word περιέχει **μη υποστηριζόμενες γραμματοσειρές** | Οι γραμματοσειρές μπορεί να αντικατασταθούν, διαταράσσοντας τη διάταξη των εξισώσεων | Παρέχετε ένα προσαρμοσμένο `FontSettings` με εφεδρικές γραμματοσειρές. | +| Μεγάλα έγγραφα (> 100 MB) | Πίεση μνήμης κατά τη μετατροπή | Χρησιμοποιήστε `LoadOptions` με `LoadFormat.Docx` και ροή (stream) του αρχείου. | +| Οι εικόνες είναι γραφικά διανυσματικά **EMF/WMF** | Μπορεί να ραστεροποιηθούν ακούσια | Μετατρέψτε τις σε PNG μέσω `ImageSaveOptions` πριν την αποθήκευση. | +| Η PDF/UA αποτυγχάνει στον έλεγχο **ενσωματωμένων πινάκων** | Η σήμανση μπορεί να γίνει ασαφής | Ενεργοποιήστε `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` για βοήθεια της μηχανής. | +| Χρειάζεται **διατήρηση προσαρμοσμένων στυλ** | Το Markdown έχει περιορισμένες δυνατότητες στυλ | Εξάγετε ένα αρχείο CSS δίπλα στο Markdown και αναφερθείτε σε αυτό. | + +## Πλήρες Παράδειγμα Εργασίας (Όλος ο Κώδικας Μαζί) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Τρέξτε το πρόγραμμα, και θα βρείτε τόσο το `doc.md` (με εξισώσεις LaTeX και καθαρές συνδέσεις εικόνων) όσο και το `doc.pdf` (πλήρως συμμορφωμένο PDF/UA‑2) στο `YOUR_DIRECTORY`. + +## Οπτική Επισκόπηση + +![παράδειγμα μετατροπής word σε markdown](https://example.com/placeholder.png "παράδειγμα μετατροπής word σε markdown – δείχνει το εισαγόμενο Word, την έξοδο Markdown και το αρχείο PDF/UA") + +*Alt text:* **παράδειγμα μετατροπής word σε markdown** – διάγραμμα της διαδικασίας μετατροπής από αρχείο Word σε Markdown και PDF/UA. + +## Συνοπτική Επισκόπηση & Επόμενα Βήματα + +Μόλις **convert Word to Markdown** διατηρώντας τις εξισώσεις ανέπαφες, αποθηκεύσαμε τις εικόνες σε τακτοποιημένο φάκελο και παραγάγαμε ένα **save as PDF/UA** αρχείο που περνάει τους ελέγχους προσβασιμότητας. Τα κύρια συμπεράσματα είναι: + +- Χρησιμοποιήστε `LoadOptions.RecoveryMode.Relaxed` για να αντέχετε σε ατελή αρχεία Word. +- Ορίστε `OfficeMathExportMode` σε `LaTeX` για καθαρή απόδοση εξισώσεων. +- Υλοποιήστε ένα `ResourceSavingCallback` για έλεγχο της εξόδου εικόνων. +- Ενεργοποιήστε `PdfCompliance.PdfUAXmpA2` και `ExportFloatingShapesAsInlineTag` για PDF σύμφωνο με πρότυπα. + +### Τι να Εξερευνήσετε Στη Σύντομη Μελλοντική + +- **Custom CSS for Markdown** – δημιουργήστε ένα stylesheet που αντικατοπτρίζει τα στυλ του Word. +- **Batch processing** – επαναλάβετε τη διαδικασία σε έναν φάκελο `.docx` αρχείων για αυτοματοποιημένες μεγάλες μεταναστεύσεις. +- **Advanced PDF/UA features** – προσθέστε προσαρμοσμένες ετικέτες, ορίστε γλωσσικά χαρακτηριστικά ή ενσωματώστε περιγραφές ήχου. +- **Integration with CI/CD** – διασφαλίστε ότι κάθε build παράγει αυτόματα προσβάσιμα PDFs. + +Αν αντιμετωπίσετε κάποιο πρόβλημα, ελέγξτε ξανά ότι η έκδοση του Aspose.Words ταιριάζει με το API που χρησιμοποιείται εδώ, και θυμηθείτε ότι η τεκμηρίωση της βιβλιοθήκης είναι μια αξιόπιστη δευτερεύουσα αναφορά. + +Καλή κωδικοποίηση, και εύχομαι τα έγγραφά σας να παραμείνουν τόσο όμορφα **και** προσβάσιμα! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/programming-with-txtsaveoptions/_index.md b/words/greek/net/programming-with-txtsaveoptions/_index.md index cc4534b8cf..2e645480c4 100644 --- a/words/greek/net/programming-with-txtsaveoptions/_index.md +++ b/words/greek/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ | [Προσθήκη σημαδιών Bidi σε έγγραφο Word](./add-bidi-marks/) | Μάθετε πώς να προσθέτετε αμφίδρομα (Bidi) σημάδια σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET με αυτόν τον οδηγό. Εξασφαλίστε τη σωστή κατεύθυνση κειμένου για περιεχόμενο σε πολλές γλώσσες. | | [Χρήση χαρακτήρα Tab ανά επίπεδο για εσοχή λίστας](./use-tab-character-per-level-for-list-indentation/) | Μάθετε πώς να δημιουργείτε λίστες πολλαπλών επιπέδων με εσοχή με στηλοθέτες χρησιμοποιώντας το Aspose.Words για .NET. Ακολουθήστε αυτόν τον οδηγό για ακριβή μορφοποίηση λιστών στα έγγραφά σας. | | [Χρήση κενού διαστήματος ανά επίπεδο για εσοχή λίστας](./use-space-character-per-level-for-list-indentation/) | Μάθετε πώς να δημιουργείτε λίστες πολλαπλών επιπέδων με εσοχή διαστήματος στο Aspose.Words για .NET. Οδηγός βήμα προς βήμα για ακριβή μορφοποίηση εγγράφων. | - +| [Αποθήκευση docx ως txt – Εξαγωγή εξισώσεων Word σε LaTeX με C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Μάθετε πώς να μετατρέψετε εξισώσεις Word σε LaTeX κατά την αποθήκευση αρχείου docx ως txt χρησιμοποιώντας C# και Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/greek/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..21097fbe5d --- /dev/null +++ b/words/greek/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Αποθήκευση docx ως txt με το Aspose.Words – γρήγορη μετατροπή Word σε + txt και μάθετε πώς να εξάγετε μαθηματικές εξισώσεις ως LaTeX. Απλός κώδικας C#, + χωρίς επιπλέον εργαλεία. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: el +og_description: Αποθηκεύστε το docx ως txt σε C# και δείτε πώς να εξάγετε μαθηματικά + σε LaTeX. Ακολουθήστε αυτόν τον οδηγό βήμα‑βήμα για να μετατρέψετε το Word σε txt + με τις εξισώσεις αμετάβλητες. +og_title: Αποθήκευση docx ως txt – Εξαγωγή εξισώσεων Word σε LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Αποθήκευση docx ως txt – Εξαγωγή εξισώσεων Word σε LaTeX με C# +url: /el/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# αποθήκευση docx ως txt – Εξαγωγή εξισώσεων Word σε LaTeX με C# + +Έχετε ποτέ χρειαστεί να **αποθηκεύσετε docx ως txt** αλλά ανησυχείτε ότι οι εξισώσεις σας θα εξαφανιστούν ή θα μετατραπούν σε ακατανόητο χαοτικό κείμενο; Δεν είστε οι μόνοι. Πολλοί προγραμματιστές αντιμετωπίζουν αυτό το πρόβλημα όταν προσπαθούν να **μετατρέψουν word σε txt** για downstream επεξεργασία, ειδικά όταν το αρχείο προέλευσης περιέχει αντικείμενα Office Math. + +Τα καλά νέα; Με μερικές γραμμές C# και τις σωστές επιλογές, μπορείτε όχι μόνο να **μετατρέψετε Word σε txt**, αλλά και να διατηρήσετε κάθε εξίσωση ως καθαρό LaTeX markup. Σε αυτό το tutorial θα περάσουμε από όλη τη διαδικασία, θα εξηγήσουμε γιατί κάθε ρύθμιση είναι σημαντική και θα σας δείξουμε πώς να επαληθεύσετε το αποτέλεσμα. + +Θα καλύψουμε: + +* Εγκατάσταση της βιβλιοθήκης Aspose.Words for .NET +* Φόρτωση ενός `.docx` που περιέχει μαθηματικές εξισώσεις +* Διαμόρφωση του `TxtSaveOptions` ώστε το **how to export math** να γίνει μια συμβολοσειρά φιλική προς LaTeX +* Αποθήκευση του αρχείου και έλεγχος του αποτελέσματος + +Στο τέλος, θα έχετε ένα επαναχρησιμοποιήσιμο snippet που σας επιτρέπει να **αποθηκεύσετε docx ως txt** διατηρώντας κάθε τύπο ως LaTeX—ιδανικό για επιστημονικές pipelines, static site generators, ή οποιαδήποτε ροή εργασίας που χρειάζεται plain‑text μαθηματικά. + +--- + +## Προαπαιτήσεις + +Πριν βουτήξουμε, βεβαιωθείτε ότι έχετε: + +* .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί επίσης με .NET Framework 4.6+) +* Visual Studio 2022 (ή οποιοδήποτε IDE προτιμάτε) +* Το πακέτο NuGet **Aspose.Words for .NET** – εγκαταστήστε το με + +```bash +dotnet add package Aspose.Words +``` + +Δεν απαιτούνται πρόσθετοι μετατροπείς ή εξωτερικά εργαλεία· το Aspose.Words διαχειρίζεται το βαρέως φορτίου εσωτερικά. + +--- + +## Βήμα 1: Εγκατάσταση και αναφορά στο Aspose.Words + +Πρώτα, προσθέστε τη βιβλιοθήκη στο project σας. Αν χρησιμοποιείτε τη γραμμή εντολών, εκτελέστε την παραπάνω εντολή. Στο Visual Studio μπορείτε επίσης να κάνετε δεξί‑κλικ στο **Dependencies → Manage NuGet Packages** και να αναζητήσετε το *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Χρησιμοποιήστε την πιο πρόσφατη σταθερή έκδοση (από τον Απρίλιο 2026 είναι η 24.10). Οι νεότερες εκδόσεις φέρνουν διορθώσεις σφαλμάτων για τη διαχείριση του OfficeMath, ώστε να αποφύγετε την ξαφνική έλλειψη συμβόλων. + +--- + +## Βήμα 2: Φόρτωση του πηγαίου εγγράφου + +Τώρα φορτώνουμε το `.docx` που περιέχει τις εξισώσεις που θέλετε να διατηρήσετε. Η κλάση `Document` αφαιρεί την πλήρη δομή του αρχείου Word, παρέχοντάς σας πρόσβαση σε κείμενο, εικόνες και αντικείμενα Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Γιατί να το φορτώσουμε πρώτα; Το Aspose.Words αναλύει το αρχείο σε ένα μοντέλο αντικειμένων, επιτρέποντάς μας να ελέγξουμε ή να τροποποιήσουμε το περιεχόμενο πριν αποφασίσουμε πώς θα το εξάγουμε. Εδώ οι αποφάσεις για το **how to export math** αρχίζουν να έχουν σημασία. + +--- + +## Βήμα 3: Διαμόρφωση του TxtSaveOptions για εξαγωγή σε LaTeX + +Η καρδιά της λύσης είναι η κλάση `TxtSaveOptions`. Από προεπιλογή, η αποθήκευση σε TXT αφαιρεί εντελώς το Office Math. Ορίζοντας το `OfficeMathExportMode` σε `LaTeX` λέει στη βιβλιοθήκη να μεταφράσει κάθε εξίσωση στην LaTeX αναπαράστασή της. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Γιατί LaTeX;** Η LaTeX είναι η lingua franca της επιστημονικής δημοσίευσης. Εξάγοντας τα μαθηματικά με αυτόν τον τρόπο, διατηρείτε τη σημασιολογία της εξίσωσης αντί για μια επίπεδη εικόνα ή μια ακατάληπτη συμβολοσειρά. Αν αργότερα τροφοδοτήσετε το TXT σε έναν επεξεργαστή Markdown που υποστηρίζει MathJax, οι εξισώσεις θα αποδοθούν τέλεια. + +--- + +## Βήμα 4: Αποθήκευση του εγγράφου ως plain‑text + +Με τις επιλογές διαμορφωμένες, το τελευταίο βήμα είναι μια εντολή μίας γραμμής που γράφει το αρχείο στο δίσκο. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Αυτό είναι—το `.docx` σας είναι τώρα ένα αρχείο `.txt` όπου κάθε εξίσωση εμφανίζεται ως ένα απόσπασμα LaTeX, έτοιμο για downstream κατανάλωση. + +--- + +## Επαλήθευση του αποτελέσματος (Πώς να αποθηκεύσετε σωστά txt) + +Ανοίξτε το `MathSample.txt` σε οποιονδήποτε επεξεργαστή κειμένου. Θα πρέπει να δείτε κάτι όπως: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Αν εντοπίσετε ακατέργαστους χαρακτήρες ειδικούς του Word (π.χ., `?` ή ελλιπή σύμβολα), ελέγξτε ξανά ότι: + +* Χρησιμοποιείτε μια πρόσφατη έκδοση του Aspose.Words (παλαιότερες εκδόσεις είχαν σφάλματα με το OfficeMath). +* Το πηγαίο έγγραφο περιέχει πραγματικά αντικείμενα **OfficeMath**—όχι αντικείμενα του παλαιού Equation Editor. Για τα τελευταία, ίσως χρειαστεί να τα μετατρέψετε χειροκίνητα ή να χρησιμοποιήσετε τη μέθοδο `ConvertMathToOfficeMath` πριν από την αποθήκευση. + +--- + +## Συνηθισμένες Παραλλαγές & Ακραίες Περιπτώσεις + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** αντικείμενα | Καλέστε `doc.ConvertMathToOfficeMath()` πριν από το βήμα 3. | +| **Χρειάζεστε plain Unicode math, όχι LaTeX** | Ορίστε `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Μεγάλα έγγραφα (100 + MB)** | Χρησιμοποιήστε streaming στην αποθήκευση με `doc.Save(Stream, txtOptions)` για να αποφύγετε υψηλή χρήση μνήμης. | +| **Θέλετε να διατηρήσετε το αρχικό όνομα αρχείου** | Χρησιμοποιήστε `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` κατά την κατασκευή της διαδρομής εξόδου. | + +Αυτές οι προσαρμογές απαντούν στην ερώτηση “**how to export math**” για διαφορετικές pipelines, διασφαλίζοντας ότι η λύση σας είναι ανθεκτική ανεξάρτητα από την πηγή. + +--- + +## Πλήρες Παράδειγμα Εργασίας (Όλα τα βήματα σε ένα μέρος) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Εκτελέστε το πρόγραμμα, ανοίξτε το παραγόμενο `.txt`, και θα δείτε τις LaTeX εξισώσεις ενσωματωμένες ακριβώς εκεί που ανήκαν. Αυτός είναι ο πιο απλός τρόπος να **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/greek/net/working-with-fonts/_index.md b/words/greek/net/working-with-fonts/_index.md index ede9a6e5a7..5eeaf523fa 100644 --- a/words/greek/net/working-with-fonts/_index.md +++ b/words/greek/net/working-with-fonts/_index.md @@ -29,7 +29,7 @@ | [Λήψη απόστασης γραμματοσειράς](./get-font-line-spacing/) | Μάθετε πώς να βρείτε απόσταση μεταξύ γραμματοσειρών χρησιμοποιώντας το Aspose.Words για .NET με αυτό το βήμα προς βήμα σεμινάριο. Ιδανικό για προγραμματιστές. | | [Έλεγχος εφέ κειμένου DrawingML](./check-drawingml-text-effect/) Μάθετε πώς να ελέγχετε τα εφέ κειμένου DrawingML σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET με τον λεπτομερή, βήμα προς βήμα οδηγό μας. Βελτιώστε τα έγγραφά σας με ευκολία. | | [Ορισμός μορφοποίησης γραμματοσειράς](./set-font-formatting/) | Μάθετε πώς να ορίζετε τη μορφοποίηση γραμματοσειρών σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET. Ακολουθήστε τον λεπτομερή οδηγό μας βήμα προς βήμα για να βελτιώσετε την αυτοματοποίηση των εγγράφων σας. | -| [Ορισμός σημαδιού έμφασης γραμματοσειράς](./set-font-emphasis-mark/) | Μάθετε πώς να ορίζετε σημάδια έμφασης γραμματοσειράς σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET με αυτόν τον λεπτομερή οδηγό βήμα προς βήμα. Ιδανικό για προγραμματιστές .NET. | +| [Ορισμός σημαδιού έμφασης γραμματοσειράς](./set-font-emphasis-mark/) | Μάθετε πώς να ορίζετε σημάδια έμφασης γραμματοσειράς σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET με αυτόν τον λεπτομερής οδηγό βήμα προς βήμα. Ιδανικό για προγραμματιστές .NET. | | [Ορισμός φακέλων γραμματοσειρών](./set-fonts-folders/) | Μάθετε πώς να ορίζετε προσαρμοσμένους φακέλους γραμματοσειρών στο Aspose.Words για .NET με αυτόν τον ολοκληρωμένο οδηγό βήμα προς βήμα. Ιδανικό για προγραμματιστές που θέλουν να βελτιώσουν τις γραμματοσειρές εγγράφων. | | [Ενεργοποίηση Απενεργοποίηση Υποκατάστασης Γραμματοσειράς](./enable-disable-font-substitution/) | Μάθετε πώς να ενεργοποιείτε ή να απενεργοποιείτε την αντικατάσταση γραμματοσειρών σε έγγραφα του Word χρησιμοποιώντας το Aspose.Words για .NET. Βεβαιωθείτε ότι τα έγγραφά σας φαίνονται ομοιόμορφα σε όλες τις πλατφόρμες. | | [Ορισμός ρυθμίσεων εφεδρικής γραμματοσειράς](./set-font-fallback-settings/) | Μάθετε πώς να ορίζετε ρυθμίσεις αντικατάστασης γραμματοσειρών στο Aspose.Words για .NET και να προσαρμόζετε την αντικατάσταση γραμματοσειρών στα έγγραφά σας στο Word. | @@ -48,8 +48,7 @@ | [Λήψη ειδοποίησης προειδοποίησης](./receive-warning-notification/) Μάθετε πώς να λαμβάνετε μια ειδοποίηση προειδοποίησης όταν χρησιμοποιείτε το Aspose.Words για .NET και να διαχειρίζεστε τυχόν προβλήματα ή προειδοποιήσεις στα έγγραφά σας. | | [Παράδειγμα Πηγής Γραμματοσειράς Πόρων Steam](./resource-steam-font-source-example/) | Μάθετε πώς να χρησιμοποιείτε το Resource Stream Font Source για να φορτώνετε προσαρμοσμένες γραμματοσειρές στο Aspose.Words για .NET. | | [Λήψη αντικατάστασης χωρίς επιθήματα](./get-substitution-without-suffixes/) | Σε αυτό το σεμινάριο, μάθετε πώς να λαμβάνετε παρακάμψεις χωρίς επιθήματα σε ένα έγγραφο του Word με το Aspose.Words για .NET. | - - +| [Αντικατάσταση Γραμματοσειρών Aspose – Εντοπισμός Ελλειπουσών Γραμματοσειρών σε Έγγραφα Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Μάθετε πώς να εντοπίζετε ελλείπουσες γραμματοσειρές σε έγγραφα Word χρησιμοποιώντας το Aspose.Words για .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/greek/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/greek/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..8c3264353f --- /dev/null +++ b/words/greek/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Οδηγός αντικατάστασης γραμματοσειρών Aspose για την ανίχνευση ελλιπών + γραμματοσειρών κατά τη φόρτωση ενός εγγράφου Word. Μάθετε πώς να διαμορφώσετε τις + ρυθμίσεις γραμματοσειρών και να διαχειρίζεστε αποτελεσματικά τις ελλιπείς γραμματοσειρές. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: el +og_description: Οδηγός αντικατάστασης γραμματοσειρών Aspose για την ανίχνευση ελλιπών + γραμματοσειρών κατά τη φόρτωση ενός εγγράφου Word. Μάθετε πώς να διαμορφώσετε τις + ρυθμίσεις γραμματοσειρών και να διαχειριστείτε αποτελεσματικά τις ελλιπείς γραμματοσειρές. +og_title: Αντικατάσταση γραμματοσειρών Aspose – Εντοπισμός ελλιπών γραμματοσειρών + σε έγγραφα Word +tags: +- Aspose.Words +- C# +- Font Management +title: Αντικατάσταση Γραμματοσειρών Aspose – Εντοπισμός Ελλειπουσών Γραμματοσειρών + σε Έγγραφα Word +url: /el/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Εντοπισμός Ελλειπόντων Γραμματοσειρών σε Έγγραφα Word + +Έχετε ποτέ αντιμετωπίσει ένα αρχείο Word που φαίνεται τέλειο σε έναν υπολογιστή αλλά εμφανίζει περίεργες αλλαγές γραμματοσειράς σε άλλο; Αυτό είναι το κλασικό πρόβλημα **aspose font substitution**, και συνήθως σημαίνει ότι λείπουν κάποιες γραμματοσειρές στο σύστημα-στόχο. Σε αυτό το tutorial θα σας δείξουμε, βήμα‑βήμα, πώς να **εντοπίσετε ελλειπούσες γραμματοσειρές** όταν **φορτώνετε ένα έγγραφο Word**, πώς να **ρυθμίσετε τις ρυθμίσεις γραμματοσειράς**, και τι να κάνετε για να **χειριστείτε τις ελλειπούσες γραμματοσειρές** με χάρη. + +Θα περάσουμε από ένα πλήρες, εκτελέσιμο παράδειγμα C#, θα εξηγήσουμε γιατί κάθε γραμμή είναι σημαντική, και ακόμη θα σας δείξουμε την έξοδο της κονσόλας που πρέπει να περιμένετε. Στο τέλος θα μπορείτε να εντοπίζετε τις αντικαταστάσεις γραμματοσειρών τη στιγμή που φορτώνεται ένα έγγραφο — χωρίς εικασίες. + +## Τι Θα Μάθετε + +- Πώς να ενεργοποιήσετε τον διαγνωστικό συλλέκτη του Aspose.Words για προειδοποιήσεις γραμματοσειρών. +- Ο ακριβής κώδικας που απαιτείται για **φόρτωση ενός εγγράφου Word** με προσαρμοσμένες **ρυθμίσεις γραμματοσειράς**. +- Πώς να επαναλάβετε τα αντικείμενα `WarningInfo` για να καταγράψετε κάθε αντικατεστημένη γραμματοσειρά. +- Συμβουλές για την καταστολή ανεπιθύμητων προειδοποιήσεων ή την παροχή εναλλακτικών γραμματοσειρών. +- Ένα έτοιμο προς εκτέλεση δείγμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο Visual Studio. + +### Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (το API λειτουργεί το ίδιο και στο .NET Framework). +- Aspose.Words για .NET (πακέτο NuGet `Aspose.Words`). +- Ένα αρχείο Word που αναφέρει μια γραμματοσειρά που δεν έχετε εγκατεστημένη (π.χ., `MissingFont.docx`). + +Αν τα έχετε, ας βουτήξουμε. + +## Βήμα 1 – Ενεργοποίηση του Διαγνωστικού Συλλέκτη (Ρύθμιση Ρυθμίσεων Γραμματοσειράς) + +Πρώτα απ' όλα: Το Aspose.Words καταγράφει προειδοποιήσεις αντικατάστασης γραμματοσειράς μόνο αν του το υποδείξετε. Αυτό γίνεται δημιουργώντας ένα αντικείμενο `FontSettings` και αντιστοιχίζοντάς το σε μια παρουσία `LoadOptions`. Σκεφτείτε το ως ενεργοποίηση των «φώτων εντοπισμού σφαλμάτων» για τη διαχείριση γραμματοσειρών. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Γιατί;** +Χωρίς ένα αντικείμενο `FontSettings` ο συλλέκτης προειδοποιήσεων παραμένει σιωπηλός, και δεν θα ξέρετε ποτέ ποιες γραμματοσειρές αντικαταστάθηκαν. Αρχικοποιώντας το κενό, επιτρέπουμε στο Aspose να χρησιμοποιήσει τις προεπιλεγμένες γραμματοσειρές του συστήματος *και* να παρακολουθεί τυχόν αντικαταστάσεις. + +> **Pro tip:** Αν γνωρίζετε ότι ένας συγκεκριμένος φάκελος περιέχει εταιρικές γραμματοσειρές, κατευθύνετε το `FontSettings` εκεί με `SetFontsFolder("path")`. Αυτό μπορεί να μειώσει τον αριθμό των προειδοποιήσεων ελλιπών γραμματοσειρών. + +## Βήμα 2 – Φόρτωση του Εγγράφου με τις Διαμορφωμένες Επιλογές (Load Word Document) + +Τώρα που ο συλλέκτης είναι ενεργός, φορτώστε το αρχείο `.docx` χρησιμοποιώντας τις ίδιες `LoadOptions`. Αυτή είναι η στιγμή που το Aspose σαρώνει το έγγραφο, ψάχνει για κάθε αναφορά γραμματοσειράς και αποφασίζει αν χρειάζεται αντικατάσταση. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Γιατί είναι σημαντικό;** +Αν απλώς καλέσατε `new Document("MissingFont.docx")`, οι προεπιλεγμένες ρυθμίσεις θα εφαρμοστούν *και* η λίστα προειδοποιήσεων θα παραμείνει κενή. Η μεταβίβαση των `loadOptions` εγγυάται ότι ο διαγνωστικός συλλέκτης είναι συνδεδεμένος στη διαδικασία φόρτωσης. + +## Βήμα 3 – Ανάκτηση και Εμφάνιση Προειδοποιήσεων Αντικατάστασης Γραμματοσειράς (Detect Missing Fonts) + +Αφού το έγγραφο είναι στη μνήμη, το Aspose αποθηκεύει τυχόν προειδοποιήσεις στο `document.WarningCallback.Warnings`. Περάστε τη συλλογή με βρόχο, φιλτράρετε για `WarningType.FontSubstitution` και εκτυπώστε την περιγραφή. Κάθε περιγραφή σας λέει ποια γραμματοσειρά έλειπε και ποια χρησιμοποιήθηκε αντί αυτής. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Αναμενόμενη έξοδος κονσόλας** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Αυτή η έξοδος σας λέει ακριβώς ποιες γραμματοσειρές λείπουν από το μηχάνημα που εκτελεί τον κώδικα. Τώρα μπορείτε να αποφασίσετε αν θα εγκαταστήσετε τις ελλιπείς γραμματοσειρές, θα τις ενσωματώσετε στο έγγραφο, ή θα διατηρήσετε την αντικατάσταση. + +![Έξοδος κονσόλας που εμφανίζει προειδοποιήσεις αντικατάστασης γραμματοσειράς Aspose](/images/aspose-font-substitution-console.png) + +*Κείμενο alt εικόνας:* αντικατάσταση γραμματοσειράς Aspose – έξοδος κονσόλας που καταγράφει τις αντικατεστημένες γραμματοσειρές + +## Βήμα 4 – Προαιρετικό: Προσαρμογή της Συμπεριφοράς Αντικατάστασης (Handle Missing Fonts) + +Μερικές φορές δεν θέλετε μόνο να ξέρετε *ότι* έγινε μια αντικατάσταση — θέλετε να ελέγξετε *πώς* συμβαίνει. Το Aspose.Words σας επιτρέπει να καταχωρήσετε έναν προσαρμοσμένο κανόνα `IFontSubstitutionRule`. Παρακάτω υπάρχει ένα γρήγορο παράδειγμα που αναγκάζει οποιαδήποτε ελλιπής γραμματοσειρά να υποκατασταθεί με `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Πότε θα το χρησιμοποιούσατε;** +Αν δημιουργείτε PDF για μια υπηρεσία web και ξέρετε ότι κάθε πελάτης μπορεί να αποδώσει το `Tahoma`, η επιβολή της εναλλακτικής εξασφαλίζει οπτική συνέπεια χωρίς να χρειάζεται να στείλετε δεκάδες αρχεία γραμματοσειρών. + +## Πλήρες Παράδειγμα Εργασίας (Όλα τα Βήματα Συνδυασμένα) + +Ακολουθεί ολόκληρο το πρόγραμμα που μπορείτε να επικολλήσετε σε ένα νέο έργο κονσόλας. Συγκεντρώνεται ακριβώς όπως είναι, υποθέτοντας ότι έχετε εγκαταστήσει το πακέτο NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Εκτελέστε το πρόγραμμα, παρακολουθήστε την κονσόλα, και θα δείτε κάθε συμβάν ελλιπούσας γραμματοσειράς να εκτυπώνεται. Από εκεί μπορείτε να αποφασίσετε αν θα εγκαταστήσετε τις ελλιπείς γραμματοσειρές, θα τις ενσωματώσετε, ή θα διατηρήσετε την εναλλακτική. + +## Συχνές Ερωτήσεις + +**Ε: Λειτουργεί αυτό με μετατροπή PDF;** +Ναι. Όταν αργότερα καλέσετε `doc.Save("output.pdf")`, οι γραμματοσειρές που αντικαταστάθηκαν κατά τη φόρτωση θα είναι αυτές που θα ενσωματωθούν στο PDF. Έτσι, η έγκαιρη σύλληψη των προειδοποιήσεων σας βοηθά να αποφύγετε απρόσμενες αλλαγές γραμματοσειράς στο τελικό PDF. + +**Ε: Τι γίνεται αν έχω πολλά έγγραφα προς επεξεργασία;** +Τυλίξτε τη λογική φόρτωσης σε ένα μπλοκ try‑catch και επαναχρησιμοποιήστε μια ενιαία παρουσία `FontSettings` για όλα τα έγγραφα. Αυτό μειώνει το κόστος και διατηρεί τον συλλέκτη προειδοποιήσεων ενεργό για κάθε αρχείο. + +**Ε: Μπορώ να καταστέλλω εντελώς τις προειδοποιήσεις;** +Μπορείτε να ορίσετε `loadOptions.WarningCallback = null;` πριν από τη φόρτωση, αλλά θα χάσετε τη δυνατότητα **εντοπισμού ελλιπών γραμματοσειρών** — κάτι που συνήθως δεν θέλετε. + +## Συμπέρασμα + +Καλύψαμε όλα όσα χρειάζεστε για να κυριαρχήσετε στο **aspose font substitution**: ενεργοποίηση του διαγνωστικού συλλέκτη, φόρτωση ενός αρχείου Word με προσαρμοσμένες **ρυθμίσεις γραμματοσειράς**, εξαγωγή της λίστας ελλιπών γραμματοσειρών, και ακόμη αντικατάσταση του προεπιλεγμένου κανόνα αντικατάστασης για **χειρισμό ελλιπών γραμματοσειρών** με τον δικό σας τρόπο. Με λίγες μόνο γραμμές C# αποκτάτε πλήρη ορατότητα σε προβλήματα γραμματοσειρών που διαφορετικά θα κρύβονταν πίσω από λεπτές αλλαγές διάταξης. + +Επόμενα βήματα; Δοκιμάστε να ενσωματώσετε τις αρχικές γραμματοσειρές στο έγγραφο με `FontSettings.SetFontsFolder` ή εξερευνήστε το `FontSourceBase` για φόρτωση γραμματοσειρών από βάση δεδομένων. Μπορείτε επίσης να πειραματιστείτε με τη συλλογή `Document.BuiltInStyle` για να δείτε πώς διαδίδονται οι αλλαγές γραμματοσειράς σε επίπεδο στυλ. + +Έχετε περισσότερες ερωτήσεις σχετικά με το Aspose.Words ή τη διαχείριση γραμματοσειρών; Αφήστε ένα σχόλιο, εξερευνήστε την επίσημη τεκμηρίωση του Aspose, ή ξεκινήστε ένα νέο έργο και πειραματιστείτε με τον παραπάνω κώδικα. Καλή προγραμματιστική, και εύχομαι τα έγγραφά σας να αποδίδουν πάντα ακριβώς όπως προορίζεται! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/basic-conversions/_index.md b/words/hindi/net/basic-conversions/_index.md index 70ed6aec19..ad1b99a12f 100644 --- a/words/hindi/net/basic-conversions/_index.md +++ b/words/hindi/net/basic-conversions/_index.md @@ -21,19 +21,20 @@ ## ट्यूटोरियल | शीर्षक | विवरण | | --- | --- | -| [Docx को Docx में बदलें](./doc-to-docx/) | .NET के लिए Aspose.Words का उपयोग करके DOC को DOCX में बदलने का तरीका जानें। कोड उदाहरणों के साथ चरण-दर-चरण मार्गदर्शिका। डेवलपर्स के लिए बिल्कुल सही। | -| [Docx को Rtf में बदलें](./docx-to-rtf/) | हमारे चरण-दर-चरण गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को RTF में परिवर्तित करना सीखें। सहज दस्तावेज़ प्रसंस्करण के लिए आसान रूपांतरण। | +| [Docx को Docx में बदलें](./doc-to-docx/) | .NET के लिए Aspose.Words का उपयोग करके DOC को DOCX में बदलने का तरीका जानें। कोड उदाहरणों के साथ चरण-दर-स्टेप मार्गदर्शिका। डेवलपर्स के लिए बिल्कुल सही। | +| [Docx को Rtf में बदलें](./docx-to-rtf/) | हमारे चरण-दर-स्टेप गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को RTF में परिवर्तित करना सीखें। सहज दस्तावेज़ प्रसंस्करण के लिए आसान रूपांतरण। | | [वर्ड फ़ाइल को पीडीएफ में बदलें](./docx-to-pdf/) हमारे गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके आसानी से Word फ़ाइलों को PDF में कनवर्ट करना सीखें। त्वरित और विश्वसनीय दस्तावेज़ रूपांतरण चाहने वाले डेवलपर्स के लिए बिल्कुल सही। | -| [Docx को बाइट में बदलें](./docx-to-byte/) | कुशल दस्तावेज़ प्रसंस्करण के लिए Aspose.Words का उपयोग करके .NET में Docx को बाइट सरणी में परिवर्तित करना सीखें। चरण-दर-चरण मार्गदर्शिका शामिल है। | +| [Docx को बाइट में बदलें](./docx-to-byte/) | कुशल दस्तावेज़ प्रसंस्करण के लिए Aspose.Words का उपयोग करके .NET में Docx को बाइट सरणी में परिवर्तित करना सीखें। चरण-दर-स्टेप मार्गदर्शिका शामिल है। | | [Docx को Epub में बदलें](./docx-to-epub/) | .NET के लिए Aspose.Words के साथ आसानी से DOCX को EPUB में बदलें। अपने .NET अनुप्रयोगों में सहज एकीकरण के लिए हमारे ट्यूटोरियल का पालन करें। | -| [Docx को Mhtml में बदलें और ईमेल भेजें](./docx-to-mhtml-and-sending-email/) | इस चरण-दर-चरण मार्गदर्शिका में जानें कि DOCX को MHTML में कैसे बदलें और .NET के लिए Aspose.Words का उपयोग करके ईमेल कैसे भेजें। आसान स्वचालन के साथ अपनी उत्पादकता बढ़ाएँ। | +| [Docx को Mhtml में बदलें और ईमेल भेजें](./docx-to-mhtml-and-sending-email/) | इस चरण-दर-स्टेप मार्गदर्शिका में जानें कि DOCX को MHTML में कैसे बदलें और .NET के लिए Aspose.Words का उपयोग करके ईमेल कैसे भेजें। आसान स्वचालन के साथ अपनी उत्पादकता बढ़ाएँ। | | [Docx फ़ाइल को Markdown में बदलें](./docx-to-markdown/) | .NET के लिए Aspose.Words का उपयोग करके DOCX फ़ाइलों को Markdown में परिवर्तित करना सीखें। अपने .NET अनुप्रयोगों में सहज एकीकरण के लिए हमारी विस्तृत मार्गदर्शिका का पालन करें। | -| [Docx को Txt में बदलें](./docx-to-txt/) हमारे चरण-दर-चरण गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को TXT में बदलें। दस्तावेज़ों को कुशलतापूर्वक और आसानी से बदलना सीखें। | +| [Docx को Txt में बदलें](./docx-to-txt/) हमारे चरण-दर-स्टेप गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके DOCX को TXT में बदलें। दस्तावेज़ों को कुशलतापूर्वक और आसानी से बदलना सीखें। | | [टेक्स्ट फ़ाइल को वर्ड डॉक्यूमेंट में बदलें](./txt-to-docx/) | .NET के लिए Aspose.Words का उपयोग करके टेक्स्ट फ़ाइलों को Word दस्तावेज़ों में परिवर्तित करना सीखें। हमारे व्यापक गाइड के साथ दस्तावेज़ रूपांतरणों को कुशलतापूर्वक प्रबंधित करें। | | [पीडीएफ को जेपीईजी के रूप में सहेजें](./pdf-to-jpeg/) | .NET के लिए Aspose.Words का उपयोग करके PDF को JPEG में आसानी से बदलें। उदाहरणों और FAQ के साथ हमारी विस्तृत मार्गदर्शिका का पालन करें। डेवलपर्स और उत्साही लोगों के लिए बिल्कुल सही। | | [पीडीएफ को वर्ड फॉर्मेट में सहेजें (Docx)](./pdf-to-docx/) | इस विस्तृत, चरण-दर-चरण मार्गदर्शिका में जानें कि .NET के लिए Aspose.Words का उपयोग करके PDF को Word दस्तावेज़ (Docx) में कैसे परिवर्तित किया जाए। डेवलपर्स के लिए बिल्कुल सही। | | [Word से LaTeX निर्यात कैसे करें – चरण‑दर‑चरण मार्गदर्शिका](./how-to-export-latex-from-word-step-by-step-guide/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ से LaTeX फ़ॉर्मेट में निर्यात करने का चरण‑दर‑चरण मार्गदर्शन। | | [C# में Aspose.Words का उपयोग करके वर्ड को PDF में बदलें – गाइड](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | C# में Aspose.Words से Word फ़ाइल को PDF में बदलने की चरण‑दर‑स्टेप गाइड। | +| [C# में Word को PDF में बदलें – Aspose.Words के साथ पूर्ण गाइड](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Aspose.Words के साथ C# में Word फ़ाइल को PDF में बदलने की पूरी मार्गदर्शिका। | | [Aspose.Words के साथ Word को PDF के रूप में सहेजें – पूर्ण C# गाइड](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words का उपयोग करके C# में Word फ़ाइल को PDF में सहेजने की पूरी गाइड। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/hindi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..a00a44a1e2 --- /dev/null +++ b/words/hindi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,194 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words का उपयोग करके C# में Word को PDF में बदलें। जानें कि docx + को PDF के रूप में कैसे सहेजें, सुलभ PDF कैसे निर्यात करें, और Word दस्तावेज़ को + कुशलता से कैसे लोड करें। +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: hi +og_description: C# में Word को PDF में बदलें, चरण‑दर‑चरण मार्गदर्शिका के साथ। जानिए + कैसे docx को PDF के रूप में सहेजें, सुलभ PDF निर्यात करें, और Aspose.Words का उपयोग + करके Word दस्तावेज़ लोड करें। +og_title: C# में Word को PDF में बदलें – पूर्ण Aspose.Words ट्यूटोरियल +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: C# में Word को PDF में बदलें – Aspose.Words के साथ पूर्ण गाइड +url: /hi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में Word को PDF में बदलें – पूर्ण प्रोग्रामिंग ट्यूटोरियल + +क्या आपने कभी सोचा है कि **वर्ड को PDF में बदलें** बिना झंझट वाले कमांड‑लाइन टूल्स या थर्ड‑पार्टी सर्विसेज़ के कैसे किया जाए? आप अकेले नहीं हैं। कई डेवलपर्स इस समस्या का सामना करते हैं जब क्लाइंट DOCX फ़ाइल से सीधे एक एक्सेसिबल PDF चाहता है। अच्छी खबर? कुछ ही C# लाइनों और शक्तिशाली Aspose.Words लाइब्रेरी के साथ, आप Word दस्तावेज़ को मानक‑अनुरूप PDF में तुरंत बदल सकते हैं। + +इस गाइड में हम आपको वह सब कुछ बताएँगे जो आपको जानना आवश्यक है: **load word document** की बुनियादों से लेकर सही विकल्पों को कॉन्फ़िगर करने तक **how to export accessible pdf**, और अंत में परिणाम को सहेजना ताकि आप **save docx as pdf** भरोसेमंद तरीके से कर सकें। अंत तक आपके पास एक तैयार‑चलाने‑योग्य स्निपेट होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +> **Pro tip:** यदि आप PDF/UA‑2 कंप्लायंस (वह एक्सेसिबिलिटी मानक जो कई सरकारी एजेंसियां मांगती हैं) को लक्ष्य बना रहे हैं, तो वही कोड बिना किसी अतिरिक्त कदम के काम करता है—सिर्फ सही `PdfCompliance` फ़्लैग सेट करें। + +## आप क्या सीखेंगे + +- Aspose.Words का उपयोग करके C# में **load word document** कैसे करें। +- **how to export accessible pdf** (PDF/UA‑2) के लिए आवश्यक सटीक सेटिंग्स। +- एक पूर्ण, चलाने योग्य उदाहरण जो एक मेथड कॉल से **save docx as pdf** करता है। +- जब आप **c# convert docx pdf** करते हैं तो सामान्य समस्याएँ और उन्हें कैसे टालें। +- जनरेटेड PDF की एक्सेसिबिलिटी अपेक्षाओं को पूरा करने की त्वरित जाँच के तरीके। + +कोई बाहरी टूल नहीं, कोई अस्पष्ट कॉन्फ़िगरेशन फ़ाइल नहीं—बस शुद्ध C# कोड जिसे आप आज ही कंपाइल कर सकते हैं। + +## पूर्वापेक्षाएँ + +1. **.NET 6.0** (या कोई भी नवीनतम .NET संस्करण) स्थापित होना चाहिए। पुराने फ्रेमवर्क भी काम करेंगे, लेकिन नीचे दिया गया सिंटैक्स आधुनिक SDK मानता है। +2. Aspose.Words for .NET के लिए एक **license**। लाइब्रेरी एक मुफ्त ट्रायल देती है, लेकिन प्रोडक्शन के लिए आपको एक वैध कुंजी चाहिए। +3. **Aspose.Words** NuGet पैकेज को अपने प्रोजेक्ट में जोड़ें: + +```bash +dotnet add package Aspose.Words +``` + +बस इतना ही—कोई अतिरिक्त बाइनरी नहीं, कोई COM इंटरऑप नहीं, सिर्फ एक साफ़ NuGet रेफ़रेंस। + +![Aspose.Words का उपयोग करके C# में वर्ड को PDF में बदलें](image-placeholder.png "Aspose.Words का उपयोग करके C# में वर्ड को PDF में बदलें") + +## चरण‑दर‑चरण कार्यान्वयन + +नीचे हम प्रक्रिया को तार्किक भागों में विभाजित करते हैं। प्रत्येक चरण में एक छोटा कोड स्निपेट, **क्यों** यह महत्वपूर्ण है की व्याख्या, और वास्तविक उपयोग से प्राप्त एक टिप शामिल है। + +### ## Word को PDF में बदलें – स्रोत दस्तावेज़ लोड करें + +पहला काम जो आपको करना है वह है **load word document** को मेमोरी में लोड करना। Aspose.Words OpenXML पार्सिंग को एब्स्ट्रैक्ट कर देता है, इसलिए आप DOCX, DOC, या यहाँ तक कि RTF फ़ाइलों के साथ बिना फ़ॉर्मेट की जटिलताओं की चिंता किए काम कर सकते हैं। + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**यह क्यों महत्वपूर्ण है:** +फ़ाइल को लोड करने से एक `Document` ऑब्जेक्ट बनता है जो पूरे Word फ़ाइल को दर्शाता है, जिसमें हेडर, फुटर, स्टाइल और छिपा मेटाडेटा शामिल है। यदि आप इस चरण को छोड़ देते हैं या फ़ाइल को कच्ची स्ट्रीम के रूप में पढ़ने की कोशिश करते हैं, तो आप लेआउट जानकारी खो देंगे जो बाद में PDF के दिखने को निर्धारित करती है। + +> **Side note:** वही `Document` कंस्ट्रक्टर `.doc` और `.rtf` के लिए भी काम करता है। इसका मतलब है कि आप **c# convert docx pdf** कर सकते हैं भले ही स्रोत फ़ाइल सख्ती से DOCX न हो। + +### ## DOCX को PDF के रूप में सहेजें – PDF/UA‑2 कंप्लायंस कॉन्फ़िगर करें + +अब जब दस्तावेज़ मेमोरी में है, हम Aspose.Words को बताते हैं कि हम PDF कैसे बनाना चाहते हैं। अधिकांश उपयोग‑केसों के लिए डिफ़ॉल्ट सेटिंग्स ठीक हैं, लेकिन जब आपको **accessible PDF** चाहिए तो आपको PDF/UA‑2 कंप्लायंस फ़्लैग को सक्षम करना होगा। + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**यह क्यों महत्वपूर्ण है:** +`PdfCompliance.PdfUAXmpA2` लाइब्रेरी को आवश्यक टैग और संरचनाएँ एम्बेड करने के लिए बताता है जिन पर स्क्रीन रीडर निर्भर करते हैं। इस फ़्लैग के बिना, आपको एक सुंदर दिखने वाला PDF मिल सकता है जो एक्सेसिबिलिटी ऑडिट में फेल हो जाता है। + +> **Tip:** यदि आपको केवल सामान्य PDF चाहिए, तो आप `Compliance` लाइन को हटा सकते हैं। बाकी विकल्प अभी भी आपको उच्च‑गुणवत्ता वाला आउटपुट देंगे। + +### ## Word को PDF में बदलें – फ़ाइल लिखें + +विकल्प तैयार होने के बाद, अंतिम चरण **save docx as pdf** करना है। यह एकल कॉल सभी भारी काम करता है: लेआउट रूपांतरण, फ़ॉन्ट एम्बेडिंग, और एक्सेसिबिलिटी टैगिंग। + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**आपको क्या मिलेगा:** +- `outputPath` पर एक PDF फ़ाइल जो Word लेआउट को प्रतिबिंबित करती है। +- यदि आपने `PdfUAXmpA2` फ़्लैग इस्तेमाल किया है, तो PDF को PDF/UA‑2 कंप्लायंट के रूप में चिह्नित किया जाएगा। +- सभी फ़ॉन्ट एम्बेडेड हैं, इसलिए फ़ाइल किसी भी मशीन पर समान दिखेगी। + +### ## एक्सेसिबल PDF की जाँच करें (वैकल्पिक लेकिन अनुशंसित) + +रूपांतरण के बाद, यह सुनिश्चित करने के लिए दोबारा जाँच करना अच्छा विचार है कि PDF वास्तव में **how to export accessible pdf** सही तरीके से है। आप मुफ्त टूल जैसे Adobe Acrobat Reader का “Accessibility Check” या ओपन‑सोर्स `pdfcpu` वैलिडेटर का उपयोग कर सकते हैं। + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +यदि वैलिडेटर कोई त्रुटि नहीं रिपोर्ट करता, तो आपने पूर्ण एक्सेसिबिलिटी समर्थन के साथ सफलतापूर्वक **convert word to pdf** किया है। + +### ## जब आप C# में DOCX को PDF में बदलते हैं तो आम समस्याएँ + +| समस्या | यह क्यों होता है | समाधान | +|-------|----------------|-----| +| Missing fonts | स्रोत DOCX में एक कस्टम फ़ॉन्ट है जो सर्वर पर स्थापित नहीं है। | `EmbedFullFonts = true` सेट करें या मशीन पर फ़ॉन्ट इंस्टॉल करें। | +| Large file size | इमेजेज़ पूर्ण रेज़ोल्यूशन पर एम्बेड की गई हैं। | `ImageCompression = PdfImageCompression.Jpeg` उपयोग करें और `JpegQuality` को कम मान पर सेट करें। | +| Broken hyperlinks | लिंक रिलेटिव पाथ की ओर इशारा कर रहे हैं जो क्लाइंट पर मौजूद नहीं हैं। | सुनिश्चित करें कि URLs एब्सोल्यूट हैं या `HyperlinkTarget` प्रॉपर्टी को समायोजित करें। | +| Accessibility tags missing | `Compliance` फ़्लैग सेट नहीं है। | ऊपर दिखाए अनुसार `Compliance = PdfCompliance.PdfUAXmpA2` जोड़ें। | + +इन बातों को ध्यान में रखकर आप अपनी **c# convert docx pdf** प्रक्रिया को मजबूत और प्रोडक्शन‑रेडी बना सकते हैं। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ मिलाकर, यहाँ एक स्व-निहित कंसोल ऐप है जिसे आप अभी कंपाइल और रन कर सकते हैं। + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**अपेक्षित परिणाम:** प्रोग्राम चलाने के बाद, आपको `C:\Docs` में `output.pdf` मिलेगा। इसे किसी भी PDF व्यूअर में खोलें; लेआउट `input.docx` के पिक्सेल‑दर‑पिक्सेल मेल खाएगा, और एक एक्सेसिबिलिटी चेक PDF/UA‑2 कंप्लायंस की पुष्टि करेगा। + +## निष्कर्ष + +हमने अभी C# और Aspose.Words का उपयोग करके **convert word to pdf** करने के लिए एक पूर्ण, अंत‑से‑अंत समाधान पर चर्चा की। **load word document**, सही `PdfSaveOptions` को कॉन्फ़िगर करके, और अंत में **save docx as pdf** करके, आप न्यूनतम कोड के साथ उच्च‑गुणवत्ता, एक्सेसिबल PDF प्राप्त करते हैं। चाहे आप एक दस्तावेज़‑जनरेशन माइक्रोसर्विस बना रहे हों, या ऑन‑प्रेमिस बैच कन्वर्टर, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-markdownsaveoptions/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/_index.md index a4246ab390..ed11b2a29e 100644 --- a/words/hindi/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hindi/net/programming-with-markdownsaveoptions/_index.md @@ -32,6 +32,8 @@ MarkdownSaveOptions के साथ वर्ड प्रोसेसिंग | [Word से Markdown निर्यात कैसे करें – पूर्ण C# गाइड](./how-to-export-markdown-from-word-complete-c-guide/) | Word दस्तावेज़ को Markdown में निर्यात करने की पूरी C# गाइड | | [DOCX को मार्कडाउन में बदलें – चरण‑दर‑चरण गाइड](./how-to-save-markdown-from-docx-step-by-step-guide/) | DOCX फ़ाइल को मार्कडाउन में बदलने की चरण‑दर‑चरण प्रक्रिया सीखें। | | [DOCX से Markdown निर्यात कैसे करें – पूरी गाइड](./how-to-export-markdown-from-docx-complete-guide/) | DOCX फ़ाइल को Markdown में निर्यात करने की विस्तृत चरण‑दर‑चरण गाइड। | +| [DOCX को Markdown में बदलें – Aspose.Words के साथ DOCX से छवियों को निकालें](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | .NET के लिए Aspose.Words का उपयोग करके DOCX फ़ाइल से छवियों को निकालते हुए उसे Markdown में बदलना सीखें। | +| [Word को Markdown में बदलें – PDF/UA निर्यात के साथ पूर्ण गाइड](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Word फ़ाइलों को PDF/UA के साथ निर्यात करते हुए Markdown में बदलने की पूरी गाइड। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..d1dbf7c3f6 --- /dev/null +++ b/words/hindi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: C# में DOCX को Markdown में बदलना और DOCX से इमेज निकालना सीखें। पूर्ण + कोड और टिप्स के साथ चरण‑दर‑चरण गाइड। +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: hi +og_description: Aspose.Words का उपयोग करके DOCX को Markdown में बदलें और DOCX से इमेज + निकालें। कोड, व्याख्या और सर्वोत्तम‑प्रैक्टिस टिप्स के साथ पूर्ण C# ट्यूटोरियल। +og_title: DOCX को Markdown में बदलें – C# में DOCX से इमेज निकालें +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX को Markdown में बदलें – Aspose.Words के साथ DOCX से छवियों को निकालें +url: /hi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX को Markdown में बदलें – C# में DOCX से इमेज निकालें + +क्या आपको **DOCX को Markdown में बदलने** की ज़रूरत रही है लेकिन आउटपुट में इमेज गायब हो गईं? आप अकेले नहीं हैं। कई प्रोजेक्ट्स में Markdown संस्करण वर्ज़न‑कंट्रोल या स्टैटिक‑साइट जेनरेटर्स के लिए परफ़ेक्ट होता है, फिर भी चित्र पीछे छूट जाते हैं, जिससे एक रिच डॉक्यूमेंट एक बंजर टेक्स्ट फ़ाइल में बदल जाता है। + +अच्छी ख़बर? कुछ ही लाइनों के C# और Aspose.Words के साथ आप **DOCX को Markdown में बदल** *और* **DOCX से इमेज निकाल** सकते हैं। यह गाइड आपको पूरी प्रक्रिया से गुज़राएगा, बताएगा कि हर भाग क्यों महत्वपूर्ण है, और यहाँ तक कि दिखाएगा कि कैसे अपने इमेज फ़ोल्डर को व्यवस्थित रखें। + +## आप क्या सीखेंगे + +- कैसे वह DOCX लोड करें जिसमें चित्र हों। +- कैसे एक कस्टम `IResourceSavingCallback` परिभाषित करें जो तय करे प्रत्येक इमेज कहाँ सेव होगी। +- कैसे `MarkdownSaveOptions` को कॉन्फ़िगर करें ताकि जेनरेटेड Markdown सही तरीके से एक्सट्रैक्टेड इमेज को रेफ़र करे। +- डुप्लिकेट इमेज नाम या non‑PNG फ़ॉर्मेट जैसी एज केस को हैंडल करने के टिप्स। +- एक पूरा, कॉपी‑एंड‑पेस्ट‑रेडी कोड सैंपल जिसे आप आज ही चला सकते हैं। + +### पूर्वापेक्षाएँ + +- .NET 6.0 या बाद का (API .NET Core, .NET Framework, और .NET 5+ पर काम करता है)। +- **Aspose.Words for .NET** का लाइसेंस (टेस्टिंग के लिए फ्री ट्रायल चलती है)। +- C# और Visual Studio (या आपका पसंदीदा IDE) की बेसिक समझ। + +अगर आपके पास ये हैं, तो चलिए शुरू करते हैं। + +--- + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose.Words इंस्टॉल करें + +सबसे पहले, एक नया कंसोल ऐप बनाएं (या मौजूदा सॉल्यूशन में इंटीग्रेट करें)। + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **प्रो टिप:** नवीनतम NuGet संस्करण (अप्रैल 2026 तक यह 24.12 है) का उपयोग करें ताकि नवीनतम Markdown एक्सपोर्ट सुधार मिलें। + +--- + +## चरण 2: इमेज को जहाँ चाहें सेव करने के लिए एक कॉलबैक बनाएं + +Aspose.Words आपको Markdown एक्सपोर्ट के दौरान लिखी जाने वाली हर रिसोर्स (इमेज, SVG आदि) को इंटरसेप्ट करने देता है। `IResourceSavingCallback` को इम्प्लीमेंट करके आप कर सकते हैं: + +1. वह फ़ोल्डर चुनें जो आपके Markdown फ़ाइल के बगल में रहे। +2. एक यूनिक फ़ाइलनाम जेनरेट करें (ताकि आप कभी मौजूदा इमेज को ओवरराइट न करें)। +3. फ़ॉर्मेट तय करें (यहाँ हम कंसिस्टेंसी के लिए PNG फोर्स करते हैं)। + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### GUID‑आधारित नाम क्यों? + +अगर स्रोत DOCX में दो चित्रों के मूल नाम एक जैसे हों, तो साधारण कॉपी‑पेस्ट एक को ओवरराइट कर देगा। `Guid.NewGuid()` का उपयोग यूनिकनेस गारंटी देता है, जो विशेष रूप से तब उपयोगी है जब आप कई बार ऑटोमेटेड पाइपलाइन में कन्वर्ज़न चलाते हैं। + +--- + +## चरण 3: DOCX लोड करें और Markdown ऑप्शन्स सेट करें + +अब हम डॉक्यूमेंट को मेमोरी में लाते हैं और पहले बनाए हुए कॉलबैक को अटैच करते हैं। + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### कोड क्या करता है, स्टेप बाय स्टेप + +| चरण | उद्देश्य | +|------|----------| +| **पाथ्स परिभाषित करें** | आपके प्रोजेक्ट को लचीला रखता है; आप बिना री‑कम्पाइल किए किसी भी फ़ोल्डर की ओर पॉइंट कर सकते हैं। | +| **DOCX लोड करें** | `Document` Word फ़ाइल को पार्स करता है, जिससे सभी एलिमेंट्स (पैराग्राफ, टेबल, चित्र) एक्सेसिबल हो जाते हैं। | +| **`MarkdownSaveOptions` कॉन्फ़िगर करें** | `ResourceSavingCallback` वह हुक है जो इमेज एक्सट्रैक्ट करता है। इसके बिना, Aspose.Words सेटिंग्स के आधार पर इमेज को base64 स्ट्रिंग के रूप में एम्बेड कर देगा या पूरी तरह ड्रॉप कर देगा। | +| **सेव करें** | `doc.Save` Markdown फ़ाइल लिखता है और प्रत्येक इमेज के लिए कॉलबैक ट्रिगर करता है। | + +--- + +## चरण 4: आउटपुट वेरिफ़ाई करें – आपको क्या दिखना चाहिए? + +प्रोग्राम चलाने के बाद, `DocWithImages.md` खोलें। आपको Markdown इमेज लिंक इस तरह दिखेंगे: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +और `C:\Docs\MarkdownResources` में आपको GUID नामों वाली PNG फ़ाइलों की एक श्रृंखला मिलेगी। किसी भी फ़ाइल को खोलें – वह मूल DOCX में एम्बेडेड चित्रों के समान ही होनी चाहिए। + +अगर आप Markdown फ़ाइल को ऐसे व्यूअर में खोलते हैं जो रिलेटिव पाथ सपोर्ट करता है (जैसे VS Code प्रीव्यू, GitHub, या कोई स्टैटिक‑साइट जेनरेटर), तो इमेज वहीँ रेंडर होंगी जहाँ Word में थीं। + +### सामान्य समस्याएँ और उनके समाधान + +| लक्षण | संभावित कारण | समाधान | +|-------|--------------|--------| +| इमेज टूटे हुए लिंक दिखा रहे हैं | `ResourceFileName` सेट नहीं किया गया, इसलिए Markdown गैर‑मौजूद फ़ाइल की ओर इशारा कर रहा है। | कॉलबैक के अंदर `args.ResourceFileName = newFileName;` सुनिश्चित करें। | +| PNG फ़ाइलें बहुत बड़ी हैं | मूल इमेज JPEG या BMP थी; PNG में बदलने से साइज बढ़ सकता है। | `args.ResourceContentType` से मूल फ़ॉर्मेट पता करें और उसे बनाए रखें: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| डुप्लिकेट इमेज अभी भी मौजूद हैं | आपने स्थिर फ़ाइलनाम के बजाय GUID नहीं इस्तेमाल किया। | GUID लॉजिक पर वापस आएँ या प्रति इमेज टाइप काउंटर जोड़ें। | +| कन्वर्ज़न `FileNotFoundException` फेंक रहा है | स्रोत DOCX पाथ गलत है या फ़ोल्डर में रीड परमिशन नहीं है। | पाथ चेक करें और उचित फ़ाइल‑सिस्टम अधिकार दें। | + +--- + +## चरण 5: एडवांस्ड ट्यूनिंग (वैकल्पिक) + +### 5.1 मूल इमेज फ़ॉर्मेट को बनाए रखें + +अगर आप चाहते हैं कि आउटपुट इमेज अपनी मूल एक्सटेंशन रखें, तो कॉलबैक को इस तरह बदलें: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 इमेज को Base64 के रूप में एम्बेड करें (जब आप अलग फ़ाइल नहीं चाहते) + +कभी‑कभी एक‑सिंगल‑फ़ाइल Markdown ज़्यादा सुविधाजनक होता है (जैसे ई‑मेल में भेजना)। विकल्प बदलें: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +लेकिन याद रखें: अधिकांश स्टैटिक‑साइट वर्कफ़्लो के लिए **DOCX से इमेज निकालना** प्राथमिक लक्ष्य है, इसलिए फ़ोल्डर अप्रोच आमतौर पर बेहतर विकल्प है। + +--- + +## पूरा कार्यशील उदाहरण (कॉपी‑एंड‑पेस्ट रेडी) + +नीचे पूरा प्रोग्राम एक फ़ाइल में दिया गया है। सिर्फ पाथ्स को अपने अनुसार बदलें और रन करें। + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +`dotnet run` के साथ चलाएँ। जब कंसोल ✅ लाइन प्रिंट करे, तो Markdown फ़ाइल खोलें और आपको इमेज सही तरीके से रेंडर होते दिखेंगे। + +--- + +## निष्कर्ष + +अब आपके पास **एक पूर्ण, प्रोडक्शन‑रेडी समाधान** है जो Aspose.Words के साथ C# में DOCX को Markdown में बदलता है और इमेज को एक्सट्रैक्ट करता है। मुख्य कीवर्ड गाइड में बार‑बार आया है, जिससे सर्च इंजन और AI असिस्टेंट दोनों के लिए रिलेवेंस बढ़ता है। + +एक ही पास में कोड: + +1. Word डॉक्यूमेंट लोड करता है। +2. `IResourceSavingCallback` के ज़रिए हर इमेज को इंटरसेप्ट करता है। +3. प्रत्येक इमेज को एक प्रेडिक्टेबल फ़ोल्डर में यूनिक नाम के साथ सेव करता है। +4. ऐसा Markdown जेनरेट करता है जो उन इमेज को रेफ़र करता है। + +अब आप आगे कर सकते हैं: + +- प्लग + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/hindi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..a690603099 --- /dev/null +++ b/words/hindi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Word को जल्दी से Markdown में बदलें और C# में PDF/UA के रूप में सहेजना + भी सीखें। चरण‑दर‑चरण कोड, टिप्स और किनारे के मामलों का समाधान। +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: hi +og_description: Aspose.Words के साथ Word को Markdown में बदलें और PDF/UA के रूप में + सहेजें। एक संक्षिप्त गाइड में कारण, प्रक्रिया और सर्वोत्तम अभ्यास टिप्स जानें। +og_title: वर्ड को मार्कडाउन में बदलें – पूर्ण C# ट्यूटोरियल +tags: +- Aspose.Words +- C# +- Document Conversion +title: वर्ड को मार्कडाउन में बदलें – PDF/UA निर्यात के साथ पूर्ण गाइड +url: /hi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word को Markdown में बदलें – PDF/UA एक्सपोर्ट के साथ पूर्ण गाइड + +क्या आपने कभी सोचा है कि **Word को Markdown में बदलें** बिना समीकरणों या छवियों को खोए? आप अकेले नहीं हैं। कई डेवलपर्स को `.docx` फ़ाइलों को साफ़ Markdown में बदलने का भरोसेमंद तरीका चाहिए, साथ ही **PDF/UA** के रूप में सहेजने की क्षमता चाहिए ताकि एक्सेसिबिलिटी‑कम्प्लायंट PDFs बन सकें। इस ट्यूटोरियल में हम Aspose.Words for .NET का उपयोग करके एक पूर्ण, तैयार‑चलाने‑योग्य समाधान दिखाएंगे, प्रत्येक सेटिंग क्यों महत्वपूर्ण है समझाएंगे, और OfficeMath तथा फ्लोटिंग शेप्स जैसे कठिन हिस्सों को कैसे संभालें दिखाएंगे। + +इस गाइड के अंत तक आपके पास एक एकल C# प्रोग्राम होगा जो: + +1. रिलीक्स्ड रिकवरी के साथ Word दस्तावेज़ लोड करता है (ताकि करप्ट फ़ाइलें रन को तोड़ न सकें)। +2. इसे Markdown में एक्सपोर्ट करता है, समीकरणों को LaTeX में बदलता है और इमेजेज़ को एक कस्टम कॉलबैक के माध्यम से स्टोर करता है। +3. वही दस्तावेज़ PDF/UA‑2 कम्प्लायंट फ़ाइल के रूप में सहेजता है, फ्लोटिंग शेप्स को इनलाइन टैग्स के रूप में एम्बेड करता है। + +बहुत कुछ लग रहा है? चिंता न करें—चलिए शुरू करते हैं। + +## आपको क्या चाहिए + +- **Aspose.Words for .NET** (लेखन के समय नवीनतम संस्करण, 23.x)। +- एक .NET विकास वातावरण (Visual Studio 2022, Rider, या `dotnet` CLI)। +- एक सैंपल Word फ़ाइल (`input.docx`) जिसे आप किसी फ़ोल्डर में रख सकें। +- C# सिंटैक्स की बुनियादी समझ—कोई जटिल चीज़ नहीं, बस कुछ `using` स्टेटमेंट्स। + +> **Pro tip:** यदि आप NuGet पैकेज मैनेजर का उपयोग कर रहे हैं, तो लाइब्रेरी जोड़ें +> `dotnet add package Aspose.Words` या Visual Studio NuGet UI के माध्यम से। + +## Step 1 – रिलीक्स्ड रिकवरी के साथ Word दस्तावेज़ लोड करें + +जब आप बाहरी स्रोतों से Word फ़ाइलें प्राप्त करते हैं तो उनमें मामूली करप्शन हो सकता है। **Relaxed** रिकवरी को सक्षम करने से Aspose.Words को एक्सेप्शन फेंके बिना आगे बढ़ने का निर्देश मिलता है। + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**यह क्यों महत्वपूर्ण है:** +- `RecoveryMode.Relaxed` एक ही खराब पैराग्राफ़ के कारण पूरी कन्वर्ज़न को रोकने से बचाता है। +- `FontSettings` ऑब्जेक्ट प्रदान करने से कोई भी गायब फ़ॉन्ट ग्रेसफ़ुली प्रतिस्थापित हो जाता है, जो बाद में समीकरणों को LaTeX में रेंडर करने के लिए आवश्यक है। + +## Step 2 – Markdown में एक्सपोर्ट करें (OfficeMath → LaTeX, इमेजेज़ कॉलबैक के माध्यम से) + +Markdown में Word समीकरणों को दर्शाने का मूल तरीका नहीं है। Aspose.Words **OfficeMath** ऑब्जेक्ट्स को LaTeX में ट्रांसलेट कर सकता है, जिसे अधिकांश Markdown रेंडरर्स समझते हैं। इमेजेज़ को कहीं सेव करना पड़ता है; एक कस्टम **resource‑saving callback** आपको फ़ोल्डर संरचना और नामकरण पर पूर्ण नियंत्रण देता है। + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### रिसोर्स‑सेविंग कॉलबैक + +नीचे एक छोटा इम्प्लीमेंटेशन है जो हर इमेज को `images` नामक सब‑फ़ोल्डर में स्टोर करता है और फ़ाइलों को `img001.png`, `img002.png` आदि नाम देता है। + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**आपको यह क्यों चाहिए:** +- कॉलबैक न होने पर Aspose.Words एक फ्लैट फ़ोल्डर बनाता है जिसमें रैंडम GUID नाम होते हैं, जिससे वर्ज़न कंट्रोल गड़बड़ हो जाता है। +- नामकरण योजना को नियंत्रित करके आप Markdown रिपॉज़िटरी को साफ़ और पुनरुत्पादक रख सकते हैं। + +### अपेक्षित Markdown आउटपुट + +रन के बाद `doc.md` खोलें और आपको यह दिखेगा: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +समीकरण `$$ … $$` में लिपटे LaTeX के रूप में दिखेंगे, और इमेजेज़ `images` फ़ोल्डर को रेफ़र करेंगे जो आपने अभी बनाया है। + +## Step 3 – PDF/UA‑2 (एक्सेसिबिलिटी‑रेडी) में एक्सपोर्ट करें + +यदि आपको दस्तावेज़ उन उपयोगकर्ताओं के साथ साझा करना है जो स्क्रीन रीडर्स या अन्य सहायक तकनीकों पर निर्भर हैं, तो **PDF/UA‑2** कम्प्लायंस गोल्ड स्टैंडर्ड है। Aspose.Words इसे एक ही फ़्लैग से लागू कर सकता है, और यह फ्लोटिंग शेप्स को इनलाइन टैग्स में फ्लैटन भी कर सकता है ताकि कन्वर्ज़न के दौरान वे न खोएँ। + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**PDF/UA क्यों महत्वपूर्ण है:** +- PDF/UA (Universal Accessibility) सुनिश्चित करता है कि उत्पन्न PDF में सही टैगिंग, लॉजिकल रीडिंग ऑर्डर, और इमेजेज़ के लिए वैकल्पिक टेक्स्ट हो। +- `ExportFloatingShapesAsInlineTag` सेट करने से टेक्स्ट बॉक्स या कॉलआउट जैसी शेप्स को छोड़ने या गलत जगह रखने से बचा जा सकता है—जटिल लेआउट्स को कन्वर्ट करते समय यह आम समस्या है। + +### PDF/UA कम्प्लायंस की जाँच + +एक्सपोर्ट के बाद PDF को Adobe Acrobat Pro में खोलें और **“Accessibility Check”** चलाएँ (Tools → Accessibility → Full Check)। यदि टूल **0 errors** रिपोर्ट करता है, तो आप सफल हैं। + +## Edge Cases & Common Pitfalls + +| स्थिति | क्या देखना है | समाधान / सिफ़ारिश | +|--------|--------------|-------------------| +| Word फ़ाइल में **unsupported fonts** हैं | फ़ॉन्ट्स प्रतिस्थापित हो सकते हैं, जिससे समीकरण लेआउट टूट सकता है | फ़ॉलबैक फ़ॉन्ट्स के साथ एक कस्टम `FontSettings` प्रदान करें | +| बड़े दस्तावेज़ (> 100 MB) | कन्वर्ज़न के दौरान मेमोरी प्रेशर | `LoadOptions` के साथ `LoadFormat.Docx` उपयोग करें और फ़ाइल को स्ट्रीम करें | +| इमेजेज़ **EMF/WMF** वेक्टर ग्राफ़िक्स हैं | वे अनजाने में रास्टराइज़ हो सकते हैं | सेव करने से पहले `ImageSaveOptions` के माध्यम से PNG में बदलें | +| PDF/UA **nested tables** पर वैलिडेशन फेल हो रहा है | टैगिंग अस्पष्ट हो सकती है | इंजन को मदद करने के लिए `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` सक्षम करें | +| **custom styles** को संरक्षित करना है | Markdown में स्टाइलिंग सीमित है | Markdown के साथ एक CSS फ़ाइल एक्सपोर्ट करें और उसे रेफ़रेंस करें | + +## Full Working Example (All Code Together) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +प्रोग्राम चलाएँ, और आपको `doc.md` (LaTeX समीकरणों और साफ़ इमेज लिंक के साथ) तथा `doc.pdf` (पूरी तरह PDF/UA‑2 कम्प्लायंट) `YOUR_DIRECTORY` में मिलेंगे। + +## Visual Overview + +![Word को Markdown में बदलने का उदाहरण](https://example.com/placeholder.png "Word को Markdown में बदलने का उदाहरण – इनपुट Word, Markdown आउटपुट, और PDF/UA फ़ाइल दिखाता है") + +*Alt text:* **Word को Markdown में बदलने का उदाहरण** – एक Word फ़ाइल से Markdown और PDF/UA तक के कन्वर्ज़न पाइपलाइन का डायग्राम। + +## Recap & Next Steps + +हमने अभी **Word को Markdown में बदल दिया** जबकि समीकरणों को बरकरार रखा, इमेजेज़ को एक साफ़ फ़ोल्डर में स्टोर किया, और एक **save as PDF/UA** फ़ाइल बनाई जो एक्सेसिबिलिटी चेक पास करती है। मुख्य बिंदु हैं: + +- `LoadOptions.RecoveryMode.Relaxed` का उपयोग करके अधूरे Word फ़ाइलों को सहन करें। +- साफ़ समीकरण रेंडरिंग के लिए `OfficeMathExportMode` को `LaTeX` सेट करें। +- इमेज आउटपुट को नियंत्रित करने के लिए `ResourceSavingCallback` लागू करें। +- मानक‑कम्प्लायंट PDF के लिए `PdfCompliance.PdfUAXmpA2` और `ExportFloatingShapesAsInlineTag` सक्षम करें। + +### आगे क्या एक्सप्लोर करें? + +- **Custom CSS for Markdown** – एक स्टाइलशीट जनरेट करें जो आपके Word स्टाइल्स को प्रतिबिंबित करे। +- **Batch processing** – `.docx` फ़ाइलों की डायरेक्टरी पर लूप चलाकर बड़े माइग्रेशन को ऑटोमेट करें। +- **Advanced PDF/UA features** – कस्टम टैग्स जोड़ें, भाषा एट्रिब्यूट सेट करें, या ऑडियो डिस्क्रिप्शन एम्बेड करें। +- **Integration with CI/CD** – सुनिश्चित करें कि हर बिल्ड स्वचालित रूप से एक्सेसिबल PDFs उत्पन्न करे। + +यदि आप किसी समस्या में फँसते हैं, तो दोबारा जांचें कि आपका Aspose.Words संस्करण यहाँ उपयोग किए गए API से मेल खाता है, और याद रखें कि लाइब्रेरी की अपनी डॉक्यूमेंटेशन एक मजबूत द्वितीयक संदर्भ है। + +Happy coding, and may your documents stay both beautiful **and** accessible! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/programming-with-txtsaveoptions/_index.md b/words/hindi/net/programming-with-txtsaveoptions/_index.md index 802013d813..767814a1bd 100644 --- a/words/hindi/net/programming-with-txtsaveoptions/_index.md +++ b/words/hindi/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Aspose.Words for .NET ट्यूटोरियल आपको Word दस् | [वर्ड डॉक्यूमेंट में बीड़ी मार्क जोड़ें](./add-bidi-marks/) | इस गाइड के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में द्विदिशात्मक (बीड़ी) चिह्न जोड़ना सीखें। बहुभाषी सामग्री के लिए उचित पाठ दिशा सुनिश्चित करें। | | [सूची इंडेंटेशन के लिए प्रति स्तर टैब वर्ण का उपयोग करें](./use-tab-character-per-level-for-list-indentation/) | .NET के लिए Aspose.Words का उपयोग करके टैब्ड इंडेंटेशन के साथ बहु-स्तरीय सूचियाँ बनाना सीखें। अपने दस्तावेज़ों में सटीक सूची स्वरूपण के लिए इस गाइड का पालन करें। | | [सूची इंडेंटेशन के लिए प्रति स्तर स्पेस वर्ण का उपयोग करें](./use-space-character-per-level-for-list-indentation/) | Aspose.Words for .NET में स्पेस कैरेक्टर इंडेंटेशन के साथ मल्टी-लेवल सूचियाँ बनाने का तरीका जानें। सटीक दस्तावेज़ फ़ॉर्मेटिंग के लिए चरण-दर-चरण मार्गदर्शिका। | - +| [docx को txt के रूप में सहेजें – C# के साथ Word समीकरणों को LaTeX में निर्यात करें](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | C# का उपयोग करके .NET के लिए Aspose.Words के साथ docx फ़ाइल को txt में बदलें और Word समीकरणों को LaTeX स्वरूप में निर्यात करना सीखें। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/hindi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..360c8e95b1 --- /dev/null +++ b/words/hindi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words के साथ docx को txt में सहेजें – Word को जल्दी से txt में + बदलें और गणितीय समीकरणों को LaTeX के रूप में निर्यात करना सीखें। सरल C# कोड, अतिरिक्त + उपकरणों की आवश्यकता नहीं। +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: hi +og_description: C# में docx को txt के रूप में सहेजें और देखें कि गणित को LaTeX में + कैसे निर्यात करें। समीकरणों को बरकरार रखते हुए Word को txt में बदलने के लिए इस चरण‑दर‑चरण + गाइड का पालन करें। +og_title: docx को txt के रूप में सहेजें – Word समीकरणों को LaTeX में निर्यात करें +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx को txt के रूप में सहेजें – C# के साथ Word समीकरणों को LaTeX में निर्यात + करें +url: /hi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx को txt के रूप में सहेजें – C# के साथ Word समीकरणों को LaTeX में निर्यात करें + +क्या आपको कभी **save docx as txt** की ज़रूरत पड़ी है, लेकिन इस बात की चिंता रही है कि आपके समीकरण गायब हो जाएंगे या अपठनीय गड़बड़ी में बदल जाएंगे? आप अकेले नहीं हैं। कई डेवलपर्स को यह समस्या आती है जब वे **convert word to txt** को downstream प्रोसेसिंग के लिए करने की कोशिश करते हैं, विशेष रूप से जब स्रोत फ़ाइल में Office Math ऑब्जेक्ट्स होते हैं। + +अच्छी खबर? कुछ ही C# लाइनों और सही विकल्पों के साथ, आप न केवल **convert Word to txt** कर सकते हैं बल्कि हर समीकरण को साफ़ LaTeX मार्कअप के रूप में भी रख सकते हैं। इस ट्यूटोरियल में हम पूरी प्रक्रिया को चरण‑दर‑चरण देखेंगे, यह समझाएंगे कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है, और आपको परिणाम को कैसे सत्यापित करें दिखाएंगे। + +हम कवर करेंगे: + +* Aspose.Words for .NET लाइब्रेरी को इंस्टॉल करना +* एक `.docx` लोड करना जिसमें गणितीय समीकरण हों +* `TxtSaveOptions` को कॉन्फ़िगर करना ताकि **how to export math** एक LaTeX‑friendly स्ट्रिंग बन जाए +* फ़ाइल को सहेजना और आउटपुट की जाँच करना + +अंत तक, आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जो आपको **save docx as txt** करने की अनुमति देगा, जबकि हर फ़ॉर्मूला को LaTeX के रूप में संरक्षित रखेगा—वैज्ञानिक पाइपलाइन, स्थैतिक साइट जेनरेटर, या किसी भी वर्कफ़्लो के लिए परिपूर्ण जो plain‑text गणित की आवश्यकता रखता है। + +--- + +## आवश्यकताएँ + +शुरू करने से पहले, सुनिश्चित करें कि आपके पास है: + +* .NET 6.0 या बाद का संस्करण (कोड .NET Framework 4.6+ के साथ भी काम करता है) +* Visual Studio 2022 (या आपका पसंदीदा कोई भी IDE) +* **Aspose.Words for .NET** NuGet पैकेज – इसे इस कमांड से इंस्टॉल करें + +```bash +dotnet add package Aspose.Words +``` + +कोई अतिरिक्त कन्वर्टर या बाहरी टूल्स आवश्यक नहीं हैं; Aspose.Words आंतरिक रूप से सभी भारी कार्य संभालता है। + +## चरण 1: Aspose.Words को इंस्टॉल और रेफ़रेंस करें + +सबसे पहले, लाइब्रेरी को अपने प्रोजेक्ट में जोड़ें। यदि आप कमांड लाइन का उपयोग कर रहे हैं, तो ऊपर दिया गया कमांड चलाएँ। Visual Studio में आप **Dependencies → Manage NuGet Packages** पर राइट‑क्लिक करके *Aspose.Words* खोज सकते हैं। + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** नवीनतम स्थिर संस्करण का उपयोग करें (अप्रैल 2026 तक यह 24.10 है)। नए रिलीज़ OfficeMath हैंडलिंग के बग फिक्स लाते हैं, इसलिए आप अप्रत्याशित गायब प्रतीकों से बचेंगे। + +## चरण 2: स्रोत दस्तावेज़ लोड करें + +अब हम उस `.docx` को लाते हैं जिसमें वह समीकरण हैं जिन्हें आप रखना चाहते हैं। `Document` क्लास पूरे Word फ़ाइल को एब्स्ट्रैक्ट करती है, जिससे आपको टेक्स्ट, इमेजेज़ और Office Math ऑब्जेक्ट्स तक पहुँच मिलती है। + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +पहले इसे लोड क्यों करें? Aspose.Words फ़ाइल को एक ऑब्जेक्ट मॉडल में पार्स करता है, जिससे हम सामग्री को निरीक्षण या संशोधित कर सकते हैं इससे पहले कि हम तय करें कि इसे कैसे एक्सपोर्ट किया जाए। यहीं पर **how to export math** निर्णय महत्वपूर्ण हो जाते हैं। + +## चरण 3: LaTeX निर्यात के लिए TxtSaveOptions कॉन्फ़िगर करें + +समाधान का मुख्य भाग `TxtSaveOptions` क्लास है। डिफ़ॉल्ट रूप से, TXT में सहेजने से Office Math पूरी तरह हट जाता है। `OfficeMathExportMode` को `LaTeX` सेट करने से लाइब्रेरी प्रत्येक समीकरण को उसके LaTeX प्रतिनिधित्व में बदल देती है। + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX वैज्ञानिक प्रकाशन की lingua franca है। इस तरह गणित को एक्सपोर्ट करने से आप समीकरण की अर्थवत्ता को एक फ्लैट इमेज या गड़बड़ स्ट्रिंग की बजाय बनाए रखते हैं। यदि आप बाद में इस TXT को ऐसे Markdown प्रोसेसर में फीड करते हैं जो MathJax को सपोर्ट करता है, तो समीकरण पूरी तरह रेंडर होंगे। + +## चरण 4: दस्तावेज़ को plain‑text के रूप में सहेजें + +विकल्प कॉन्फ़िगर हो जाने पर, अंतिम चरण एक‑लाइनर है जो फ़ाइल को डिस्क पर लिखता है। + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +बस इतना ही—आपका `.docx` अब एक `.txt` फ़ाइल है जहाँ हर समीकरण LaTeX स्निपेट के रूप में दिखता है, downstream उपयोग के लिए तैयार। + +## आउटपुट की जाँच (txt को सही तरीके से सहेजना कैसे है) + +`MathSample.txt` को किसी भी टेक्स्ट एडिटर में खोलें। आपको कुछ इस तरह दिखना चाहिए: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +यदि आप कच्चे Word‑विशिष्ट अक्षर (जैसे `?` या गायब प्रतीक) देखते हैं, तो दोबारा जाँचें कि: + +* आप एक नवीनतम Aspose.Words संस्करण का उपयोग कर रहे हैं (पुराने बिल्ड में OfficeMath के साथ बग थे)। +* स्रोत दस्तावेज़ वास्तव में **OfficeMath** ऑब्जेक्ट्स रखता है—पुराने Equation Editor ऑब्जेक्ट्स नहीं। बाद वाले के लिए, आपको उन्हें मैन्युअल रूप से कन्वर्ट करना पड़ सकता है या सहेजने से पहले `ConvertMathToOfficeMath` मेथड का उपयोग करना पड़ सकता है। + +## सामान्य विविधताएँ और किनारे के मामले + +| स्थिति | क्या करें | +|-----------|------------| +| **Legacy Equation Editor** objects | चरण 3 से पहले `doc.ConvertMathToOfficeMath()` कॉल करें। | +| **You need plain Unicode math, not LaTeX** | `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode` सेट करें। | +| **Large documents (100 + MB)** | मेमोरी उपयोग कम करने के लिए `doc.Save(Stream, txtOptions)` का उपयोग करके सेव ऑपरेशन को स्ट्रीम करें। | +| **You want to keep the original file name** | आउटपुट पाथ बनाते समय `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` उपयोग करें। | + +ये बदलाव विभिन्न पाइपलाइन के लिए “**how to export math**” प्रश्न का उत्तर देते हैं, जिससे आपका समाधान स्रोत चाहे जैसा भी हो, मजबूत बनता है। + +## पूर्ण कार्यशील उदाहरण (सभी चरण एक ही जगह) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +प्रोग्राम चलाएँ, उत्पन्न `.txt` खोलें, और आप देखेंगे कि LaTeX समीकरण ठीक उसी जगह एम्बेडेड हैं जहाँ वे होने चाहिए थे। यह **convert** करने का सबसे सरल तरीका है + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hindi/net/working-with-fonts/_index.md b/words/hindi/net/working-with-fonts/_index.md index 7b5c73e90a..3860b42d2f 100644 --- a/words/hindi/net/working-with-fonts/_index.md +++ b/words/hindi/net/working-with-fonts/_index.md @@ -32,10 +32,10 @@ | [फ़ॉन्ट जोर चिह्न सेट करें](./set-font-emphasis-mark/) | इस विस्तृत, चरण-दर-चरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में फ़ॉन्ट जोर चिह्न सेट करना सीखें। .NET डेवलपर्स के लिए बिल्कुल सही। | | [फ़ॉन्ट फ़ोल्डर सेट करें](./set-fonts-folders/) | इस विस्तृत, चरण-दर-चरण मार्गदर्शिका के साथ .NET के लिए Aspose.Words में कस्टम फ़ॉन्ट फ़ोल्डर सेट करना सीखें। दस्तावेज़ फ़ॉन्ट को बेहतर बनाने की चाह रखने वाले डेवलपर्स के लिए बिल्कुल सही। | | [फ़ॉन्ट प्रतिस्थापन सक्षम करें अक्षम करें](./enable-disable-font-substitution/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में फ़ॉन्ट प्रतिस्थापन को सक्षम या अक्षम करना सीखें। सुनिश्चित करें कि आपके दस्तावेज़ सभी प्लेटफ़ॉर्म पर एक जैसे दिखें। | -| [फ़ॉन्ट फ़ॉलबैक सेटिंग सेट करें](./set-font-fallback-settings/) | जानें कि .NET के लिए Aspose.Words में फ़ॉन्ट प्रतिस्थापन सेटिंग्स कैसे सेट करें और अपने Word दस्तावेज़ों में फ़ॉन्ट प्रतिस्थापन को अनुकूलित करें। | +| [फ़ॉन्ट फ़ॉलबैक सेटिंग सेट करें](./set-font-fallback-settings/) | जानें कि .NET के लिए Aspose.Words में फ़ॉन्ट प्रतिस्थापन सेटिंग्स कैसे सेट करें और अपने Word दस्तावेज़ में फ़ॉन्ट प्रतिस्थापन को अनुकूलित करें। | | [नोटो फ़ॉलबैक सेटिंग्स लोड करें](./load-noto-fallback-settings/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ में Noto फ़ॉलबैक सेटिंग लोड करना सीखें। सभी वर्णों को सही ढंग से प्रदर्शित करने के लिए हमारे चरण-दर-चरण मार्गदर्शिका का पालन करें। | | [फ़ॉन्ट फ़ोल्डर डिफ़ॉल्ट इंस्टेंस सेट करें](./set-fonts-folders-default-instance/) | इस चरण-दर-चरण ट्यूटोरियल के साथ .NET के लिए Aspose.Words में डिफ़ॉल्ट इंस्टेंस के लिए फ़ॉन्ट फ़ोल्डर सेट करना सीखें। अपने Word दस्तावेज़ों को आसानी से कस्टमाइज़ करें। | -| [फ़ॉन्ट फ़ोल्डर्स एकाधिक फ़ोल्डर्स सेट करें](./set-fonts-folders-multiple-folders/) | .NET के लिए Aspose.Words का उपयोग करके अपने Word दस्तावेज़ों में एकाधिक फ़ॉन्ट फ़ोल्डर सेट करना सीखें। यह चरण-दर-चरण मार्गदर्शिका सुनिश्चित करती है कि आपके दस्तावेज़ों में वही फ़ॉन्ट उपयोग किए जाएँ जिनकी आपको आवश्यकता है। | +| [फ़ॉन्ट फ़ोल्डर्स एकाधिक फ़ोल्डर्स सेट करें](./set-fonts-folders-multiple-folders/) | .NET के लिए Aspose.Words का उपयोग करके अपने Word दस्तावेज़ में एकाधिक फ़ॉन्ट फ़ोल्डर सेट करना सीखें। यह चरण-दर-चरण मार्गदर्शिका सुनिश्चित करती है कि आपके दस्तावेज़ों में वही फ़ॉन्ट उपयोग किए जाएँ जिनकी आपको आवश्यकता है। | | [फ़ॉन्ट फ़ोल्डर सिस्टम और कस्टम फ़ोल्डर सेट करें](./set-fonts-folders-system-and-custom-folder/) जानें कि .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में सिस्टम और कस्टम फ़ॉन्ट फ़ोल्डर कैसे सेट करें, जिससे यह सुनिश्चित हो सके कि आपके दस्तावेज़ विभिन्न वातावरणों में सही ढंग से प्रदर्शित हों। | | [प्राथमिकता के साथ फ़ॉन्ट फ़ोल्डर सेट करें](./set-fonts-folders-with-priority/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में प्राथमिकता के साथ फ़ॉन्ट फ़ोल्डर सेट करना सीखें। हमारा गाइड सुनिश्चित करता है कि आपके दस्तावेज़ हर बार पूरी तरह से रेंडर हों। | | [ट्रू टाइप फ़ॉन्ट्स फ़ोल्डर सेट करें](./set-true-type-fonts-folder/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में ट्रू टाइप फ़ॉन्ट फ़ोल्डर सेट करना सीखें। सुसंगत फ़ॉन्ट प्रबंधन सुनिश्चित करने के लिए हमारे विस्तृत, चरण-दर-चरण मार्गदर्शिका का पालन करें। | @@ -48,6 +48,7 @@ | [चेतावनी अधिसूचना प्राप्त करें](./receive-warning-notification/) जानें कि .NET के लिए Aspose.Words का उपयोग करते समय चेतावनी अधिसूचना कैसे प्राप्त करें और अपने दस्तावेज़ों में किसी भी समस्या या चेतावनी का प्रबंधन कैसे करें। | | [संसाधन स्टीम फ़ॉन्ट स्रोत उदाहरण](./resource-steam-font-source-example/) | .NET के लिए Aspose.Words में कस्टम फ़ॉन्ट लोड करने के लिए संसाधन स्ट्रीम फ़ॉन्ट स्रोत का उपयोग करना सीखें। | | [प्रत्यय के बिना प्रतिस्थापन प्राप्त करें](./get-substitution-without-suffixes/) | इस ट्यूटोरियल में, Aspose.Words for .NET के साथ Word दस्तावेज़ में प्रत्यय रहित ओवरराइड प्राप्त करना सीखें। | +| [Aspose फ़ॉन्ट प्रतिस्थापन – Word दस्तावेज़ों में लापता फ़ॉन्ट्स का पता लगाएँ](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | .NET के लिए Aspose.Words का उपयोग करके Word दस्तावेज़ों में लापता फ़ॉन्ट्स का पता लगाने और प्रबंधित करने का तरीका सीखें। | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hindi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/hindi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..55c61a37c4 --- /dev/null +++ b/words/hindi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Aspose फ़ॉन्ट प्रतिस्थापन गाइड वर्ड दस्तावेज़ लोड करते समय गायब फ़ॉन्ट्स + का पता लगाने के लिए। फ़ॉन्ट सेटिंग्स को कॉन्फ़िगर करना और गायब फ़ॉन्ट्स को कुशलतापूर्वक + संभालना सीखें। +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: hi +og_description: Aspose फ़ॉन्ट प्रतिस्थापन गाइड जो वर्ड दस्तावेज़ लोड करते समय गायब + फ़ॉन्ट्स का पता लगाता है। फ़ॉन्ट सेटिंग्स को कॉन्फ़िगर करना सीखें और गायब फ़ॉन्ट्स + को प्रभावी ढंग से संभालें। +og_title: Aspose फ़ॉन्ट प्रतिस्थापन – वर्ड दस्तावेज़ों में गायब फ़ॉन्ट का पता लगाएँ +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose फ़ॉन्ट प्रतिस्थापन – वर्ड दस्तावेज़ों में लापता फ़ॉन्ट का पता लगाएँ +url: /hi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Word दस्तावेज़ों में लापता फ़ॉन्ट्स का पता लगाएँ + +क्या कभी ऐसा हुआ है कि एक Word फ़ाइल एक मशीन पर एकदम सही दिखती है, लेकिन दूसरी पर फ़ॉन्ट बदलकर दिखती है? यही क्लासिक **aspose font substitution** समस्या है, और आमतौर पर इसका मतलब है कि लक्ष्य सिस्टम में कुछ फ़ॉन्ट्स नहीं हैं। इस ट्यूटोरियल में हम आपको चरण‑बद्ध तरीके से दिखाएंगे कि **Word दस्तावेज़ लोड करते समय लापता फ़ॉन्ट्स का पता कैसे लगाएँ**, **फ़ॉन्ट सेटिंग्स को कैसे कॉन्फ़िगर करें**, और **लापता फ़ॉन्ट्स को सुगमता से कैसे हैंडल करें**। + +हम एक पूर्ण, चलने योग्य C# उदाहरण के माध्यम से चलेंगे, समझाएंगे कि प्रत्येक पंक्ति क्यों महत्वपूर्ण है, और वह कंसोल आउटपुट भी दिखाएंगे जिसकी आपको उम्मीद करनी चाहिए। अंत तक आप दस्तावेज़ लोड होते ही फ़ॉन्ट प्रतिस्थापन को पहचान सकेंगे—बिना किसी अनुमान के। + +## आप क्या सीखेंगे + +- Aspose.Words के फ़ॉन्ट चेतावनियों के लिए डायग्नोस्टिक कलेक्टर को कैसे सक्षम करें। +- कस्टम **फ़ॉन्ट सेटिंग्स** के साथ **Word दस्तावेज़ लोड** करने के लिए आवश्यक सटीक कोड। +- `WarningInfo` ऑब्जेक्ट्स पर इटरेट करके हर प्रतिस्थापित फ़ॉन्ट की सूची कैसे बनाएं। +- अनचाही चेतावनियों को दबाने या फॉलबैक फ़ॉन्ट प्रदान करने के टिप्स। +- एक तैयार‑से‑चलाने वाला सैंपल जिसे आप Visual Studio में कॉपी‑पेस्ट कर सकते हैं। + +### आवश्यकताएँ + +- .NET 6.0 या बाद का (API .NET Framework पर भी समान काम करता है)। +- Aspose.Words for .NET (NuGet पैकेज `Aspose.Words`)। +- एक Word फ़ाइल जिसमें ऐसा फ़ॉन्ट रेफ़रेंस हो जो आपके सिस्टम में इंस्टॉल न हो (जैसे `MissingFont.docx`)। + +यदि आपके पास ये सब है, तो चलिए शुरू करते हैं। + +## चरण 1 – डायग्नोस्टिक कलेक्टर को सक्षम करें (फ़ॉन्ट सेटिंग्स कॉन्फ़िगर करें) + +सबसे पहले: Aspose.Words केवल तब ही फ़ॉन्ट प्रतिस्थापन चेतावनियों को रिकॉर्ड करता है जब आप उसे बताते हैं। यह `FontSettings` ऑब्जेक्ट बनाकर और उसे `LoadOptions` इंस्टेंस में असाइन करके किया जाता है। इसे फ़ॉन्ट हैंडलिंग के लिए “डिबग लाइट्स” चालू करने जैसा समझें। + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**क्यों?** +यदि `FontSettings` ऑब्जेक्ट नहीं बनाया गया, तो चेतावनी कलेक्टर चुप रहता है, और आपको कभी नहीं पता चलता कि कौन से फ़ॉन्ट बदल दिए गए। इसे खाली इनिशियलाइज़ करके हम Aspose को डिफ़ॉल्ट सिस्टम फ़ॉन्ट्स उपयोग करने देते हैं *और* किसी भी प्रतिस्थापन को ट्रैक करते हैं। + +> **प्रो टिप:** यदि आपको पता है कि कोई विशेष फ़ोल्डर कॉरपोरेट फ़ॉन्ट्स रखता है, तो `FontSettings` को `SetFontsFolder("path")` के साथ वहाँ पॉइंट करें। इससे लापता‑फ़ॉन्ट चेतावनियों की संख्या घट सकती है। + +## चरण 2 – कॉन्फ़िगर किए गए विकल्पों के साथ दस्तावेज़ लोड करें (Word दस्तावेज़ लोड करें) + +अब जब कलेक्टर सक्रिय है, तो वही `LoadOptions` का उपयोग करके अपनी `.docx` फ़ाइल लोड करें। यही वह क्षण है जब Aspose दस्तावेज़ को स्कैन करता है, हर फ़ॉन्ट रेफ़रेंस देखता है, और तय करता है कि प्रतिस्थापन आवश्यक है या नहीं। + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**यह क्यों महत्वपूर्ण है?** +यदि आप केवल `new Document("MissingFont.docx")` कॉल करते, तो डिफ़ॉल्ट सेटिंग्स लागू होतीं *और* चेतावनी सूची खाली रहती। `loadOptions` पास करने से यह सुनिश्चित होता है कि डायग्नोस्टिक कलेक्टर लोडिंग पाइपलाइन में जुड़ा हुआ है। + +## चरण 3 – फ़ॉन्ट प्रतिस्थापन चेतावनियों को प्राप्त करें और प्रदर्शित करें (लापता फ़ॉन्ट्स का पता लगाएँ) + +दस्तावेज़ मेमोरी में लोड हो जाने के बाद, Aspose किसी भी चेतावनी को `document.WarningCallback.Warnings` में स्टोर करता है। उस कलेक्शन पर लूप लगाएँ, `WarningType.FontSubstitution` के लिए फ़िल्टर करें, और विवरण प्रिंट करें। प्रत्येक विवरण बताता है कि कौन सा फ़ॉन्ट लापता था और उसकी जगह कौन सा फ़ॉन्ट उपयोग किया गया। + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**अपेक्षित कंसोल आउटपुट** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +यह आउटपुट आपको ठीक‑ठीक बताता है कि कोड चलाने वाली मशीन पर कौन‑से फ़ॉन्ट्स लापता हैं। अब आप तय कर सकते हैं कि लापता फ़ॉन्ट्स इंस्टॉल करें, उन्हें दस्तावेज़ में एम्बेड करें, या प्रतिस्थापन को जैसा है वैसा रखें। + +![Console output showing aspose font substitution warnings](/images/aspose-font-substitution-console.png) + +*छवि वैकल्पिक पाठ:* aspose फ़ॉन्ट प्रतिस्थापन – कंसोल आउटपुट जिसमें प्रतिस्थापित फ़ॉन्ट्स की सूची है + +## चरण 4 – वैकल्पिक: प्रतिस्थापन व्यवहार को कस्टमाइज़ करें (लापता फ़ॉन्ट्स को हैंडल करें) + +कभी‑कभी आप सिर्फ यह जानना नहीं चाहते कि *किसी* फ़ॉन्ट का प्रतिस्थापन हुआ, बल्कि आप यह नियंत्रित करना चाहते हैं कि *कैसे* हुआ। Aspose.Words आपको एक कस्टम `IFontSubstitutionRule` रजिस्टर करने की सुविधा देता है। नीचे एक त्वरित उदाहरण है जो किसी भी लापता फ़ॉन्ट को `Tahoma` पर फॉलबैक करने के लिए मजबूर करता है। + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**आप इसे कब उपयोग करेंगे?** +यदि आप वेब सर्विस के लिए PDFs जेनरेट कर रहे हैं और आपको पता है कि हर क्लाइंट `Tahoma` रेंडर कर सकता है, तो फॉलबैक को मजबूर करने से विज़ुअल कंसिस्टेंसी सुनिश्चित होती है, बिना कई फ़ॉन्ट फ़ाइलें शिप किए। + +## पूर्ण कार्यशील उदाहरण (सभी चरणों का संयोजन) + +यहाँ पूरा प्रोग्राम है जिसे आप नई कंसोल प्रोजेक्ट में पेस्ट कर सकते हैं। यह जैसा है वैसा ही कंपाइल हो जाएगा, बशर्ते आपने Aspose.Words NuGet पैकेज इंस्टॉल किया हो। + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +प्रोग्राम चलाएँ, कंसोल देखें, और आपको हर लापता‑फ़ॉन्ट इवेंट प्रिंट होते दिखेंगे। इसके बाद आप तय कर सकते हैं कि फ़ॉन्ट्स इंस्टॉल करें, एम्बेड करें, या फॉलबैक रखें। + +## अक्सर पूछे जाने वाले प्रश्न + +**प्रश्न: क्या यह PDF रूपांतरण के साथ काम करता है?** +हाँ। जब आप बाद में `doc.Save("output.pdf")` कॉल करेंगे, तो लोडिंग के दौरान प्रतिस्थापित किए गए फ़ॉन्ट्स ही PDF में एम्बेड होंगे। इसलिए चेतावनियों को पहले पकड़ना आपको अंतिम PDF में आश्चर्यजनक फ़ॉन्ट बदलावों से बचाता है। + +**प्रश्न: यदि मेरे पास कई दस्तावेज़ प्रोसेस करने हैं तो क्या करें?** +लोडिंग लॉजिक को `try‑catch` ब्लॉक में रखें और कई दस्तावेज़ों में एक ही `FontSettings` इंस्टेंस को पुनः उपयोग करें। इससे ओवरहेड कम होता है और प्रत्येक फ़ाइल के लिए चेतावनी कलेक्टर सक्रिय रहता है। + +**प्रश्न: क्या मैं चेतावनियों को पूरी तरह से दबा सकता हूँ?** +आप `loadOptions.WarningCallback = null;` सेट करके लोडिंग से पहले चेतावनियों को बंद कर सकते हैं, लेकिन इससे **लापता फ़ॉन्ट्स का पता लगाना** संभव नहीं रहेगा—जो आमतौर पर आपका लक्ष्य नहीं होता। + +## निष्कर्ष + +हमने **aspose font substitution** को पूरी तरह से समझने के लिए सभी आवश्यक कदम कवर किए: डायग्नोस्टिक कलेक्टर को सक्षम करना, कस्टम **फ़ॉन्ट सेटिंग्स** के साथ Word फ़ाइल लोड करना, लापता फ़ॉन्ट्स की सूची निकालना, और यहाँ तक कि डिफ़ॉल्ट प्रतिस्थापन नियम को ओवरराइड करके **लापता फ़ॉन्ट्स** को अपनी इच्छा अनुसार हैंडल करना। कुछ ही C# लाइनों से आप उन फ़ॉन्ट समस्याओं पर पूरी नज़र रख सकते हैं, जो अन्यथा सूक्ष्म लेआउट बदलावों के पीछे छिपी रहती हैं। + +अगला कदम? `FontSettings.SetFontsFolder` के साथ मूल फ़ॉन्ट्स को दस्तावेज़ में एम्बेड करने की कोशिश करें या `FontSourceBase` का उपयोग करके फ़ॉन्ट्स को डेटाबेस से लोड करें। आप `Document.BuiltInStyle` कलेक्शन के साथ प्रयोग करके देख सकते हैं कि स्टाइल‑लेवल फ़ॉन्ट बदलाव कैसे प्रसारित होते हैं। + +Aspose.Words या फ़ॉन्ट मैनेजमेंट के बारे में और सवाल हैं? टिप्पणी छोड़ें, आधिकारिक Aspose दस्तावेज़ देखें, या नई प्रोजेक्ट बनाकर ऊपर दिया गया कोड आज़माएँ। खुशहाल कोडिंग, और आपके दस्तावेज़ हमेशा इच्छित रूप में रेंडर हों! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/basic-conversions/_index.md b/words/hongkong/net/basic-conversions/_index.md index 4b06abe748..512a681707 100644 --- a/words/hongkong/net/basic-conversions/_index.md +++ b/words/hongkong/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [將 PDF 儲存為 Jpeg](./pdf-to-jpeg/) |使用 Aspose.Words for .NET 輕鬆將 PDF 轉換為 JPEG。請遵循我們的詳細指南,其中包含範例和常見問題。非常適合開發人員和愛好者。 | | [將 PDF 儲存為 Word 格式 (Docx)](./pdf-to-docx/) |透過本詳細的逐步指南了解如何使用 Aspose.Words for .NET 將 PDF 轉換為 Word 文件 (Docx)。非常適合開發人員。 | | [使用 Aspose.Words 將 Word 儲存為 PDF – 完整 C# 教學](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | 完整指南教您在 C# 中使用 Aspose.Words 將 Word 檔案儲存為 PDF,提供程式碼範例與最佳實踐。 | +| [在 C# 中使用 Aspose.Words 完整 Word 轉 PDF 教學](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | 提供完整步驟與程式碼範例,說明如何在 C# 中使用 Aspose.Words 將 Word 文件轉換為 PDF。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hongkong/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/hongkong/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..be47337f1c --- /dev/null +++ b/words/hongkong/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-05 +description: 使用 C# 及 Aspose.Words 將 Word 轉換為 PDF。了解如何將 docx 儲存為 PDF、匯出可存取的 PDF,以及有效載入 + Word 文件。 +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: zh-hant +og_description: 將 Word 轉換為 PDF(C#)的逐步指南。了解如何將 docx 儲存為 PDF、匯出可存取的 PDF,以及使用 Aspose.Words + 載入 Word 文件。 +og_title: 在 C# 中將 Word 轉換為 PDF – 完整 Aspose.Words 教程 +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: 在 C# 中將 Word 轉換為 PDF – 完整指南(使用 Aspose.Words) +url: /zh-hant/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中將 Word 轉換為 PDF – 完整程式教學 + +有沒有想過要 **convert word to pdf**,卻不想與繁雜的指令列工具或第三方服務糾纏?你並不是唯一有此困擾的開發者。當客戶要求直接從 DOCX 檔案產出符合無障礙規範的 PDF 時,常常會卡在這一步。好消息是,只要寫幾行 C# 程式,搭配功能強大的 Aspose.Words 套件,就能瞬間把 Word 文件轉成符合標準的 PDF。 + +在本教學中,我們會一步步說明所有必備知識:從 **load word document** 的基礎操作、設定正確的選項以 **how to export accessible pdf**,到最後儲存結果,讓你能可靠地 **save docx as pdf**。完成後,你將擁有一段可直接放入任何 .NET 專案的完整程式碼。 + +> **專業提示:** 若你需要符合 PDF/UA‑2(許多政府機關要求的無障礙標準),只要設定正確的 `PdfCompliance` 旗標,程式碼本身不需要額外變更。 + +--- + +## 你將學會 + +- 如何在 C# 中使用 Aspose.Words **load word document**。 +- 產出 **how to export accessible pdf**(PDF/UA‑2)所需的精確設定。 +- 一個完整、可直接執行的範例,讓你只需一行程式碼即可 **save docx as pdf**。 +- 在 **c# convert docx pdf** 時常見的陷阱與避免方式。 +- 快速驗證產生的 PDF 是否符合無障礙需求的方法。 + +全程不需外部工具、也不必編寫複雜的設定檔,只要純粹的 C# 程式碼即可立即編譯執行。 + +--- + +## 前置條件 + +在開始之前,請先確認你已具備以下環境: + +1. 已安裝 **.NET 6.0**(或任何較新的 .NET 版本)。舊版框架亦可使用,但以下語法以現代 SDK 為前提。 +2. 取得 **Aspose.Words for .NET** 的授權。此套件提供免費試用版,正式上線前需使用有效金鑰。 +3. 在專案中加入 **Aspose.Words** NuGet 套件: + +```bash +dotnet add package Aspose.Words +``` + +就這樣——不需要額外的二進位檔案、也不必使用 COM interop,只要一個乾淨的 NuGet 參考即可。 + +--- + +![使用 Aspose.Words 在 C# 中將 Word 轉換為 PDF](image-placeholder.png "使用 Aspose.Words 在 C# 中將 Word 轉換為 PDF") + +--- + +## 步驟說明實作 + +以下將整個流程切分為多個邏輯區塊。每一步都會提供程式碼片段、說明 **為何** 需要這麼做,以及來自實務經驗的小技巧。 + +### ## Convert Word to PDF – Load the Source Document + +首先必須 **load word document** 到記憶體。Aspose.Words 會自行處理 OpenXML 解析,讓你可以直接操作 DOCX、DOC,甚至 RTF,而不必擔心格式細節。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**為何重要:** +載入檔案會產生一個 `Document` 物件,完整代表 Word 檔的所有內容(包括頁首、頁尾、樣式與隱藏的中繼資料)。若跳過此步驟或改用原始串流讀取,版面配置資訊將遺失,進而影響 PDF 的最終呈現。 + +> **旁註:** 同一個 `Document` 建構子同樣支援 `.doc` 與 `.rtf`,因此即使來源不是純粹的 DOCX,你仍可 **c# convert docx pdf**。 + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +文件已載入記憶體後,我們需要告訴 Aspose.Words 產生 PDF 時的行為。大多數情況下預設設定已足夠,但若要產出 **accessible PDF**,必須開啟 PDF/UA‑2 相容性旗標。 + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**為何重要:** +`PdfCompliance.PdfUAXmpA2` 會指示函式庫嵌入螢幕閱讀器所需的標籤與結構。若未設定此旗標,雖然 PDF 看起來完美,卻可能在無障礙稽核中失敗。 + +> **小技巧:** 若只需要普通 PDF,直接移除 `Compliance` 那一行即可,其餘選項仍能產出高品質檔案。 + +### ## Convert Word to PDF – Write the File + +設定完成後,最後一步就是 **save docx as pdf**。只要呼叫一次方法,函式庫就會完成版面轉換、字型嵌入與無障礙標記等所有工作。 + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**你會得到:** +- 位於 `outputPath` 的 PDF 檔,版面與原始 Word 完全一致。 +- 若使用 `PdfUAXmpA2` 旗標,PDF 會被標記為符合 PDF/UA‑2。 +- 所有字型皆已嵌入,確保在任何機器上顯示一致。 + +### ## Verify the Accessible PDF (Optional but Recommended) + +轉換完成後,建議再次確認 PDF 是否真的 **how to export accessible pdf** 正確。可使用 Adobe Acrobat Reader 的「Accessibility Check」或開源的 `pdfcpu` 驗證工具。 + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +若驗證工具未回報錯誤,即表示你已成功 **convert word to pdf**,且具備完整的無障礙支援。 + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| 問題 | 為何會發生 | 解決方式 | +|------|------------|----------| +| 缺少字型 | 原始 DOCX 使用了伺服器上未安裝的自訂字型 | 設定 `EmbedFullFonts = true` 或在機器上安裝該字型 | +| 檔案過大 | 圖片以原始解析度嵌入 | 使用 `ImageCompression = PdfImageCompression.Jpeg` 並調低 `JpegQuality` | +| 超連結失效 | 連結使用相對路徑,客戶端找不到對應檔案 | 改為絕對 URL,或調整 `HyperlinkTarget` 屬性 | +| 無障礙標籤缺失 | 未設定 `Compliance` 旗標 | 如前範例加入 `Compliance = PdfCompliance.PdfUAXmpA2` | + +掌握以上要點,即可讓你的 **c# convert docx pdf** 流程更穩定、適合上線使用。 + +--- + +## 完整範例程式 + +以下提供一個可直接編譯執行的 Console 應用程式,將所有步驟整合在一起。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**預期結果:** 執行程式後,你會在 `C:\Docs` 看到 `output.pdf`。以任意 PDF 閱讀器開啟,版面應與 `input.docx` 完全相符,且使用無障礙檢查工具時會通過 PDF/UA‑2 認證。 + +--- + +## 結語 + +我們已完整示範如何使用 C# 與 Aspose.Words **convert word to pdf**。只要 **load word document**、正確設定 `PdfSaveOptions`,最後 **save docx as pdf**,即可在最少程式碼下產出高品質且符合無障礙標準的 PDF。無論你是建置文件產生微服務,或是本地批次轉換工具, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-markdownsaveoptions/_index.md b/words/hongkong/net/programming-with-markdownsaveoptions/_index.md index 683c822db1..62225928a0 100644 --- a/words/hongkong/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hongkong/net/programming-with-markdownsaveoptions/_index.md @@ -32,6 +32,8 @@ | [將 docx 儲存為 markdown – 完整 C# 指南(含圖像提取)](./save-docx-as-markdown-full-c-guide-with-image-extraction/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 DOCX 轉換為 Markdown,並提取圖像。 | | [如何將 Word 匯出為 Markdown – 完整 C# 指南](./how-to-export-markdown-from-word-complete-c-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 Word 文件匯出為 Markdown,提供完整步驟與範例程式碼。 | | [如何將 DOCX 匯出為 Markdown – 完整 C# 指南](./how-to-export-markdown-from-docx-complete-guide/) |示範如何使用 Aspose.Words for .NET 在 C# 中將 DOCX 匯出為 Markdown,提供完整步驟與範例程式碼。 | +| [將 DOCX 轉換為 Markdown – 從 DOCX 中提取圖像 (使用 Aspose.Words)](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) |示篯如何使用 Aspose.Words for .NET 將 DOCX 轉換為 Markdown,並提取圖像。 | +| [將 Word 轉換為 Markdown – 完整指南,含 PDF/UA 匯出](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) |示範如何使用 Aspose.Words for .NET 將 Word 文件轉換為 Markdown,並同時匯出符合 PDF/UA 標準的 PDF。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hongkong/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/hongkong/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..3b2265c190 --- /dev/null +++ b/words/hongkong/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-04-05 +description: 學習如何在 C# 中將 DOCX 轉換為 Markdown,並從 DOCX 中提取圖片。一步一步的指南,附完整程式碼與技巧。 +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: zh-hant +og_description: 使用 Aspose.Words 將 DOCX 轉換為 Markdown 並從 DOCX 中提取圖片。完整的 C# 教學,包含程式碼、說明與最佳實踐技巧。 +og_title: 將 DOCX 轉換為 Markdown – 使用 C# 從 DOCX 提取圖片 +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: 將 DOCX 轉換為 Markdown – 使用 Aspose.Words 從 DOCX 提取圖像 +url: /zh-hant/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 DOCX 轉換為 Markdown – 從 DOCX 中擷取圖片(C#) + +是否曾經需要**將 DOCX 轉換為 Markdown**,卻苦於輸出中圖片消失?你並不是唯一遇到這個問題的人。在許多專案中,Markdown 版本非常適合版本控制或靜態網站產生器,但圖片卻被遺漏,讓本來豐富的文件變成一個空洞的純文字檔。 + +好消息是?只要幾行 C# 程式碼加上 Aspose.Words,就能自動**將 DOCX 轉換為 Markdown** *以及* **從 DOCX 中擷取圖片**。本指南將帶你完整走過整個流程,說明每個步驟的原因,甚至示範如何保持圖片資料夾整潔。 + +## 你將學會 + +- 如何載入包含圖片的 DOCX。 +- 如何定義自訂的 `IResourceSavingCallback` 以決定每張圖片的儲存位置。 +- 如何設定 `MarkdownSaveOptions`,讓產生的 Markdown 正確引用已擷取的圖片。 +- 處理特殊情況的技巧,例如圖片名稱重複或非 PNG 格式。 +- 一個完整、可直接複製貼上的程式碼範例,讓你今天就能執行。 + +### 前置條件 + +- .NET 6.0 或更新版本(此 API 可在 .NET Core、.NET Framework 以及 .NET 5+ 上運作)。 +- 一份 **Aspose.Words for .NET** 授權(免費試用版可用於測試)。 +- 具備基本的 C# 與 Visual Studio(或你慣用的 IDE)使用經驗。 + +如果你已具備上述條件,讓我們開始吧。 + +--- + +## 步驟 1:設定專案並安裝 Aspose.Words + +首先,建立一個新的 Console 應用程式(或整合到現有的解決方案中)。 + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **專業提示:** 使用最新的 NuGet 版本(截至 2026 年 4 月為 24.12),即可取得最新的 Markdown 匯出改進。 + +--- + +## 步驟 2:建立回呼以將圖片儲存至指定位置 + +Aspose.Words 允許你在 Markdown 匯出過程中攔截每一個資源(圖片、SVG 等)。透過實作 `IResourceSavingCallback`,你可以: + +1. 選擇一個與 Markdown 檔案同層的資料夾。 +2. 產生唯一的檔名(避免覆寫已存在的圖片)。 +3. 決定格式(此處強制使用 PNG 以保持一致性)。 + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### 為什麼使用 GUID 作為檔名? + +如果來源 DOCX 中有兩張圖片的原始名稱相同,直接複製貼上會導致其中一張被覆寫。使用 `Guid.NewGuid()` 可保證唯一性,對於在自動化流水線中多次執行轉換特別有用。 + +--- + +## 步驟 3:載入 DOCX 並設定 Markdown 選項 + +現在,我們將文件載入記憶體,並掛接剛剛建立的回呼。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### 程式碼逐步說明 + +| 步驟 | 目的 | +|------|------| +| **定義路徑** | 讓專案保持彈性;可指向任何資料夾而不需重新編譯。 | +| **載入 DOCX** | `Document` 會解析 Word 檔案,讓所有元素(段落、表格、圖片)皆可存取。 | +| **設定 `MarkdownSaveOptions`** | `ResourceSavingCallback` 是擷取圖片的掛點。若未設定,Aspose.Words 會將圖片以 base64 字串嵌入,或根據設定直接省略。 | +| **儲存** | `doc.Save` 會寫入 Markdown 檔案,並為每張圖片觸發回呼。 | + +--- + +## 步驟 4:驗證輸出 – 你應該看到什麼? + +執行程式後,開啟 `DocWithImages.md`。你會看到類似以下的 Markdown 圖片連結: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +在 `C:\Docs\MarkdownResources` 中,你會找到一系列以 GUID 命名的 PNG 檔案。打開任一檔案,應與原始 DOCX 中嵌入的圖片完全相同。 + +如果在支援相對路徑的檢視器中開啟 Markdown 檔案(例如 VS Code 預覽、GitHub,或靜態網站產生器),圖片將會如同在 Word 中一樣正確顯示。 + +### 常見問題與避免方法 + +| 症狀 | 可能原因 | 解決方式 | +|------|----------|----------| +| 圖片顯示為斷開連結 | `ResourceFileName` 未設定,導致 Markdown 指向不存在的檔案。 | 在回呼中確保設定 `args.ResourceFileName = newFileName;`。 | +| PNG 檔案過大 | 原始圖片為 JPEG 或 BMP;轉換為 PNG 會增加檔案大小。 | 透過 `args.ResourceContentType` 偵測原始格式並保留:`args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| 仍出現重複圖片 | 使用了固定檔名而非 GUID。 | 改回使用 GUID 邏輯,或為每種圖片類型加入計數器。 | +| 轉換拋出 `FileNotFoundException` | 來源 DOCX 路徑錯誤或資料夾缺乏讀取權限。 | 確認路徑並授予相應的檔案系統權限。 | + +--- + +## 步驟 5:進階調整(可選) + +### 5.1 保留原始圖片格式 + +如果希望輸出圖片保留原始副檔名,請修改回呼: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 以 Base64 內嵌圖片(當你*不想*使用獨立檔案時) + +有時單一檔案的 Markdown 會更方便(例如透過電郵傳送)。請變更設定: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +但請記住:對於大多數靜態網站工作流程而言,**從 DOCX 中擷取圖片** 是主要目標,因此使用資料夾方式通常較佳。 + +--- + +## 完整可執行範例(可直接複製貼上) + +以下是一個完整的單檔程式碼。只需將路徑替換為自己的路徑後執行即可。 + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +使用 `dotnet run` 執行。當主控台顯示 ✅ 行時,開啟 Markdown 檔案,即可看到圖片正確呈現。 + +--- + +## 結論 + +現在,你已擁有一套使用 Aspose.Words 在 C# 中**完整、可投入生產的 DOCX 轉換為 Markdown 並擷取圖片**解決方案。主要關鍵字遍佈全文,提升對搜尋引擎與 AI 助手的相關性。 + +一次執行,程式碼會: + +1. 載入 Word 文件。 +2. 透過 `IResourceSavingCallback` 攔截每張圖片。 +3. 將每張圖片儲存至可預測且唯一名稱的資料夾。 +4. 產生引用這些圖片的 Markdown。 + +從此你可以: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/hongkong/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..d9618c1f7a --- /dev/null +++ b/words/hongkong/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-05 +description: 快速將 Word 轉換為 Markdown,並學習如何在 C# 中儲存為 PDF/UA。逐步程式碼、技巧與邊緣案例處理。 +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: zh-hant +og_description: 將 Word 轉換為 Markdown,並使用 Aspose.Words 另存為 PDF/UA。於一本精簡指南中了解原因、方法及最佳實踐技巧。 +og_title: 將 Word 轉換為 Markdown – 完整 C# 教程 +tags: +- Aspose.Words +- C# +- Document Conversion +title: 將 Word 轉換為 Markdown – 完整指南(含 PDF/UA 匯出) +url: /zh-hant/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 Word 轉換為 Markdown – 完整指南與 PDF/UA 匯出 + +有沒有想過如何在不遺失公式或圖片的情況下 **convert Word to Markdown**?你並不是唯一有此疑問的人。許多開發者需要一種可靠的方法,將 `.docx` 檔案轉換成乾淨的 Markdown,同時仍能 **save as PDF/UA** 以符合無障礙 PDF 的規範。在本教學中,我們將使用 Aspose.Words for .NET,逐步說明完整、可直接執行的解決方案,解釋每個設定的原因,並示範如何處理較為複雜的部分,如 OfficeMath 與浮動圖形。 + +閱讀完本指南後,你將擁有一個單一的 C# 程式,能夠: + +1. 以寬鬆的復原模式載入 Word 文件(即使檔案損壞也不會中斷執行)。 +2. 將其匯出為 Markdown,將公式轉換為 LaTeX,並透過自訂回呼儲存圖片。 +3. 將相同文件儲存為符合 PDF/UA‑2 標準的檔案,並將浮動圖形嵌入為內聯標籤。 + +聽起來很多嗎?別擔心——讓我們立即開始。 + +## 需求環境 + +- **Aspose.Words for .NET**(撰寫時的最新版本 23.x)。 +- 一個 .NET 開發環境(Visual Studio 2022、Rider,或 `dotnet` CLI)。 +- 一個範例 Word 檔案(`input.docx`),放置於可參考的資料夾中。 +- 具備基本的 C# 語法知識——不需要高深技巧,只要了解少量 `using` 陳述式即可。 + +> **Pro tip:** 如果你使用 NuGet 套件管理員,可使用以下指令加入函式庫 +> `dotnet add package Aspose.Words` 或透過 Visual Studio NuGet UI。 + +## 步驟 1 – 以寬鬆復原模式載入 Word 文件 + +當你從外部來源收到 Word 檔案時,可能會包含輕微的損壞。啟用 **Relaxed** 復原模式可讓 Aspose.Words 繼續執行,而不是拋出例外。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**為何重要:** +- `RecoveryMode.Relaxed` 可防止單一格式錯誤的段落中止整個轉換。 +- 提供 `FontSettings` 物件可確保缺少的字型能夠優雅地替代,這在之後將公式渲染為 LaTeX 時至關重要。 + +## 步驟 2 – 匯出為 Markdown(OfficeMath → LaTeX,圖片透過回呼) + +Markdown 本身沒有原生方式來表示 Word 公式。Aspose.Words 能將 **OfficeMath** 物件轉換為 LaTeX,這是大多數 Markdown 渲染器能理解的格式。然而,圖片必須儲存至某處;自訂的 **resource‑saving callback** 讓你完全掌控資料夾結構與命名方式。 + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### 資源儲存回呼 + +以下是一個簡短的實作,會將每張圖片存放於名為 `images` 的子資料夾,並以 `img001.png`、`img002.png` 等方式命名。 + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**為何需要這個回呼:** +- 若未使用回呼,Aspose.Words 會在同一層資料夾中產生隨機 GUID 名稱的檔案,導致版本控制變得混亂。 +- 透過自行控制命名規則,可保持 Markdown 倉庫整潔且可重現。 + +### 預期的 Markdown 輸出 + +執行後開啟 `doc.md`,你會看到: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +公式會以 LaTeX 形式包在 `$$ … $$` 中,圖片則會引用剛才建立的 `images` 資料夾。 + +## 步驟 3 – 匯出為 PDF/UA‑2(無障礙就緒) + +如果需要與依賴螢幕閱讀器或其他輔助技術的使用者分享文件,**PDF/UA‑2** 相容性是最佳標準。Aspose.Words 可透過單一旗標強制執行,且能將浮動圖形展平成內聯標籤,避免在轉換過程中遺失。 + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**為何 PDF/UA 重要:** +- PDF/UA(通用無障礙)保證產生的 PDF 具備正確的標記、合乎邏輯的閱讀順序,以及圖片的替代文字。 +- 設定 `ExportFloatingShapesAsInlineTag` 可確保文字方塊或註解等圖形不會被遺漏或錯位——這是轉換複雜版面時常見的問題。 + +### 驗證 PDF/UA 相容性 + +匯出後,於 Adobe Acrobat Pro 開啟 PDF,執行 **「Accessibility Check」**(工具 → 無障礙功能 → 完整檢查)。若工具回報 **0 個錯誤**,即表示成功。 + +## 邊緣情況與常見陷阱 + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word 檔案包含 **unsupported fonts** | 字型可能被替代,導致公式排版錯亂 | 提供自訂的 `FontSettings` 並設定備用字型。 | +| 大型文件(> 100 MB) | 轉換過程中記憶體壓力大 | 使用 `LoadOptions` 搭配 `LoadFormat.Docx` 並以串流方式讀取檔案。 | +| 圖片為 **EMF/WMF** 向量圖形 | 可能會被非預期地點陣化 | 在儲存前使用 `ImageSaveOptions` 轉換為 PNG。 | +| PDF/UA 在 **nested tables** 驗證失敗 | 標記可能變得模糊 | 啟用 `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` 以協助引擎處理。 | +| 需要 **preserve custom styles** | Markdown 的樣式功能有限 | 將 CSS 檔案與 Markdown 同時匯出並加以引用。 | + +## 完整範例(全部程式碼) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +執行程式後,你會在 `YOUR_DIRECTORY` 中找到 `doc.md`(包含 LaTeX 公式與整潔的圖片連結)以及 `doc.pdf`(完全符合 PDF/UA‑2 標準)。 + +## 視覺概覽 + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Alt text:* **convert word to markdown example** – 從 Word 檔案到 Markdown 與 PDF/UA 的轉換流程圖。 + +## 重點回顧與後續步驟 + +我們剛剛 **converted Word to Markdown**,同時保留了完整的公式,將圖片儲存於整潔的資料夾,並產生了通過無障礙檢查的 **save as PDF/UA** 檔案。主要重點如下: + +- 使用 `LoadOptions.RecoveryMode.Relaxed` 以容忍不完整的 Word 檔案。 +- 將 `OfficeMathExportMode` 設為 `LaTeX`,以獲得乾淨的公式呈現。 +- 實作 `ResourceSavingCallback` 以控制圖片輸出。 +- 啟用 `PdfCompliance.PdfUAXmpA2` 與 `ExportFloatingShapesAsInlineTag`,以產生符合標準的 PDF。 + +### 接下來可以探索的方向? + +- **Custom CSS for Markdown** – 產生與 Word 樣式相符的樣式表。 +- **Batch processing** – 迭代 `.docx` 目錄以自動化大量遷移。 +- **Advanced PDF/UA features** – 新增自訂標記、設定語言屬性,或嵌入音訊說明。 +- **Integration with CI/CD** – 確保每次建置自動產生無障礙 PDF。 + +如果遇到問題,請再次確認你的 Aspose.Words 版本與此處使用的 API 相符,並記得該函式庫的官方文件是可靠的次要參考資源。 + +祝開發順利,願你的文件同時保持美觀 **and** 無障礙! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/programming-with-txtsaveoptions/_index.md b/words/hongkong/net/programming-with-txtsaveoptions/_index.md index f16a5a9f45..2b053b28ac 100644 --- a/words/hongkong/net/programming-with-txtsaveoptions/_index.md +++ b/words/hongkong/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Aspose.Words for .NET 教學課程將引導您了解在操作 Word 文件的過 | [在 Word 文件中新增雙向標記](./add-bidi-marks/) |透過本指南了解如何使用 Aspose.Words for .NET 在 Word 文件中新增雙向 (Bidi) 標記。確保多語言內容的文字方向正確。 | | [每級使用製表符進行列表縮排](./use-tab-character-per-level-for-list-indentation/) |了解如何使用 Aspose.Words for .NET 建立帶有製表符縮排的多層清單。請遵循本指南在您的文件中進行精確的清單格式。 | | [每級使用空格字元進行列表縮排](./use-space-character-per-level-for-list-indentation/) |了解如何在 Aspose.Words for .NET 中建立帶有空格字元縮排的多層清單。精確文檔格式的逐步指南。 | - +| [將 docx 儲存為 txt – 使用 C# 匯出 Word 方程式為 LaTeX](./save-docx-as-txt-export-word-equations-to-latex-with-c/) |了解如何使用 Aspose.Words for .NET 將 Word 文件中的方程式匯出為 LaTeX 格式的文字檔,並儲存為 .txt。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hongkong/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/hongkong/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..cb4e2a10ea --- /dev/null +++ b/words/hongkong/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-04-05 +description: 使用 Aspose.Words 將 docx 儲存為 txt – 快速將 Word 轉換為 txt,並了解如何將數學公式匯出為 LaTeX。簡單的 + C# 程式碼,無需額外工具。 +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: zh-hant +og_description: 在 C# 中將 docx 儲存為 txt,並了解如何將數學公式匯出為 LaTeX。跟隨此一步一步的指引,將 Word 轉換為保留公式的 + txt。 +og_title: 將 docx 另存為 txt – 匯出 Word 方程式為 LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: 將 docx 儲存為 txt – 使用 C# 匯出 Word 方程式至 LaTeX +url: /zh-hant/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 將 docx 另存為 txt – 使用 C# 匯出 Word 方程式為 LaTeX + +有沒有曾經需要 **save docx as txt**,但擔心方程式會消失或變成無法辨識的亂碼?您並非唯一遇到這個問題的人。許多開發者在嘗試 **convert word to txt** 以供後續處理時,尤其是來源檔案包含 Office Math 物件時,都會卡在這裡。 + +好消息是?只要幾行 C# 程式碼加上正確的設定,您不僅可以 **convert Word to txt**,還能將每個方程式保留為乾淨的 LaTeX 標記。本教學將逐步說明整個流程、解釋每個設定的意義,並示範如何驗證結果。 + +我們將說明: + +* 安裝 Aspose.Words for .NET 套件 +* 載入包含數學方程式的 `.docx` +* 設定 `TxtSaveOptions`,讓 **how to export math** 以 LaTeX 友善的字串輸出 +* 儲存檔案並檢查輸出 + +完成後,您將擁有一段可重複使用的程式碼,讓您 **save docx as txt** 同時保留每個公式為 LaTeX——非常適合科學工作流程、靜態網站產生器,或任何需要純文字數學的情境。 + +--- + +## 前置條件 + +在開始之前,請確保您已具備: + +* .NET 6.0 或更新版本(此程式碼亦相容 .NET Framework 4.6 以上) +* Visual Studio 2022(或您慣用的任何 IDE) +* **Aspose.Words for .NET** NuGet 套件 – 以以下指令安裝 + +```bash +dotnet add package Aspose.Words +``` + +不需要額外的轉換器或外部工具;Aspose.Words 會在內部完成所有繁重的工作。 + +--- + +## 第一步:安裝並參考 Aspose.Words + +首先,將套件加入您的專案。若使用指令列,執行上方指令即可。於 Visual Studio 中,您也可以右鍵點選 **Dependencies → Manage NuGet Packages**,搜尋 *Aspose.Words*。 + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **專業小技巧:** 使用最新的穩定版(截至 2026 年 4 月為 24.10)。較新的版本修正了 OfficeMath 處理的錯誤,能避免出現意外的遺失符號。 + +--- + +## 第二步:載入來源文件 + +接下來,我們把包含方程式的 `.docx` 載入。`Document` 類別會抽象整個 Word 檔案,讓您可以存取文字、圖片與 Office Math 物件。 + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +為什麼要先載入?Aspose.Words 會將檔案解析成物件模型,讓我們在決定如何匯出之前,先檢查或修改內容。這也是 **how to export math** 的決策開始發揮作用的地方。 + +--- + +## 第三步:設定 TxtSaveOptions 以 LaTeX 匯出 + +解決方案的核心是 `TxtSaveOptions` 類別。預設情況下,儲存為 TXT 會完全移除 Office Math。將 `OfficeMathExportMode` 設為 `LaTeX`,即可指示程式庫將每個方程式轉換為 LaTeX 表示。 + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**為什麼選 LaTeX?** LaTeX 是科學出版的通用語言。以此方式匯出數學式,能保留方程式的語意,而不是平面影像或亂碼字串。若之後將 TXT 交給支援 MathJax 的 Markdown 處理器,方程式將能完美渲染。 + +--- + +## 第四步:將文件儲存為純文字 + +設定完成後,只需一行程式碼即可將檔案寫入磁碟。 + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +就這樣——您的 `.docx` 現在已變成 `.txt`,每個方程式皆以 LaTeX 片段呈現,隨時可供後續使用。 + +--- + +## 驗證輸出(如何正確儲存 txt) + +在任意文字編輯器中開啟 `MathSample.txt`,您應該會看到類似以下的內容: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +如果看到原生 Word 的特殊字元(例如 `?` 或遺失的符號),請再次確認: + +* 您使用的是較新版的 Aspose.Words(舊版曾有 OfficeMath 的 Bug)。 +* 來源文件確實包含 **OfficeMath** 物件,而非舊版 Equation Editor 物件。若是後者,可能需要先手動轉換,或在儲存前呼叫 `ConvertMathToOfficeMath` 方法。 + +--- + +## 常見變化與邊緣案例 + +| 情境 | 處理方式 | +|-----------|------------| +| **舊版 Equation Editor 物件** | 在第 3 步之前呼叫 `doc.ConvertMathToOfficeMath()`。 | +| **需要純 Unicode 數學,而非 LaTeX** | 設定 `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`。 | +| **大型文件(100 + MB)** | 使用 `doc.Save(Stream, txtOptions)` 以串流方式儲存,降低記憶體使用。 | +| **想保留原始檔名** | 在組合輸出路徑時使用 `Path.GetFileNameWithoutExtension(inputPath) + ".txt"`。 | + +這些調整可回應不同管線對 **how to export math** 的需求,確保您的解決方案在任何來源下都具備韌性。 + +--- + +## 完整範例(一次完成所有步驟) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +執行程式後,開啟產生的 `.txt`,您會看到 LaTeX 方程式正好嵌入在原本的位置。這是最直接、最簡單的方式來 **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hongkong/net/working-with-fonts/_index.md b/words/hongkong/net/working-with-fonts/_index.md index 8984baa9aa..cd42c0e4b8 100644 --- a/words/hongkong/net/working-with-fonts/_index.md +++ b/words/hongkong/net/working-with-fonts/_index.md @@ -1,5 +1,5 @@ --- -"description": "使用字體進行文字處理教學教您如何使用 Aspose.Words for .NET 在 Word 中處理字體。格式化、替換、通知等等。" +"description": "使用字體進行文字處理教您如何使用 Aspose.Words for .NET 在 Word 中處理字體。格式化、替換、通知等等。" "linktitle": "使用字型進行文字處理" "second_title": "Aspose.Words文件處理API" "title": "使用字型進行文字處理" @@ -45,6 +45,7 @@ | [字體設定預設實例](./font-settings-default-instance/) |在本教學中,學習如何使用 Aspose.Words for .NET 在 Word 文件中配置預設字體設定。 | | [取得可用字體列表](./get-list-of-available-fonts/) |在本詳細的逐步教學中了解如何使用 Aspose.Words for .NET 取得可用字體清單。提升您的字體管理技能。 | | [接收字體通知](./receive-notifications-of-fonts/) |了解如何在使用 Aspose.Words for .NET 時接收遺失或取代的字體通知。 | +| [Aspose 字體替換 – 偵測 Word 文件中缺少的字體](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) |了解如何使用 Aspose.Words for .NET 偵測 Word 文件中缺少的字體並進行字體替換。 | | [接收警告通知](./receive-warning-notification/) |了解如何在使用 Aspose.Words for .NET 時接收警告通知並管理文件中的任何問題或警告。 | | [資源 Steam 字體來源範例](./resource-steam-font-source-example/) |了解如何使用資源流字體來源將自訂字體載入到 Aspose.Words for .NET 中。 | | [取得不含後綴的替換](./get-substitution-without-suffixes/) |在本教學中,學習如何使用 Aspose.Words for .NET 在 Word 文件中取得無後綴覆蓋。 | diff --git a/words/hongkong/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/hongkong/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..112dee56f9 --- /dev/null +++ b/words/hongkong/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-04-05 +description: Aspose 字型替換指南:在載入 Word 文件時偵測缺失的字型。學習如何設定字型參數,並有效處理缺失的字型。 +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: zh-hant +og_description: Aspose 字體置換指南:在載入 Word 文件時偵測缺失字體。學習如何設定字體設定並有效處理缺失字體。 +og_title: Aspose 字體替換 – 檢測 Word 文件中缺失的字體 +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose 字型替換 – 偵測 Word 文件中缺失的字型 +url: /zh-hant/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose 字型替換 – 偵測 Word 文件中缺少的字型 + +有沒有遇過同一個 Word 檔在一台機器上顯示正常,卻在另一台機器上出現奇怪的字型變更?這就是經典的 **aspose font substitution** 問題,通常代表目標系統缺少某些字型。在本教學中,我們將一步一步示範如何在 **載入 Word 文件** 時 **偵測缺少的字型**、如何 **設定字型選項**,以及如何優雅地 **處理缺少的字型**。 + +我們會走過完整、可執行的 C# 範例,說明每一行程式碼的意義,並展示預期的主控台輸出。完成後,你將能在文件載入的瞬間即發現字型替換,無需猜測。 + +## 你將學到 + +- 如何為 Aspose.Words 啟用字型警告的診斷收集器。 +- 載入 Word 文件時使用自訂 **字型設定** 的完整程式碼。 +- 如何遍歷 `WarningInfo` 物件以列出每一個被替換的字型。 +- 抑制不必要警告或提供備用字型的技巧。 +- 可直接複製貼上到 Visual Studio 的即用範例。 + +### 前置條件 + +- .NET 6.0 或更新版本(在 .NET Framework 上的 API 行為相同)。 +- Aspose.Words for .NET(NuGet 套件 `Aspose.Words`)。 +- 一個引用了你未安裝字型的 Word 檔(例如 `MissingFont.docx`)。 + +如果你已具備上述條件,讓我們開始吧。 + +## 第一步 – 啟用診斷收集器(設定字型選項) + +首先要先讓 Aspose.Words 記錄字型替換警告,必須建立 `FontSettings` 物件並指派給 `LoadOptions` 實例。這就像為字型處理開啟「除錯燈」一樣。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**為什麼要這樣做?** +如果沒有 `FontSettings` 物件,警告收集器會保持沉默,你永遠不會知道哪些字型被替換。將它以空設定初始化,我們就讓 Aspose 使用預設系統字型 *同時* 追蹤任何替換情況。 + +> **專業提示:** 若你知道某個資料夾內有公司字型,可使用 `SetFontsFolder("path")` 指向該資料夾,這樣可以減少缺少字型的警告數量。 + +## 第二步 – 使用已設定的選項載入文件(載入 Word 文件) + +收集器啟動後,使用相同的 `LoadOptions` 載入 `.docx` 檔。此時 Aspose 會掃描文件、檢查每一個字型參考,並決定是否需要替換。 + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**這有什麼重要性?** +如果直接呼叫 `new Document("MissingFont.docx")`,會套用預設設定,且警告清單會保持空白。傳入 `loadOptions` 可確保診斷收集器已掛接到載入流程中。 + +## 第三步 – 取得並顯示字型替換警告(偵測缺少的字型) + +文件載入記憶體後,Aspose 會將警告存於 `document.WarningCallback.Warnings`。遍歷此集合,篩選 `WarningType.FontSubstitution`,並印出說明文字。每條說明都會告訴你哪個字型缺失、使用了哪個備用字型。 + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**預期的主控台輸出** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +這段輸出會精確告訴執行程式的機器缺少哪些字型。接著你可以決定是安裝缺少的字型、將其嵌入文件,或是保留替換結果。 + +![顯示 Aspose 字型替換警告的主控台輸出](/images/aspose-font-substitution-console.png) + +*圖片說明:* aspose 字型替換 – 主控台輸出列出被替換的字型 + +## 第四步 – 可選:自訂替換行為(處理缺少的字型) + +有時候你不只想知道 *發生了* 替換,還想控制 *如何* 替換。Aspose.Words 允許你註冊自訂的 `IFontSubstitutionRule`。以下範例會將所有缺少的字型強制回退至 `Tahoma`。 + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**什麼情況下會使用這個?** +如果你為 Web 服務產生 PDF,且知道所有客戶端都能正確渲染 `Tahoma`,強制回退可保證視覺一致性,且不必攜帶大量字型檔案。 + +## 完整可執行範例(結合所有步驟) + +以下是可直接貼到新 Console 專案的完整程式碼。只要已安裝 Aspose.Words NuGet 套件,即可直接編譯執行。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +執行程式,觀察主控台,即可看到每一次缺少字型的事件被列印出來。之後你可以決定是安裝缺少的字型、將其嵌入,或是保留回退設定。 + +## 常見問題 + +**Q: 這能用於 PDF 轉換嗎?** +可以。當你稍後呼叫 `doc.Save("output.pdf")` 時,載入期間被替換的字型會被嵌入 PDF。因此提前捕捉警告可避免最終 PDF 出現意外的字型變更。 + +**Q: 若要處理大量文件該怎麼做?** +將載入邏輯包在 try‑catch 區塊內,並在多個文件之間重複使用同一個 `FontSettings` 實例。這樣可減少開銷,且每個檔案都會保有警告收集器。 + +**Q: 能完全抑制警告嗎?** +可以在載入前設定 `loadOptions.WarningCallback = null;`,但這會失去 **偵測缺少字型** 的能力——通常不是你想要的結果。 + +## 結論 + +我們已完整說明如何掌握 **aspose font substitution**:啟用診斷收集器、使用自訂 **字型設定** 載入 Word 檔、擷取缺少字型清單,甚至覆寫預設的替換規則以 **自行處理缺少的字型**。只需幾行 C# 程式碼,即可獲得對字型問題的完整可視性,避免因隱藏的版面變化而產生困擾。 + +接下來的步驟?試著使用 `FontSettings.SetFontsFolder` 將原始字型嵌入文件,或探索 `FontSourceBase` 從資料庫載入字型。你也可以實驗 `Document.BuiltInStyle` 集合,觀察樣式層級的字型變更如何傳遞。 + +對 Aspose.Words 或字型管理還有其他疑問嗎?歡迎留言、參考官方 Aspose 文件,或開啟新專案親自玩玩上面的程式碼。祝開發順利,文件永遠如你所願正確呈現! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/basic-conversions/_index.md b/words/hungarian/net/basic-conversions/_index.md index e6951319a2..52fddb2499 100644 --- a/words/hungarian/net/basic-conversions/_index.md +++ b/words/hungarian/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Az Alapvető konverziók című útmutató végigvezeti Önt az Aspose.Words for | [LaTeX exportálása Wordből – Lépésről‑lépésre útmutató](./how-to-export-latex-from-word-step-by-step-guide/) | Tanulja meg, hogyan exportálhat LaTeX-et Word dokumentumokból az Aspose.Words for .NET segítségével, részletes lépésekkel. | | [Word konvertálása PDF-be C#-ban az Aspose.Words – Útmutató](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Tanulja meg, hogyan konvertálhat Word dokumentumokat PDF-be C#-ban az Aspose.Words használatával. | | [Word mentése PDF-be az Aspose.Words segítségével – Teljes C# útmutató](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Tanulja meg, hogyan menthet Word dokumentumokat PDF-be C#-ban az Aspose.Words használatával, részletes lépésekkel. | +| [Word konvertálása PDF-be C#-ban – Teljes útmutató az Aspose.Words használatával](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Tanulja meg, hogyan konvertálhat Word dokumentumokat PDF-be C#-ban az Aspose.Words teljes útmutatójával. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/hungarian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..b8f7ecf3e9 --- /dev/null +++ b/words/hungarian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,196 @@ +--- +category: general +date: 2026-04-05 +description: Word konvertálása PDF-be C#-ban az Aspose.Words használatával. Tanulja + meg, hogyan mentse el a docx-et PDF-ként, exportáljon hozzáférhető PDF-et, és töltse + be a Word-dokumentumot hatékonyan. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: hu +og_description: Konvertálja a Word dokumentumot PDF-re C#-ban lépésről lépésre útmutatóval. + Tudja meg, hogyan menthet docx-et PDF-ként, exportálhat hozzáférhető PDF-et, és + hogyan tölthet be Word dokumentumot az Aspose.Words segítségével. +og_title: Word konvertálása PDF‑be C#‑ban – Teljes Aspose.Words útmutató +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Word konvertálása PDF-be C#‑ban – Teljes útmutató az Aspose.Words‑szal +url: /hu/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word konvertálása PDF-be C#-ban – Teljes programozási útmutató + +Gondolkodtál már azon, hogyan **Word PDF‑re konvertálása** anélkül, hogy bonyolult parancssori eszközökkel vagy harmadik fél szolgáltatásaival kellene küzdened? Nem vagy egyedül. Sok fejlesztő szembesül ezzel a problémával, amikor egy ügyfél egy hozzáférhető PDF-et kér közvetlenül egy DOCX fájlból. A jó hír? Néhány C# sorral és az erőteljes Aspose.Words könyvtárral egy Word dokumentumot szabvány‑megfelelő PDF‑vé alakíthatsz pillanatok alatt. + +Ebben az útmutatóban mindent végigvázolunk, amit tudnod kell: a **Word dokumentum betöltése** alapjaitól, a megfelelő beállítások konfigurálásán át a **hozzáférhető PDF exportálása**‑ig, és végül az eredmény mentéséig, hogy megbízhatóan **DOCX mentése PDF‑ként**. A végére egy kész, futtatható kódrészletet kapsz, amelyet bármely .NET projektbe beilleszthetsz. + +> **Pro tipp:** Ha a PDF/UA‑2 megfelelőségre (az a hozzáférhetőségi szabvány, amelyet sok kormányzati ügynökség megkövetel) törekszel, ugyanaz a kód működik extra lépések nélkül – csak állítsd be a megfelelő `PdfCompliance` zászlót. + +## Mit fogsz megtanulni + +- Hogyan **Word dokumentum betöltése** az Aspose.Words segítségével C#-ban. +- A pontos beállítások, amelyek szükségesek a **hozzáférhető PDF exportálása**‑hoz (PDF/UA‑2). +- Egy teljes, futtatható példa, amely **DOCX mentése PDF‑ként** egy metódushívással. +- Gyakori buktatók, amikor **C#‑ban DOCX‑et PDF‑re konvertálás** és hogyan kerülhetők el. +- Gyors módszerek annak ellenőrzésére, hogy a generált PDF megfelel-e a hozzáférhetőségi elvárásoknak. + +Nincs külső eszköz, nincs rejtett konfigurációs fájl – csak tiszta C# kód, amelyet ma lefordíthatsz. + +## Előfeltételek + +Mielőtt belemerülnénk, győződj meg róla, hogy rendelkezel: + +1. **.NET 6.0** (vagy bármely friss .NET verzió) telepítve. Régebbi keretrendszerek is működnek, de az alábbi szintaxis a modern SDK-t feltételezi. +2. Egy **licenc** az Aspose.Words for .NET-hez. A könyvtár ingyenes próbaverziót kínál, de a produkcióhoz érvényes kulcsra lesz szükséged. +3. A **Aspose.Words** NuGet csomag hozzáadva a projektedhez: + +```bash +dotnet add package Aspose.Words +``` + +Ennyi – nincs további bináris, nincs COM interop, csak egy tiszta NuGet hivatkozás. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## Lépésről‑lépésre megvalósítás + +Az alábbiakban a folyamatot logikai egységekre bontjuk. Minden lépés egy kis kódrészletet, egy magyarázatot arra, hogy **miért** fontos, és egy a valós használatból származó tippet tartalmaz. + +### ## Word PDF‑re konvertálása – A forrásdokumentum betöltése + +Az első dolog, amit meg kell tenned, hogy **Word dokumentum betöltése** a memóriába. Az Aspose.Words elrejti az OpenXML feldolgozást, így DOCX, DOC vagy akár RTF fájlokkal is dolgozhatsz anélkül, hogy a formátum sajátosságai miatt aggódnál. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Miért fontos:** +A fájl betöltése egy `Document` objektumot hoz létre, amely a teljes Word fájlt képviseli, beleértve a fejlécet, láblécet, stílusokat és a rejtett metaadatokat. Ha kihagyod ezt a lépést, vagy nyers adatfolyamként próbálod olvasni a fájlt, elveszíted a később a PDF megjelenését meghatározó elrendezési információkat. + +> **Megjegyzés:** Ugyanaz a `Document` konstruktor működik `.doc` és `.rtf` esetén is. Ez azt jelenti, hogy **C#‑ban DOCX‑et PDF‑re konvertálás** akkor is lehetséges, ha a forrás nem kifejezetten DOCX. + +### ## DOCX mentése PDF‑ként – PDF/UA‑2 megfelelőség beállítása + +Miután a dokumentum a memóriában van, megmondjuk az Aspose.Words‑nek, hogyan szeretnénk, hogy a PDF generálódjon. A legtöbb esetben az alapértelmezett beállítások megfelelőek, de ha **hozzáférhető PDF**‑re van szükséged, engedélyezned kell a PDF/UA‑2 megfelelőség zászlót. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Miért fontos:** +A `PdfCompliance.PdfUAXmpA2` azt mondja a könyvtárnak, hogy ágyazza be a képernyőolvasók által igényelt címkéket és struktúrákat. Enélkül a zászló nélkül egy tökéletesen kinéző PDF-et kaphatsz, amely nem felel meg a hozzáférhetőségi ellenőrzésnek. + +> **Tipp:** Ha csak egy normál PDF-re van szükséged, elhagyhatod a `Compliance` sort. A többi beállítás továbbra is magas minőségű kimenetet biztosít. + +### ## Word PDF‑re konvertálása – A fájl írása + +Az opciók készen állnak, az utolsó lépés a **DOCX mentése PDF‑ként**. Ez az egyetlen hívás végzi el a nehéz munkát: az elrendezés konvertálása, a betűkészletek beágyazása és a hozzáférhetőségi címkézés. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Mit kapsz:** +- Egy PDF fájl a `outputPath` helyen, amely tükrözi a Word elrendezését. +- Ha a `PdfUAXmpA2` zászlót használtad, a PDF PDF/UA‑2‑nek minősül. +- Minden betűkészlet be van ágyazva, így a fájl bármely gépen azonosul. + +### ## A hozzáférhető PDF ellenőrzése (Opcionális, de ajánlott) + +A konvertálás után jó ötlet duplán ellenőrizni, hogy a PDF valóban **hozzáférhető PDF exportálása**‑t hajtja-e végre helyesen. Használhatsz ingyenes eszközöket, például az Adobe Acrobat Reader „Accessibility Check” funkcióját vagy a nyílt forráskódú `pdfcpu` validátort. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Ha a validátor hibátlanul jelent, akkor sikeresen **Word PDF‑re konvertálása**‑t hajtottál végre teljes hozzáférhetőségi támogatással. + +### ## Gyakori buktatók C#‑ban DOCX‑et PDF‑re konvertálásakor + +| Probléma | Miért fordul elő | Megoldás | +|----------|------------------|----------| +| Hiányzó betűkészletek | A forrás DOCX egy egyedi betűkészletet használ, amely nincs telepítve a szerveren. | Állítsd be `EmbedFullFonts = true` vagy telepítsd a betűkészletet a gépre. | +| Nagy fájlméret | A képek teljes felbontásban vannak beágyazva. | Használd a `ImageCompression = PdfImageCompression.Jpeg` beállítást, és állítsd alacsonyabbra a `JpegQuality` értéket. | +| Törött hiperhivatkozások | A hivatkozások relatív útvonalakra mutatnak, amelyek a kliensen nem léteznek. | Győződj meg róla, hogy az URL-ek abszolútak, vagy állítsd be a `HyperlinkTarget` tulajdonságot. | +| Hiányzó hozzáférhetőségi címkék | `Compliance` zászló nincs beállítva. | Add hozzá a `Compliance = PdfCompliance.PdfUAXmpA2` beállítást, ahogy fent látható. | + +Ezeket szem előtt tartva a **C#‑ban DOCX‑et PDF‑re konvertálás** rutinod robusztus és produkcióra kész lesz. + +## Teljes működő példa + +Összegezve, itt egy önálló konzolalkalmazás, amelyet most lefordíthatsz és futtathatsz. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Várt eredmény:** A program futtatása után megtalálod az `output.pdf` fájlt a `C:\Docs` mappában. Nyisd meg bármely PDF‑olvasóval; az elrendezésnek pixel‑ponton egyeznie kell az `input.docx`‑vel, és egy hozzáférhetőségi ellenőrzés megerősíti a PDF/UA‑2 megfelelőséget. + +## Következtetés + +Most végigvettünk egy teljes, vég‑a‑vég megoldást arra, hogyan **Word PDF‑re konvertálása** C# és Aspose.Words segítségével. A **Word dokumentum betöltése**, a megfelelő `PdfSaveOptions` konfigurálása, majd végül a **DOCX mentése PDF‑ként** révén magas minőségű, hozzáférhető PDF-et kapsz minimális kóddal. Akár dokumentum‑generáló mikroszolgáltatást építesz, akár helyi kötegelt konvertálót, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/_index.md index a6a760349e..c3a84352dc 100644 --- a/words/hungarian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/hungarian/net/programming-with-markdownsaveoptions/_index.md @@ -37,6 +37,10 @@ Ismerje meg, hogyan mentheti el a DOCX fájlokat Markdown formátumba lépésrő Ismerje meg, hogyan exportálhatja a Word dokumentumokat Markdown formátumba egy teljes C# útmutatóval. ### [Hogyan exportáljunk Markdownot DOCX‑ből – Teljes útmutató](./how-to-export-markdown-from-docx-complete-guide/) Ismerje meg, hogyan exportálhatja a DOCX fájlokat Markdown formátumba egy teljes útmutatóval. +### [DOCX konvertálása Markdownba – Képek kinyerése a DOCX-ből Aspose.Words segítségével](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Ismerje meg, hogyan nyerhet ki képeket a DOCX fájlokból és konvertálhatja őket Markdownba az Aspose.Words for .NET segítségével. +### [Word konvertálása Markdownba – Teljes útmutató PDF/UA exporttal](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +Ismerje meg, hogyan konvertálhatja a Word dokumentumokat Markdownba, és exportálhatja PDF/UA formátumban az Aspose.Words for .NET segítségével. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..69ac321238 --- /dev/null +++ b/words/hungarian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-04-05 +description: Tanulja meg, hogyan konvertálja a DOCX-et Markdownra, és hogyan nyerjen + ki képeket a DOCX-ből C#-ban. Lépésről‑lépésre útmutató teljes kóddal és tippekkel. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: hu +og_description: Konvertálja a DOCX-et Markdown formátumba, és nyerjen ki képeket a + DOCX-ből az Aspose.Words segítségével. Teljes C# oktatóanyag kóddal, magyarázattal + és legjobb gyakorlat tippekkel. +og_title: DOCX konvertálása Markdownra – Képek kinyerése DOCX‑ből C#‑ban +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX konvertálása Markdownra – Képek kinyerése a DOCX‑ből az Aspose.Words segítségével +url: /hu/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX konvertálása Markdown formátumba – Képek kinyerése DOCX‑ből C#‑ban + +Valaha szükséged volt **DOCX konvertálására Markdown formátumba**, de nehezen tudtad kezelni, hogy a képek eltűnnek a kimenetben? Nem vagy egyedül. Sok projektben a markdown verzió tökéletes a verziókezeléshez vagy a statikus weboldalgenerátorokhoz, ám a képek hátramaradnak, így egy gazdag dokumentum egy sivár szövegfájl lesz. + +A jó hír? Néhány C#‑os sorral és az Aspose.Words‑szal **DOCX‑t konvertálhatsz Markdown‑ba** *és* **kibonthatod a képeket a DOCX‑ből** automatikusan. Ez az útmutató végigvezet a teljes folyamaton, elmagyarázza, miért fontos minden lépés, és még azt is megmutatja, hogyan tarthatod rendben a képmappádat. + +## Amit megtanulsz + +- Hogyan tölts be egy képeket tartalmazó DOCX‑et. +- Hogyan definiálj egy egyedi `IResourceSavingCallback`‑et, amely meghatározza, hová kerül minden kép. +- Hogyan konfiguráld a `MarkdownSaveOptions`‑t, hogy a generált markdown helyesen hivatkozzon a kinyert képekre. +- Tippek a szélhelyzetek kezeléséhez, például duplikált képnév vagy nem‑PNG formátumok esetén. +- Egy teljes, másolás‑beillesztés kész kódminta, amelyet már ma futtathatsz. + +### Előfeltételek + +- .NET 6.0 vagy újabb (az API működik .NET Core, .NET Framework és .NET 5+ környezetben). +- Licenc a **Aspose.Words for .NET**‑hez (az ingyenes próba verzió teszteléshez elegendő). +- Alapvető ismeretek C#‑ban és Visual Studio‑ban (vagy a kedvenc IDE‑dben). + +Ha ezek megvannak, merüljünk el benne. + +--- + +## 1. lépés: A projekt beállítása és az Aspose.Words telepítése + +Először hozz létre egy új konzolalkalmazást (vagy integráld egy meglévő megoldásba). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tipp:** Használd a legújabb NuGet verziót (2026. április állása szerint ez a 24.12), hogy megkapd a legújabb markdown export fejlesztéseket. + +--- + +## 2. lépés: Callback létrehozása a képek mentéséhez a kívánt helyre + +Az Aspose.Words lehetővé teszi, hogy minden erőforrást (képek, SVG‑k stb.) elfogj, amely a markdown export során íródik. A `IResourceSavingCallback` implementálásával a következőket teheted: + +1. Válassz egy mappát, amely a markdown fájlod mellett helyezkedik el. +2. Generálj egy egyedi fájlnevet (így soha nem írsz felül egy már létező képet). +3. Döntsd el a formátumot (itt a konzisztencia kedvéért PNG‑t kényszerítünk). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Miért GUID‑alapú név? + +Ha a forrás DOCX két azonos eredeti névvel rendelkező képet tartalmaz, egy egyszerű másolás‑beillesztés felülírná az egyiket. A `Guid.NewGuid()` használata garantálja az egyediséget, ami különösen hasznos, ha a konverziót sokszor futtatod egy automatizált folyamatban. + +--- + +## 3. lépés: A DOCX betöltése és a Markdown beállítások összekapcsolása + +Most betöltjük a dokumentumot a memóriába, és csatoljuk a most létrehozott callback‑et. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Mit csinál a kód lépésről lépésre + +| Lépés | Cél | +|------|-----| +| **Útvonalak meghatározása** | Rugalmasan tartja a projektet; bármelyik mappára mutathatsz újrafordítás nélkül. | +| **DOCX betöltése** | A `Document` beolvassa a Word fájlt, így minden elem (bekezdések, táblázatok, képek) elérhetővé válik. | +| **`MarkdownSaveOptions` konfigurálása** | A `ResourceSavingCallback` az a horog, amely kinyeri a képeket. Enélkül az Aspose.Words vagy beágyazza a képeket base64‑ként, vagy teljesen elhagyja őket a beállításoktól függően. | +| **Mentés** | A `doc.Save` kiírja a markdown fájlt, és minden képhez meghívja a callback‑et. | + +--- + +## 4. lépés: A kimenet ellenőrzése – Mit kell látnod? + +A program futtatása után nyisd meg a `DocWithImages.md` fájlt. Olyan markdown kép hivatkozásokat fogsz látni, mint ez: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +És a `C:\Docs\MarkdownResources` mappában egy sor PNG fájlt találsz GUID‑nevekkel. Nyisd meg bármelyiket – azonosnak kell lennie az eredeti DOCX‑ben beágyazott képekkel. + +Ha a markdown fájlt egy relatív útvonalakat tiszteletben tartó nézőben nyitod meg (pl. VS Code előnézet, GitHub vagy egy statikus weboldalgenerátor), a képek úgy fognak megjelenni, ahogy a Word‑ben voltak. + +### Gyakori hibák és hogyan kerüld el őket + +| Tünet | Valószínű ok | Javítás | +|-------|--------------|---------| +| A képek törött hivatkozásként jelennek meg | A `ResourceFileName` nem lett beállítva, ezért a markdown egy nem létező fájlra mutat. | Győződj meg róla, hogy a callback‑ben `args.ResourceFileName = newFileName;` legyen beállítva. | +| A PNG fájlok hatalmasak | Az eredeti képek JPEG vagy BMP formátumúak voltak; a PNG‑re konvertálás növelheti a méretet. | Detektáld az eredeti formátumot a `args.ResourceContentType`‑on keresztül, és őrizd meg: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplikált képek továbbra is megjelennek | Statikus fájlnevet használtál GUID helyett. | Válts vissza GUID logikára, vagy adj egy számlálót képtípusonként. | +| A konverzió `FileNotFoundException`‑t dob | A forrás DOCX útvonala hibás vagy a mappának nincs olvasási joga. | Ellenőrizd az útvonalat, és biztosíts megfelelő fájlrendszeri jogosultságokat. | + +--- + +## 5. lépés: Haladó finomhangolások (opcionális) + +### 5.1 Eredeti képformátumok megőrzése + +Ha azt szeretnéd, hogy a kimeneti képek megtartsák az eredeti kiterjesztésüket, módosítsd a callback‑et: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Képek beágyazása Base64‑ként (ha *nem* szeretnél külön fájlokat) + +Néha egy egyetlen fájlból álló markdown előnyösebb (pl. e‑mailben való küldéshez). Változtasd meg a beállítást: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +De ne feledd: **kép kinyerése a DOCX‑ből** a legtöbb statikus weboldal munkafolyamat elsődleges célja, így a mappa‑megoldás általában jobb választás. + +--- + +## Teljes működő példa (másolás-beillesztés kész) + +Az alábbiakban egyetlen fájlban látható a teljes program. Csak cseréld le az útvonalakat a sajátodra, és futtasd. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Futtasd a `dotnet run` paranccsal. Amikor a konzol kiírja a ✅ sort, nyisd meg a markdown fájlt, és a képeknek helyesen kell megjelenniük. + +--- + +## Összegzés + +Most már rendelkezel egy **teljes, production‑kész megoldással a DOCX‑ről Markdown‑ra konvertáláshoz és a képek kinyeréséhez a DOCX‑ből** az Aspose.Words C#‑os használatával. A fő kulcsszó végig jelen van az útmutatóban, erősítve a relevanciát mind a keresőmotorok, mind az AI asszisztensek számára. + +Egyetlen lépésben a kód: + +1. Betölti a Word dokumentumot. +2. Elfog minden képet a `IResourceSavingCallback`‑en keresztül. +3. Minden képet egy előre meghatározott mappába ment egyedi névvel. +4. Olyan markdown‑t generál, amely hivatkozik ezekre a képekre. + +Innen tovább: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/hungarian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..42151f8898 --- /dev/null +++ b/words/hungarian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-04-05 +description: Gyorsan konvertálj Word dokumentumot Markdown formátumba, és tanuld meg, + hogyan mentheted PDF/UA formátumban C#‑ban. Lépésről‑lépésre kód, tippek és szélső + esetek kezelése. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: hu +og_description: Konvertálja a Word dokumentumot Markdown formátumba, és mentse PDF/UA + formátumban az Aspose.Words segítségével. Ismerje meg a miértet, a hogyan-t, és + a legjobb gyakorlatok tippeit egy tömör útmutatóban. +og_title: Word konvertálása Markdownra – Teljes C# oktatóanyag +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word konvertálása Markdownra – Teljes útmutató PDF/UA exporttal +url: /hu/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word konvertálása Markdown formátumba – Teljes útmutató PDF/UA exporttal + +Gondoltad már, hogyan **konvertálhatod a Word dokumentumot Markdown‑ba** anélkül, hogy az egyenletek vagy képek elvesznének? Nem vagy egyedül. Sok fejlesztőnek megbízható módra van szüksége, hogy a `.docx` fájlokat tiszta Markdown‑ba alakítsa, miközben **PDF/UA‑ként is mentheti** a hozzáférhetőségi követelményeknek megfelelő PDF‑eket. Ebben a tutorialban végigvezetünk egy teljes, azonnal futtatható megoldáson az Aspose.Words for .NET használatával, elmagyarázzuk, miért fontos minden beállítás, és megmutatjuk, hogyan kezeld a bonyolultabb részeket, mint az OfficeMath és a lebegő alakzatok. + +A útmutató végére egyetlen C# programod lesz, amely: + +1. Betölti a Word dokumentumot lazított helyreállítással (így a sérült fájlok sem állítják le a futást). +2. Exportálja azt Markdown‑ba, az egyenleteket LaTeX‑re alakítva, a képeket egy egyedi callback‑en keresztül tárolja. +3. Ugyanezt a dokumentumot PDF/UA‑2 kompatibilis fájlként menti, a lebegő alakzatokat inline címkékként ágyazza be. + +Jól hangzik? Semmi gond—merüljünk el benne. + +## Amire szükséged lesz + +- **Aspose.Words for .NET** (legújabb verzió, 23.x a cikk írásakor). +- .NET fejlesztői környezet (Visual Studio 2022, Rider vagy a `dotnet` CLI). +- Egy minta Word fájl (`input.docx`) egy olyan mappában, amelyre hivatkozhatsz. +- Alapvető ismeretek a C# szintaxisról—semmi egzotikus, csak néhány `using` utasítás. + +> **Pro tipp:** Ha NuGet csomagkezelőt használsz, add hozzá a könyvtárat a következővel +> `dotnet add package Aspose.Words` vagy a Visual Studio NuGet UI‑ján keresztül. + +## 1. lépés – A Word dokumentum betöltése lazított helyreállítással + +Amikor külső forrásból származó Word fájlokat kapsz, azok kisebb sérüléseket is tartalmazhatnak. A **Relaxed** helyreállítás engedélyezése azt mondja az Aspose.Words‑nek, hogy folytassa a feldolgozást ahelyett, hogy kivételt dobna. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Miért fontos ez:** +- A `RecoveryMode.Relaxed` megakadályozza, hogy egyetlen hibás bekezdés leállítsa az egész konverziót. +- A `FontSettings` objektum megadása biztosítja, hogy a hiányzó betűtípusok elegánsan helyettesítve legyenek, ami elengedhetetlen az egyenletek LaTeX‑re történő rendereléséhez. + +## 2. lépés – Exportálás Markdown‑ba (OfficeMath → LaTeX, képek callback‑en keresztül) + +A Markdown natívan nem tudja ábrázolni a Word egyenleteket. Az Aspose.Words képes a **OfficeMath** objektumokat LaTeX‑re fordítani, amit a legtöbb Markdown renderelő ért. A képeket azonban valahová el kell menteni; egy egyedi **resource‑saving callback** teljes kontrollt ad a mappaszerkezet és a névadás felett. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### A resource‑saving callback + +Az alábbi kis megvalósítás minden képet egy `images` almappába ment, és a fájlokat `img001.png`, `img002.png` stb. néven nevezve. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Miért van rá szükséged:** +- Callback nélkül az Aspose.Words egy lapos mappát hoz létre véletlenszerű GUID nevekkel, ami a verziókezelést nehezíti. +- A névadási séma irányításával a Markdown tároló rendezett és reprodukálható marad. + +### Várható Markdown kimenet + +Nyisd meg a `doc.md` fájlt a futtatás után, és a következőt fogod látni: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Az egyenletek LaTeX‑ként jelennek meg `$$ … $$` közé zárva, a képek pedig a most létrehozott `images` mappára hivatkoznak. + +## 3. lépés – Exportálás PDF/UA‑2‑re (hozzáférhetőség‑kész) + +Ha olyan felhasználókkal kell megosztanod a dokumentumot, akik képernyőolvasót vagy más segédeszközt használnak, a **PDF/UA‑2** megfelelőség a legmagasabb szint. Az Aspose.Words egyetlen flag‑gel képes ezt érvényesíteni, és a lebegő alakzatokat inline címkékké is laposíthatja, hogy ne vesszenek el a konverzió során. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Miért fontos a PDF/UA:** +- A PDF/UA (Universal Accessibility) garantálja, hogy a létrehozott PDF megfelelő címkézést, logikus olvasási sorrendet és alternatív szöveget tartalmaz a képekhez. +- Az `ExportFloatingShapesAsInlineTag` beállítás biztosítja, hogy a szövegdobozok vagy felhívások ne legyenek kihagyva vagy rossz helyre kerülve – ez gyakori hiba összetett elrendezések konvertálásakor. + +### PDF/UA megfelelőség ellenőrzése + +Az export után nyisd meg a PDF‑et az Adobe Acrobat Pro‑ban, és futtasd a **„Accessibility Check”**‑et (Tools → Accessibility → Full Check). Ha az eszköz **0 hibát** jelent, sikerült. + +## Szélsőséges esetek és gyakori buktatók + +| Helyzet | Mire figyelj | Javítás / Ajánlás | +|----------------------------------------|--------------------------------------------------------|-----------------------------------------------------------| +| A Word fájl **nem támogatott betűtípusokat** tartalmaz | A betűtípusok helyettesítése megtörheti az egyenlet elrendezését | Adj meg egy egyedi `FontSettings`‑et tartalék betűtípusokkal. | +| Nagy dokumentumok (> 100 MB) | Memória nyomás a konverzió során | Használd a `LoadOptions`‑t `LoadFormat.Docx`‑szel, és streameld a fájlt. | +| A képek **EMF/WMF** vektoros grafikák | Véletlenül rasterizálódhatnak | Konvertáld őket PNG‑re `ImageSaveOptions` segítségével mentés előtt. | +| PDF/UA hibát jelez **beágyazott táblázatok** esetén | A címkézés bizonytalan lehet | Engedélyezd a `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit`‑et a motor segítésére. | +| **Egyedi stílusok** megőrzése szükséges | A Markdown korlátozott stíluslehetőségekkel rendelkezik | Exportálj egy CSS fájlt a Markdown mellé, és hivatkozz rá. | + +## Teljes működő példa (az összes kód együtt) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Futtasd a programot, és megtalálod a `doc.md` (LaTeX egyenletekkel és tiszta képhivatkozásokkal) és a `doc.pdf` (teljesen PDF/UA‑2 kompatibilis) fájlokat a `YOUR_DIRECTORY` könyvtárban. + +## Vizuális áttekintés + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Alt szöveg:* **convert word to markdown example** – diagram a konverziós csővezetékéről, amely egy Word fájlból Markdown‑ba és PDF/UA‑ba vezet. + +## Összefoglalás és következő lépések + +Épp most **konvertáltuk a Word dokumentumot Markdown‑ba**, miközben az egyenletek érintetlenek maradtak, a képeket rendezett mappában tároltuk, és egy **PDF/UA‑ként mentett** fájlt hoztunk létre, amely átmegy a hozzáférhetőségi ellenőrzéseken. A legfontosabb tanulságok: + +- Használd a `LoadOptions.RecoveryMode.Relaxed`‑t, hogy toleráld a hibás Word fájlokat. +- Állítsd be az `OfficeMathExportMode`‑t `LaTeX`‑re a tiszta egyenletmegjelenítéshez. +- Implementálj egy `ResourceSavingCallback`‑et a képek kimenetének irányításához. +- Engedélyezd a `PdfCompliance.PdfUAXmpA2`‑t és az `ExportFloatingShapesAsInlineTag`‑et a szabványos PDF‑hez. + +### Mit érdemes még felfedezni? + +- **Egyedi CSS a Markdown‑hoz** – generálj egy stíluslapot, amely tükrözi a Word stílusaidat. +- **Kötegelt feldolgozás** – iterálj egy `.docx` fájlokból álló könyvtáron, hogy automatizáld a nagy migrációkat. +- **Haladó PDF/UA funkciók** – adj hozzá egyedi címkéket, állíts be nyelvi attribútumokat, vagy ágyazz be audio leírásokat. +- **CI/CD integráció** – biztosítsd, hogy minden build automatikusan hozzáférhető PDF‑eket állítson elő. + +Ha elakadsz, ellenőrizd, hogy az Aspose.Words verziód megegyezik-e a cikkben használt API‑val, és ne feledd, hogy a könyvtár saját dokumentációja kiváló másodlagos referencia. + +Boldog kódolást, és legyenek a dokumentumaid egyszerre gyönyörűek **és** hozzáférhetőek! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/programming-with-txtsaveoptions/_index.md b/words/hungarian/net/programming-with-txtsaveoptions/_index.md index ae0259f372..4ac05701ec 100644 --- a/words/hungarian/net/programming-with-txtsaveoptions/_index.md +++ b/words/hungarian/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Ezeknek az oktatóanyagoknak köszönhetően teljes mértékben kiaknázhatod az | [Kétirányú jelek hozzáadása Word-dokumentumban](./add-bidi-marks/) | Tanulja meg, hogyan adhat hozzá kétirányú (Bidi) jeleket Word-dokumentumokban az Aspose.Words for .NET használatával ebből az útmutatóból. Biztosítsa a megfelelő szövegirányt többnyelvű tartalom esetén. | | [Tabulátor karakter használata szintenként a lista behúzásához](./use-tab-character-per-level-for-list-indentation/) | Ismerje meg, hogyan hozhat létre többszintű, tabulátoros behúzással rendelkező listákat az Aspose.Words for .NET segítségével. Kövesse ezt az útmutatót a dokumentumokban található precíz listaformázáshoz. | | [Szóköz karakter használata szintenként a lista behúzásához](./use-space-character-per-level-for-list-indentation/) | Tanulja meg, hogyan hozhat létre többszintű listákat szóközök behúzásával az Aspose.Words for .NET programban. Lépésről lépésre útmutató a precíz dokumentumformázáshoz. | - +| [docx mentése txt‑ként – Word egyenletek exportálása LaTeX‑be C#‑val](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Tanulja meg, hogyan exportálhatja a Word egyenleteket LaTeX formátumba C#‑ban, miközben a DOCX fájlt TXT‑ként menti. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/hungarian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..b6913ec997 --- /dev/null +++ b/words/hungarian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: docx mentése txt formátumba az Aspose.Words segítségével – gyorsan konvertálja + a Wordet txt-re, és tanulja meg, hogyan exportálhatja a matematikai egyenleteket + LaTeX-be. Egyszerű C# kód, nincs szükség extra eszközökre. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: hu +og_description: Mentse a docx fájlt txt formátumba C#-ban, és nézze meg, hogyan exportálható + a matematika LaTeX-be. Kövesse ezt a lépésről‑lépésre útmutatót a Word txt-re konvertálásához, + a képletek érintetlenül maradnak. +og_title: docx mentése txt-ként – Word egyenletek exportálása LaTeX-be +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx mentése txt formátumba – Word egyenletek exportálása LaTeX-be C#‑val +url: /hu/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx mentése txt‑ként – Word egyenletek exportálása LaTeX‑be C#‑vel + +Valaha szükséged volt **docx mentése txt‑ként**, de aggódtál, hogy az egyenletek eltűnnek vagy olvashatatlan szöveggé válnak? Nem vagy egyedül. Sok fejlesztő szembesül ezzel, amikor **word konvertálása txt‑be** próbálja meg a további feldolgozáshoz, különösen ha a forrásfájl Office Math objektumokat tartalmaz. + +A jó hír? Néhány C#‑sorral és a megfelelő beállításokkal nemcsak **Word konvertálása txt‑be** lehetséges, hanem minden egyenletet tiszta LaTeX‑kódként is megőrizhetsz. Ebben az útmutatóban végigvezetünk a teljes folyamaton, elmagyarázzuk, miért fontos minden beállítás, és megmutatjuk, hogyan ellenőrizheted az eredményt. + +A következőket fogjuk áttekinteni: + +* Az Aspose.Words for .NET könyvtár telepítése +* Egy `.docx` betöltése, amely matematikai egyenleteket tartalmaz +* A `TxtSaveOptions` konfigurálása úgy, hogy a **how to export math** LaTeX‑barát karakterlánccá váljon +* A fájl mentése és a kimenet ellenőrzése + +A végére egy újrahasználható kódrészletet kapsz, amely lehetővé teszi a **docx mentése txt‑ként**, miközben minden képletet LaTeX‑ként őriz meg – tökéletes tudományos pipeline‑okhoz, statikus weboldalgenerátorokhoz vagy bármilyen munkafolyamathoz, amelynek tiszta szöveges matematikára van szüksége. + +--- + +## Előkövetelmények + +Mielőtt belemerülnénk, győződj meg róla, hogy a következőkkel rendelkezel: + +* .NET 6.0 vagy újabb (a kód .NET Framework 4.6+‑vel is működik) +* Visual Studio 2022 (vagy bármely kedvelt IDE) +* A **Aspose.Words for .NET** NuGet csomag – telepítsd a következővel + +```bash +dotnet add package Aspose.Words +``` + +Nem szükséges további konverter vagy külső eszköz; az Aspose.Words a nehéz munkát belsőleg végzi. + +--- + +## 1. lépés: Aspose.Words telepítése és hivatkozása + +Először add hozzá a könyvtárat a projektedhez. Ha parancssort használsz, futtasd a fenti parancsot. Visual Studio‑ban pedig jobb‑kattints a **Dependencies → Manage NuGet Packages** menüpontra, és keresd meg az *Aspose.Words* csomagot. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tipp:** Használd a legújabb stabil verziót (2026. április állása szerint ez a 24.10). Az újabb kiadások hibajavításokat tartalmaznak az OfficeMath kezelésében, így elkerülheted a váratlan hiányzó szimbólumokat. + +--- + +## 2. lépés: A forrásdokumentum betöltése + +Most betöltjük azt a `.docx`‑et, amely az egyenleteket tartalmazza, amiket meg szeretnél őrizni. A `Document` osztály absztrahálja a teljes Word‑fájlt, így hozzáférést biztosít a szöveghez, képekhez és Office Math objektumokhoz. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Miért kell előbb betölteni? Az Aspose.Words a fájlt egy objektummodellé alakítja, ami lehetővé teszi a tartalom ellenőrzését vagy módosítását, mielőtt eldöntenénk, hogyan exportáljuk. Itt kezdődik el a **how to export math** döntés fontossága. + +--- + +## 3. lépés: TxtSaveOptions konfigurálása LaTeX exporthoz + +A megoldás szíve a `TxtSaveOptions` osztály. Alapértelmezés szerint a TXT mentése teljesen eltávolítja az Office Math‑ot. Az `OfficeMathExportMode` beállítása `LaTeX`‑re azt mondja a könyvtárnak, hogy minden egyenletet a LaTeX reprezentációjává alakítson. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Miért LaTeX?** A LaTeX a tudományos kiadványszerkesztés lingua francája. Így az egyenletek szemantikai tartalma megmarad, ahelyett, hogy egy lapos kép vagy összezavaró karakterlánc lenne. Ha később a TXT‑t egy MathJax‑ot támogató Markdown‑processzorba táplálod, az egyenletek tökéletesen megjelennek. + +--- + +## 4. lépés: Dokumentum mentése egyszerű szövegként + +Miután beállítottuk a lehetőségeket, az utolsó lépés egy egyetlen sor, amely a fájlt a lemezre írja. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Ennyi—most a `.docx` egy `.txt` fájl lett, ahol minden egyenlet LaTeX‑kódrészletként jelenik meg, készen áll a további felhasználásra. + +--- + +## A kimenet ellenőrzése (Hogyan mentse helyesen a txt‑t) + +Nyisd meg a `MathSample.txt`‑et bármely szövegszerkesztőben. Valami ilyesmit kell látnod: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Ha nyers Word‑specifikus karaktereket (pl. `?` vagy hiányzó szimbólumok) látsz, ellenőrizd a következőket: + +* A legfrissebb Aspose.Words verziót használod (a régebbi build‑ek hibákat tartalmaztak az OfficeMath‑ban). +* A forrásdokumentum valóban **OfficeMath** objektumokat tartalmaz, nem pedig régi Equation Editor objektumokat. Az utóbbi esetén manuálisan kell konvertálni őket, vagy a `ConvertMathToOfficeMath` metódust kell meghívni a mentés előtt. + +--- + +## Gyakori variációk és szélsőséges esetek + +| Helyzet | Mit kell tenni | +|-----------|------------| +| **Legacy Equation Editor** objektumok | Hívd meg a `doc.ConvertMathToOfficeMath()` metódust a 3. lépés előtt. | +| **Szükséged van egyszerű Unicode matematikára, nem LaTeX‑re** | Állítsd be `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Nagy dokumentumok (100 + MB)** | Használd a `doc.Save(Stream, txtOptions)` streaming mentést, hogy elkerüld a magas memóriahasználatot. | +| **Az eredeti fájlnév megtartása** | A kimeneti útvonal építésekor használd a `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` kifejezést. | + +Ezek a finomhangolások válaszolnak a “**how to export math**” kérdésre különböző pipeline‑okban, biztosítva, hogy a megoldásod robusztus legyen bármilyen forrás esetén. + +--- + +## Teljes működő példa (Minden lépés egy helyen) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Futtasd a programot, nyisd meg a generált `.txt`‑et, és láthatod a LaTeX egyenleteket pontosan ott, ahol lennie kellett. Ez a legegyszerűbb módja a **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/hungarian/net/working-with-fonts/_index.md b/words/hungarian/net/working-with-fonts/_index.md index 609ee46620..2669ae3f88 100644 --- a/words/hungarian/net/working-with-fonts/_index.md +++ b/words/hungarian/net/working-with-fonts/_index.md @@ -40,7 +40,7 @@ Akár különböző betűtípusokkal szeretné formázni a szöveget, betűtípu | [Betűtípusok mappáinak prioritás szerinti beállítása](./set-fonts-folders-with-priority/) | Ismerje meg, hogyan állíthat be prioritást a betűtípus-mappákban a Word-dokumentumokban az Aspose.Words for .NET használatával. Útmutatónk biztosítja, hogy dokumentumai minden alkalommal tökéletesen jelenjenek meg. | | [True Type betűtípusok mappa beállítása](./set-true-type-fonts-folder/) | Ismerje meg, hogyan állíthat be True Type Fonts mappát Word-dokumentumokban az Aspose.Words for .NET segítségével. Kövesse részletes, lépésről lépésre szóló útmutatónkat a betűtípus-kezelés egységessége érdekében. | | [Alapértelmezett betűtípus megadása rendereléshez](./specify-default-font-when-rendering/) | Ismerje meg, hogyan adhat meg alapértelmezett betűtípust Word-dokumentumok renderelésekor az Aspose.Words for .NET használatával. Biztosítsa a dokumentumok egységes megjelenését a platformokon átívelően. | -| [Betűtípus-beállítások betöltési opciókkal](./font-settings-with-load-options/) Ismerje meg, hogyan kezelheti a betűtípus-beállításokat a betöltési opciókkal az Aspose.Words for .NET programban. Lépésről lépésre útmutató fejlesztőknek a betűtípusok egységes megjelenésének biztosításához a Word-dokumentumokban. +| [Betűtípus-beállítások betöltési opciókkal](./font-settings-with-load-options/) Ismerje meg, hogyan kezelheti a betűtípus-beállításokat a betöltési opciókkal az Aspose.Words for .NET programban. Lépésről lépésre útmutató fejlesztőknek a betűtípusok egységes megjelenésének biztosításához a Word-dokumentumokban. | | [Betűtípusok beállítása mappa](./set-fonts-folder/) | Ismerje meg, hogyan állíthat be egyéni betűtípusmappát az Aspose.Words for .NET programban, hogy Word-dokumentumai helyesen jelenjenek meg hiányzó betűtípusok nélkül. | | [Betűtípusbeállítások Alapértelmezett példány](./font-settings-default-instance/) | Ebben az oktatóanyagban megtudhatja, hogyan konfigurálhatja az alapértelmezett betűtípus-beállításokat egy Word-dokumentumban az Aspose.Words for .NET segítségével. | | [Elérhető betűtípusok listájának lekérése](./get-list-of-available-fonts/) | Fedezze fel, hogyan kérheti le az elérhető betűtípusok listáját az Aspose.Words for .NET használatával ebben a részletes, lépésről lépésre szóló útmutatóban. Fejlessze betűtípus-kezelési készségeit. | @@ -48,8 +48,7 @@ Akár különböző betűtípusokkal szeretné formázni a szöveget, betűtípu | [Figyelmeztető értesítés fogadása](./receive-warning-notification/) Ismerje meg, hogyan kaphat figyelmeztető értesítést az Aspose.Words for .NET használatakor, és hogyan kezelheti a dokumentumokban előforduló problémákat vagy figyelmeztetéseket. | | [Erőforrás Steam betűtípus forrás példa](./resource-steam-font-source-example/) | Ismerje meg, hogyan használható a Resource Stream Font Source egyéni betűtípusok betöltéséhez az Aspose.Words for .NET fájlba. | | [Helyettesítés kérése utótagok nélkül](./get-substitution-without-suffixes/) | Ebben az oktatóanyagban megtudhatja, hogyan lehet utótag nélküli felülírásokat beállítani egy Word-dokumentumban az Aspose.Words for .NET segítségével. | - - +| [Aspose betűtípus-helyettesítés – Hiányzó betűtípusok észlelése Word dokumentumokban](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Ismerje meg, hogyan észlelheti a hiányzó betűtípusokat a Word-dokumentumokban az Aspose.Words for .NET segítségével. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/hungarian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/hungarian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..0d96898007 --- /dev/null +++ b/words/hungarian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Aspose betűtípus-helyettesítési útmutató a hiányzó betűtípusok észleléséhez + Word-dokumentum betöltésekor. Tanulja meg a betűtípus-beállítások konfigurálását + és a hiányzó betűtípusok hatékony kezelését. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: hu +og_description: Aspose betűtípus helyettesítési útmutató a hiányzó betűtípusok észleléséhez + Word-dokumentum betöltésekor. Tanulja meg a betűtípus-beállítások konfigurálását + és a hiányzó betűtípusok hatékony kezelését. +og_title: Aspose betűtípus helyettesítés – Hiányzó betűtípusok felismerése Word dokumentumokban +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose betűtípus helyettesítés – Hiányzó betűtípusok felderítése Word-dokumentumokban +url: /hu/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Hiányzó betűtípusok észlelése Word dokumentumokban + +Már előfordult már, hogy egy Word fájl egy gépen tökéletesnek tűnik, de egy másikon furcsa betűtípus‑változásokat mutat? Ez a klasszikus **aspose font substitution** probléma, és általában azt jelenti, hogy néhány betűtípus hiányzik a célrendszeren. Ebben az útmutatóban lépésről‑lépésre megmutatjuk, hogyan **észlelheted a hiányzó betűtípusokat**, amikor **betöltesz egy Word dokumentumot**, hogyan **konfigurálhatod a betűtípus beállításokat**, és mit kell tenni a **hiányzó betűtípusok** elegáns kezeléséhez. + +Végigvezetünk egy teljes, futtatható C# példán, elmagyarázzuk, miért fontos minden sor, és még a várt konzolkimenetet is megmutatjuk. A végére képes leszel felismerni a betűtípus‑helyettesítéseket már a dokumentum betöltésekor – találgatás nélkül. + +## Amit megtanulsz + +- Hogyan engedélyezheted az Aspose.Words diagnosztikai gyűjtőjét a betűtípus‑figyelmeztetésekhez. +- A pontos kód, amely szükséges egy **Word dokumentum betöltéséhez** egyedi **betűtípus beállításokkal**. +- Hogyan iterálhatsz a `WarningInfo` objektumokon, hogy felsorold az összes helyettesített betűtípust. +- Tippek a nem kívánt figyelmeztetések elnyomásához vagy helyettesítő betűtípusok biztosításához. +- Egy azonnal futtatható minta, amelyet kimásolhatsz a Visual Studio-ba. + +### Előkövetelmények + +- .NET 6.0 vagy újabb (az API ugyanúgy működik a .NET Framework‑on is). +- Aspose.Words for .NET (NuGet csomag `Aspose.Words`). +- Egy Word fájl, amely egy olyan betűtípust hivatkozik, amely nincs telepítve (pl. `MissingFont.docx`). + +Ha ezek megvannak, vágjunk bele. + +## 1. lépés – A diagnosztikai gyűjtő engedélyezése (Betűtípus beállítások konfigurálása) + +Először is: az Aspose.Words csak akkor rögzíti a betűtípus‑helyettesítési figyelmeztetéseket, ha ezt engedélyezed. Ezt úgy éred el, hogy létrehozol egy `FontSettings` objektumot, és hozzárendeled egy `LoadOptions` példányhoz. Gondolj rá úgy, mint a betűtípus‑kezelés „debug lámpáinak” bekapcsolására. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Miért?** +`FontSettings` objektum nélkül a figyelmeztető gyűjtő csendben marad, és soha nem fogod megtudni, mely betűtípusok lettek cserélve. Üresen inicializálva engedjük, hogy az Aspose az alapértelmezett rendszer‑betűtípusokat használja *és* nyomon kövesse a helyettesítéseket. + +> **Pro tipp:** Ha tudod, hogy egy adott mappa vállalati betűtípusokat tartalmaz, állítsd be a `FontSettings`‑t arra a `SetFontsFolder("path")` hívással. Ez csökkentheti a hiányzó betűtípusok figyelmeztetéseinek számát. + +## 2. lépés – A dokumentum betöltése a konfigurált beállításokkal (Word dokumentum betöltése) + +Most, hogy a gyűjtő aktív, töltsd be a `.docx` fájlodat ugyanazzal a `LoadOptions` példánnyal. Ebben a pillanatban az Aspose átvizsgálja a dokumentumot, minden betűtípus‑hivatkozást megkeres, és eldönti, szükséges‑e a helyettesítés. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Miért fontos ez?** +Ha egyszerűen csak `new Document("MissingFont.docx")`‑t hívtad volna, az alapértelmezett beállítások lennének érvényben *és* a figyelmeztetési lista üres maradna. A `loadOptions` átadása garantálja, hogy a diagnosztikai gyűjtő a betöltési folyamatba legyen bekapcsolva. + +## 3. lépés – Betűtípus‑helyettesítési figyelmeztetések lekérése és megjelenítése (Hiányzó betűtípusok észlelése) + +A dokumentum memóriába kerülése után az Aspose a figyelmeztetéseket a `document.WarningCallback.Warnings`‑ben tárolja. Iterálj végig ezen a gyűjteményen, szűrd le a `WarningType.FontSubstitution` elemeket, és írd ki a leírást. Minden leírás megmondja, melyik betűtípus hiányzott és melyik lett helyette használva. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Várt konzolkimenet** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Ez a kimenet pontosan megmutatja, mely betűtípusok hiányoznak azon a gépen, amelyen a kód fut. Most már eldöntheted, telepíted‑e a hiányzó betűtípusokat, beágyazod‑e a dokumentumba, vagy megtartod a helyettesítést. + +![aspose betűtípus helyettesítés – konzolkimenet a helyettesített betűtípusok listájával](/images/aspose-font-substitution-console.png) + +*Image alt text:* aspose betűtípus helyettesítés – konzolkimenet a helyettesített betűtípusok listájával + +## 4. lépés – Opcionális: A helyettesítési viselkedés testreszabása (Hiányzó betűtípusok kezelése) + +Néha nem csak azt akarod tudni, *hogy* helyettesítés történt — hanem azt, *hogyan* történik. Az Aspose.Words lehetővé teszi egy egyedi `IFontSubstitutionRule` regisztrálását. Az alábbi gyors példa minden hiányzó betűtípust a `Tahoma`‑ra kényszerít. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Mikor használod ezt?** +Ha PDF‑eket generálsz egy webszolgáltatáshoz, és tudod, hogy minden kliens képes a `Tahoma` megjelenítésére, a visszaesés kényszerítése vizuális konzisztenciát biztosít anélkül, hogy tucatnyi betűtípus‑fájlt kellene szállítani. + +## Teljes működő példa (Minden lépés egyben) + +Itt van a teljes program, amelyet beilleszthetsz egy új konzolprojektbe. A kód változtatás nélkül lefordul, feltételezve, hogy telepítetted az Aspose.Words NuGet csomagot. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Futtasd a programot, figyeld a konzolt, és minden hiányzó betűtípus eseményt kiíratva látsz majd. Innen eldöntheted, telepíted‑e a hiányzó betűtípusokat, beágyazod‑e őket, vagy megtartod a visszaesést. + +## Gyakran Ismételt Kérdések + +**K: Működik ez PDF konverzióval?** +Igen. Amikor később meghívod a `doc.Save("output.pdf")`‑t, a betöltés során helyettesített betűtípusok lesznek beágyazva a PDF‑be. Így a figyelmeztetések korai elkapása segít elkerülni a váratlan betűtípus‑változásokat a végső PDF‑ben. + +**K: Mi van, ha sok dokumentumot kell feldolgozni?** +Csomagold a betöltési logikát egy try‑catch blokkba, és használd újra ugyanazt a `FontSettings` példányt a dokumentumok között. Ez csökkenti a terhelést és minden fájlra aktív marad a figyelmeztető gyűjtő. + +**K: Teljesen elnyomhatom a figyelmeztetéseket?** +Beállíthatod a `loadOptions.WarningCallback = null;`‑t a betöltés előtt, de ekkor elveszíted a **hiányzó betűtípusok** észlelésének képességét — ami általában nem kívánt. + +## Összegzés + +Áttekintettük mindazt, amire szükséged van a **aspose font substitution** elsajátításához: a diagnosztikai gyűjtő engedélyezése, egy Word fájl betöltése egyedi **betűtípus beállításokkal**, a hiányzó betűtípusok listájának kinyerése, és még az alapértelmezett helyettesítési szabály felülírása a **hiányzó betűtípusok** saját módon történő kezeléséhez. Néhány C# sorral teljes átláthatóságot kapsz a betűtípus‑problémákban, amelyek egyébként finom elrendezési változások mögé rejtőznek. + +Következő lépések? Próbáld meg beágyazni az eredeti betűtípusokat a dokumentumba a `FontSettings.SetFontsFolder`‑val, vagy fedezd fel a `FontSourceBase`‑t, hogy betűtípusokat adatbázisból tölts be. Kísérletezhetsz a `Document.BuiltInStyle` gyűjteménnyel is, hogy lásd, hogyan terjednek a stílus‑szintű betűtípus‑változások. + +Van még kérdésed az Aspose.Words‑ról vagy a betűtípus‑kezelésről? Hagyj egy megjegyzést, nézd meg a hivatalos Aspose dokumentációt, vagy indíts egy új projektet és kísérletezz a fenti kóddal. Boldog kódolást, és legyenek a dokumentumaid mindig pontosan úgy megjelenítve, ahogy elvárod! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/basic-conversions/_index.md b/words/indonesian/net/basic-conversions/_index.md index a4f93f422e..1f159bf939 100644 --- a/words/indonesian/net/basic-conversions/_index.md +++ b/words/indonesian/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Simpan Word sebagai PDF dengan Aspose.Words – Panduan Lengkap C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Panduan langkah demi langkah menyimpan dokumen Word ke PDF menggunakan Aspose.Words dalam C#. Sempurna untuk pengembang. | | [Cara Mengekspor LaTeX dari Word – Panduan Langkah‑demi‑Langkah](./how-to-export-latex-from-word-step-by-step-guide/) | Pelajari cara mengekspor dokumen Word ke format LaTeX dengan Aspose.Words untuk .NET dalam panduan langkah demi langkah. | | [Mengonversi Word ke PDF dalam C# menggunakan Aspose.Words – Panduan](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Panduan langkah demi langkah mengonversi dokumen Word ke PDF menggunakan Aspose.Words dalam C#. Bahasa Indonesia: | +| [Mengonversi Word ke PDF dalam C# – Panduan Lengkap dengan Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Panduan lengkap mengonversi dokumen Word ke PDF menggunakan Aspose.Words dalam C#. Contoh kode dan langkah mudah. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/indonesian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..24cfb21cbd --- /dev/null +++ b/words/indonesian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-05 +description: Konversi Word ke PDF dalam C# menggunakan Aspose.Words. Pelajari cara + menyimpan docx sebagai PDF, mengekspor PDF yang dapat diakses, dan memuat dokumen + Word secara efisien. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: id +og_description: Konversi Word ke PDF di C# dengan panduan langkah demi langkah. Temukan + cara menyimpan docx sebagai PDF, mengekspor PDF yang dapat diakses, dan memuat dokumen + Word menggunakan Aspose.Words. +og_title: Mengonversi Word ke PDF di C# – Tutorial Lengkap Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Mengonversi Word ke PDF di C# – Panduan Lengkap dengan Aspose.Words +url: /id/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi Word ke PDF di C# – Tutorial Pemrograman Lengkap + +Pernah bertanya-tanya bagaimana cara **convert word to pdf** tanpa harus berurusan dengan alat baris perintah yang rumit atau layanan pihak ketiga? Anda bukan satu-satunya. Banyak pengembang menemui kendala ini ketika klien meminta PDF yang dapat diakses langsung dari file DOCX. Kabar baiknya? Dengan beberapa baris C# dan pustaka Aspose.Words yang kuat, Anda dapat mengubah dokumen Word menjadi PDF yang sesuai standar dalam sekejap. + +Dalam panduan ini kami akan membahas semua yang perlu Anda ketahui: mulai dari dasar **load word document**, melalui konfigurasi opsi yang tepat untuk **how to export accessible pdf**, dan akhirnya menyimpan hasilnya sehingga Anda dapat **save docx as pdf** dengan andal. Pada akhir tutorial Anda akan memiliki potongan kode siap‑jalankan yang dapat Anda masukkan ke proyek .NET mana pun. + +> **Pro tip:** Jika Anda menargetkan kepatuhan PDF/UA‑2 (standar aksesibilitas yang banyak lembaga pemerintah butuhkan), kode yang sama berfungsi tanpa langkah tambahan—cukup atur flag `PdfCompliance` yang tepat. + +--- + +## Apa yang Akan Anda Pelajari + +- Cara **load word document** menggunakan Aspose.Words di C#. +- Pengaturan tepat yang diperlukan untuk **how to export accessible pdf** (PDF/UA‑2). +- Contoh lengkap yang dapat dijalankan yang **save docx as pdf** dengan satu pemanggilan metode. +- Jebakan umum ketika Anda **c# convert docx pdf** dan cara menghindarinya. +- Cara cepat untuk memverifikasi bahwa PDF yang dihasilkan memenuhi harapan aksesibilitas. + +Tanpa alat eksternal, tanpa file konfigurasi yang rumit—hanya kode C# murni yang dapat Anda kompilasi hari ini. + +--- + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +1. **.NET 6.0** (atau versi .NET terbaru lainnya) terpasang. Kerangka kerja yang lebih lama juga dapat bekerja, tetapi sintaks di bawah mengasumsikan SDK modern. +2. **Lisensi** untuk Aspose.Words for .NET. Pustaka ini menawarkan percobaan gratis, tetapi untuk produksi Anda memerlukan kunci yang valid. +3. Paket NuGet **Aspose.Words** ditambahkan ke proyek Anda: + +```bash +dotnet add package Aspose.Words +``` + +Itu saja—tanpa binari tambahan, tanpa interop COM, hanya referensi NuGet yang bersih. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +--- + +## Implementasi Langkah‑per‑Langkah + +Di bawah ini kami membagi proses menjadi bagian‑bagian logis. Setiap langkah berisi potongan kode kecil, penjelasan **mengapa** itu penting, dan tip yang berasal dari penggunaan dunia nyata. + +### ## Mengonversi Word ke PDF – Muat Dokumen Sumber + +Hal pertama yang perlu Anda lakukan adalah **load word document** ke memori. Aspose.Words menyembunyikan proses parsing OpenXML, sehingga Anda dapat bekerja dengan file DOCX, DOC, atau bahkan RTF tanpa khawatir tentang keanehan format. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Mengapa ini penting:** +Memuat file membuat objek `Document` yang mewakili seluruh file Word, termasuk header, footer, gaya, dan metadata tersembunyi. Jika Anda melewatkan langkah ini atau mencoba membaca file sebagai aliran mentah, Anda akan kehilangan informasi tata letak yang kemudian menentukan tampilan PDF. + +> **Catatan samping:** Konstruktor `Document` yang sama bekerja untuk `.doc` dan `.rtf`. Itu berarti Anda dapat **c# convert docx pdf** bahkan ketika sumbernya bukan DOCX secara ketat. + +### ## Simpan DOCX sebagai PDF – Konfigurasi Kepatuhan PDF/UA‑2 + +Sekarang dokumen berada di memori, kami memberi tahu Aspose.Words bagaimana PDF harus dihasilkan. Untuk kebanyakan kasus penggunaan, pengaturan default sudah cukup, tetapi ketika Anda membutuhkan **accessible PDF**, Anda harus mengaktifkan flag kepatuhan PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Mengapa ini penting:** +`PdfCompliance.PdfUAXmpA2` memberi tahu pustaka untuk menyematkan tag dan struktur yang diperlukan yang diandalkan pembaca layar. Tanpa flag ini, Anda mungkin mendapatkan PDF yang tampak sempurna tetapi gagal dalam audit aksesibilitas. + +> **Tip:** Jika Anda hanya membutuhkan PDF biasa, Anda dapat menghilangkan baris `Compliance`. Sisa opsi masih memberikan output berkualitas tinggi. + +### ## Mengonversi Word ke PDF – Tulis File + +Dengan opsi siap, langkah terakhir adalah **save docx as pdf**. Pemanggilan tunggal ini melakukan semua pekerjaan berat: konversi tata letak, penyematan font, dan penandaan aksesibilitas. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Apa yang Anda dapatkan:** +- File PDF di `outputPath` yang mencerminkan tata letak Word. +- Jika Anda menggunakan flag `PdfUAXmpA2`, PDF akan ditandai sebagai sesuai PDF/UA‑2. +- Semua font disematkan, sehingga file terlihat identik di mesin mana pun. + +### ## Verifikasi PDF yang Accessible (Opsional tetapi Disarankan) + +Setelah konversi, ada baiknya memeriksa kembali bahwa PDF benar‑benar **how to export accessible pdf** dengan tepat. Anda dapat menggunakan alat gratis seperti “Accessibility Check” pada Adobe Acrobat Reader atau validator open‑source `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Jika validator tidak melaporkan kesalahan, Anda telah berhasil **convert word to pdf** dengan dukungan aksesibilitas penuh. + +### ## Kesalahan Umum Saat Anda C# Convert DOCX ke PDF + +| Masalah | Mengapa Terjadi | Solusi | +|-------|----------------|-----| +| Font hilang | DOCX sumber menggunakan font khusus yang tidak terpasang di server. | Atur `EmbedFullFonts = true` atau pasang font tersebut di mesin. | +| Ukuran file besar | Gambar disematkan dengan resolusi penuh. | Gunakan `ImageCompression = PdfImageCompression.Jpeg` dan atur `JpegQuality` ke nilai yang lebih rendah. | +| Hyperlink rusak | Tautan mengarah ke jalur relatif yang tidak ada di klien. | Pastikan URL bersifat absolut atau sesuaikan properti `HyperlinkTarget`. | +| Tag aksesibilitas hilang | Flag `Compliance` tidak diatur. | Tambahkan `Compliance = PdfCompliance.PdfUAXmpA2` seperti yang ditunjukkan di atas. | + +Mengingat hal‑hal ini akan membuat rutinitas **c# convert docx pdf** Anda menjadi kuat dan siap produksi. + +--- + +## Contoh Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut aplikasi konsol mandiri yang dapat Anda kompilasi dan jalankan sekarang juga. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Hasil yang diharapkan:** Setelah menjalankan program, Anda akan menemukan `output.pdf` di `C:\Docs`. Buka di penampil PDF apa pun; tata letaknya harus cocok dengan `input.docx` pixel‑per‑pixel, dan pemeriksaan aksesibilitas akan mengonfirmasi kepatuhan PDF/UA‑2. + +--- + +## Kesimpulan + +Kami baru saja menelusuri solusi lengkap, end‑to‑end untuk cara **convert word to pdf** menggunakan C# dan Aspose.Words. Dengan **load word document**, mengonfigurasi `PdfSaveOptions` yang tepat, dan akhirnya **save docx as pdf**, Anda mendapatkan PDF berkualitas tinggi dan dapat diakses dengan kode minimal. Baik Anda membangun layanan mikro generasi dokumen, konverter batch on‑premise, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-markdownsaveoptions/_index.md b/words/indonesian/net/programming-with-markdownsaveoptions/_index.md index 99c8d539a0..92945b9fdb 100644 --- a/words/indonesian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/indonesian/net/programming-with-markdownsaveoptions/_index.md @@ -41,6 +41,10 @@ Pelajari cara mengekspor dokumen Word ke Markdown dengan panduan lengkap C#. Pelajari cara menyimpan file DOCX sebagai Markdown dengan panduan langkah demi langkah menggunakan C#. ### [Cara Mengekspor Markdown dari DOCX – Panduan Lengkap](./how-to-export-markdown-from-docx-complete-guide/) Pelajari cara mengekspor dokumen DOCX ke format Markdown dengan panduan lengkap. +### [Konversi DOCX ke Markdown – Ekstrak Gambar dari DOCX dengan Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Pelajari cara mengonversi file DOCX ke Markdown sambil mengekstrak semua gambar menggunakan Aspose.Words. +### [Konversi Word ke Markdown – Panduan Lengkap dengan Ekspor PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +Pelajari cara mengonversi dokumen Word ke Markdown lengkap dengan mengekspor PDF/UA menggunakan Aspose.Words untuk .NET. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/indonesian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..4c757e73c9 --- /dev/null +++ b/words/indonesian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Pelajari cara mengonversi DOCX ke Markdown dan mengekstrak gambar dari + DOCX dalam C#. Panduan langkah demi langkah dengan kode lengkap dan tips. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: id +og_description: Konversi DOCX ke Markdown dan ekstrak gambar dari DOCX menggunakan + Aspose.Words. Tutorial C# lengkap dengan kode, penjelasan, dan tips praktik terbaik. +og_title: Konversi DOCX ke Markdown – Ekstrak Gambar dari DOCX dengan C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Ubah DOCX ke Markdown – Ekstrak Gambar dari DOCX dengan Aspose.Words +url: /id/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi DOCX ke Markdown – Mengekstrak Gambar dari DOCX dalam C# + +Pernah perlu **mengonversi DOCX ke Markdown** tetapi kesulitan karena gambar menghilang di output? Anda tidak sendirian. Dalam banyak proyek versi markdown sangat cocok untuk version‑control atau static‑site generator, namun gambar‑gambar tertinggal, menjadikan dokumen kaya menjadi file teks kosong. + +Kabar baik? Dengan beberapa baris C# dan Aspose.Words Anda dapat **mengonversi DOCX ke Markdown** *dan* **mengekstrak gambar dari DOCX** secara otomatis. Panduan ini membawa Anda melalui seluruh proses, menjelaskan mengapa setiap bagian penting, dan bahkan menunjukkan cara menjaga folder gambar tetap rapi. + +## Apa yang Akan Anda Pelajari + +- Cara memuat DOCX yang berisi gambar. +- Cara mendefinisikan `IResourceSavingCallback` khusus yang menentukan ke mana setiap gambar disimpan. +- Cara mengonfigurasi `MarkdownSaveOptions` sehingga markdown yang dihasilkan merujuk ke gambar yang diekstrak dengan benar. +- Tips menangani kasus tepi seperti nama gambar duplikat atau format non‑PNG. +- Contoh kode lengkap yang siap disalin‑tempel dan dapat Anda jalankan hari ini. + +### Prasyarat + +- .NET 6.0 atau lebih baru (API ini bekerja pada .NET Core, .NET Framework, dan .NET 5+). +- Lisensi untuk **Aspose.Words for .NET** (versi percobaan gratis dapat digunakan untuk pengujian). +- Pemahaman dasar tentang C# dan Visual Studio (atau IDE favorit Anda). + +Jika Anda sudah memiliki semuanya, mari kita mulai. + +--- + +## Langkah 1: Siapkan Proyek dan Instal Aspose.Words + +Pertama, buat aplikasi console baru (atau integrasikan ke dalam solusi yang sudah ada). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Tip Pro:** Gunakan versi NuGet terbaru (per April 2026 versi 24.12) untuk mendapatkan perbaikan ekspor markdown terbaru. + +--- + +## Langkah 2: Buat Callback untuk Menyimpan Gambar di Lokasi yang Anda Inginkan + +Aspose.Words memungkinkan Anda menyela setiap sumber daya (gambar, SVG, dll.) yang ditulis selama ekspor markdown. Dengan mengimplementasikan `IResourceSavingCallback` Anda dapat: + +1. Pilih folder yang berada di samping file markdown Anda. +2. Buat nama file unik (agar tidak pernah menimpa gambar yang sudah ada). +3. Tentukan format (di sini kami memaksa PNG untuk konsistensi). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Mengapa Nama Berbasis GUID? + +Jika DOCX sumber berisi dua gambar dengan nama asli yang sama, penyalinan sederhana akan menimpa salah satunya. Menggunakan `Guid.NewGuid()` menjamin keunikan, yang sangat berguna ketika Anda menjalankan konversi berulang kali dalam pipeline otomatis. + +--- + +## Langkah 3: Muat DOCX dan Hubungkan Opsi Markdown + +Sekarang kita memuat dokumen ke memori dan melampirkan callback yang baru saja dibuat. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Apa yang dilakukan kode, langkah demi langkah + +| Langkah | Tujuan | +|------|---------| +| **Mendefinisikan jalur** | Menjaga proyek Anda fleksibel; Anda dapat menunjuk ke folder mana pun tanpa harus mengompilasi ulang. | +| **Muat DOCX** | `Document` mem‑parsing file Word, membuat semua elemen (paragraf, tabel, gambar) dapat diakses. | +| **Konfigurasikan `MarkdownSaveOptions`** | `ResourceSavingCallback` adalah kait yang mengekstrak gambar. Tanpanya, Aspose.Words akan menyematkan gambar sebagai string base64 atau mengabaikannya sepenuhnya, tergantung pada pengaturan. | +| **Simpan** | `doc.Save` menulis file markdown dan memicu callback untuk setiap gambar. | + +--- + +## Langkah 4: Verifikasi Output – Apa yang Harus Anda Lihat? + +Setelah menjalankan program, buka `DocWithImages.md`. Anda akan melihat tautan gambar markdown yang tampak seperti ini: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Dan di `C:\Docs\MarkdownResources` Anda akan menemukan serangkaian file PNG dengan nama GUID. Buka salah satunya – mereka harus identik dengan gambar yang disematkan dalam DOCX asli. + +Jika Anda membuka file markdown di penampil yang menghormati jalur relatif (misalnya pratinjau VS Code, GitHub, atau static‑site generator), gambar akan ditampilkan persis seperti di Word. + +### Masalah Umum & Cara Menghindarinya + +| Gejala | Penyebab Kemungkinan | Solusi | +|---------|--------------|-----| +| Gambar muncul sebagai tautan rusak | `ResourceFileName` tidak diatur, sehingga markdown mengarah ke file yang tidak ada. | Pastikan `args.ResourceFileName = newFileName;` di dalam callback. | +| File PNG berukuran besar | Gambar asli berupa JPEG atau BMP; mengonversi ke PNG dapat meningkatkan ukuran. | Deteksi format asli melalui `args.ResourceContentType` dan pertahankan: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Gambar duplikat masih muncul | Anda menggunakan nama file statis alih‑alih GUID. | Kembalikan ke logika GUID atau tambahkan penghitung per tipe gambar. | +| Konversi melempar `FileNotFoundException` | Jalur DOCX sumber salah atau folder tidak memiliki izin baca. | Verifikasi jalur dan berikan hak akses sistem file yang sesuai. | + +--- + +## Langkah 5: Penyesuaian Lanjutan (Opsional) + +### 5.1 Pertahankan Format Gambar Asli + +Jika Anda ingin gambar output tetap menggunakan ekstensi aslinya, ubah callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Sematkan Gambar sebagai Base64 (Ketika Anda *Tidak* Menginginkan File Terpisah) + +Terkadang markdown satu‑file lebih disukai (misalnya untuk dikirim lewat email). Ubah opsi: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Namun ingat: **mengekstrak gambar dari DOCX** adalah tujuan utama untuk kebanyakan alur kerja static‑site, jadi pendekatan folder biasanya pilihan yang lebih baik. + +--- + +## Contoh Lengkap yang Berfungsi (Siap Salin‑Tempel) + +Berikut seluruh program dalam satu file. Cukup ganti jalur dengan milik Anda sendiri dan jalankan. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Jalankan dengan `dotnet run`. Ketika konsol mencetak baris ✅, buka file markdown dan Anda akan melihat gambar ditampilkan dengan benar. + +--- + +## Kesimpulan + +Anda kini memiliki **solusi lengkap dan siap produksi untuk mengonversi DOCX ke Markdown dan mengekstrak gambar dari DOCX** menggunakan Aspose.Words dalam C#. Kata kunci utama muncul di seluruh panduan, memperkuat relevansi bagi mesin pencari dan asisten AI. + +Dalam satu langkah kode: + +1. Memuat dokumen Word. +2. Menyela setiap gambar via `IResourceSavingCallback`. +3. Menyimpan setiap gambar ke folder yang dapat diprediksi dengan nama unik. +4. Menghasilkan markdown yang merujuk ke gambar‑gambar tersebut. + +Dari sini Anda dapat: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/indonesian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..1298e890f6 --- /dev/null +++ b/words/indonesian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Ubah Word ke Markdown dengan cepat dan pelajari cara menyimpan sebagai + PDF/UA di C#. Kode langkah demi langkah, tips, dan penanganan kasus tepi. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: id +og_description: Konversi Word ke Markdown dan simpan sebagai PDF/UA dengan Aspose.Words. + Pelajari alasan, cara, dan tips praktik terbaik dalam satu panduan singkat. +og_title: Ubah Word ke Markdown – Tutorial C# Lengkap +tags: +- Aspose.Words +- C# +- Document Conversion +title: Ubah Word ke Markdown – Panduan Lengkap dengan Ekspor PDF/UA +url: /id/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi Word ke Markdown – Panduan Lengkap dengan Ekspor PDF/UA + +Pernah bertanya-tanya bagaimana cara **mengonversi Word ke Markdown** tanpa kehilangan persamaan atau gambar? Anda tidak sendirian. Banyak pengembang membutuhkan cara yang andal untuk mengubah file `.docx` menjadi Markdown bersih sambil tetap dapat **menyimpan sebagai PDF/UA** untuk PDF yang mematuhi standar aksesibilitas. Dalam tutorial ini kami akan membahas solusi lengkap yang siap dijalankan menggunakan Aspose.Words untuk .NET, menjelaskan mengapa setiap pengaturan penting, dan menunjukkan cara menangani bagian yang lebih rumit seperti OfficeMath dan bentuk mengambang. + +Pada akhir panduan ini Anda akan memiliki satu program C# yang: + +1. Memuat dokumen Word dengan pemulihan santai (relaxed recovery) (sehingga file yang rusak tidak menghentikan proses). +2. Mengekspor ke Markdown, mengubah persamaan menjadi LaTeX dan menyimpan gambar melalui callback khusus. +3. Menyimpan dokumen yang sama sebagai file yang mematuhi PDF/UA‑2, menyematkan bentuk mengambang sebagai tag inline. + +Terlihat banyak? Tenang saja—mari kita mulai. + +## Apa yang Anda Butuhkan + +- **Aspose.Words for .NET** (versi terbaru, 23.x pada saat penulisan). +- Lingkungan pengembangan .NET (Visual Studio 2022, Rider, atau `dotnet` CLI). +- File Word contoh (`input.docx`) yang ditempatkan di folder yang dapat Anda referensikan. +- Familiaritas dasar dengan sintaks C#—tidak ada yang rumit, hanya beberapa pernyataan `using`. + +> **Pro tip:** Jika Anda menggunakan manajer paket NuGet, tambahkan pustaka dengan +> `dotnet add package Aspose.Words` atau melalui UI NuGet Visual Studio. + +## Langkah 1 – Memuat Dokumen Word dengan Pemulihan Santai + +Saat Anda menerima file Word dari sumber eksternal, file tersebut mungkin mengandung korupsi kecil. Mengaktifkan pemulihan **Relaxed** memberi tahu Aspose.Words untuk terus berjalan alih-alih melempar pengecualian. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Mengapa ini penting:** +- `RecoveryMode.Relaxed` mencegah satu paragraf yang rusak menghentikan seluruh konversi. +- Menyediakan objek `FontSettings` memastikan bahwa font yang hilang diganti secara elegan, yang penting ketika Anda kemudian merender persamaan sebagai LaTeX. + +## Langkah 2 – Mengekspor ke Markdown (OfficeMath → LaTeX, Gambar via Callback) + +Markdown tidak memiliki cara bawaan untuk merepresentasikan persamaan Word. Aspose.Words dapat menerjemahkan objek **OfficeMath** menjadi LaTeX, yang dipahami oleh kebanyakan renderer Markdown. Gambar, bagaimanapun, perlu disimpan di suatu tempat; **callback penyimpanan sumber daya** khusus memberi Anda kontrol penuh atas struktur folder dan penamaan. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback Penyimpanan Sumber Daya + +Berikut adalah implementasi kecil yang menyimpan setiap gambar dalam sub‑folder bernama `images` dan menamai file dengan `img001.png`, `img002.png`, dll. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Mengapa Anda memerlukan ini:** +- Tanpa callback, Aspose.Words membuat folder datar dengan nama GUID acak, yang membuat kontrol versi berantakan. +- Dengan mengontrol skema penamaan, Anda menjaga repositori Markdown tetap rapi dan dapat direproduksi. + +### Output Markdown yang Diharapkan + +Buka `doc.md` setelah menjalankan program dan Anda akan melihat: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Persamaan muncul sebagai LaTeX yang dibungkus dalam `$$ … $$`, dan gambar merujuk ke folder `images` yang baru saja Anda buat. + +## Langkah 3 – Mengekspor ke PDF/UA‑2 (Siap Aksesibilitas) + +Jika Anda perlu membagikan dokumen kepada pengguna yang mengandalkan pembaca layar atau teknologi bantu lainnya, kepatuhan **PDF/UA‑2** adalah standar emas. Aspose.Words dapat menegakkannya dengan satu flag, dan juga dapat meratakan bentuk mengambang menjadi tag inline sehingga tidak hilang selama konversi. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Mengapa PDF/UA penting:** +- PDF/UA (Universal Accessibility) menjamin bahwa PDF yang dihasilkan berisi penandaan yang tepat, urutan baca logis, dan teks alternatif untuk gambar. +- Mengatur `ExportFloatingShapesAsInlineTag` memastikan bahwa bentuk seperti kotak teks atau callout tidak diabaikan atau salah tempat—kesalahan umum saat mengonversi tata letak kompleks. + +### Memverifikasi Kepatuhan PDF/UA + +Setelah ekspor, buka PDF di Adobe Acrobat Pro dan jalankan **“Accessibility Check”** (Tools → Accessibility → Full Check). Jika alat melaporkan **0 error**, Anda berhasil. + +## Kasus Tepi & Kesalahan Umum + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| File Word berisi **font yang tidak didukung** | Font dapat digantikan, merusak tata letak persamaan | Sediakan `FontSettings` khusus dengan font fallback. | +| Dokumen besar (> 100 MB) | Tekanan memori selama konversi | Gunakan `LoadOptions` dengan `LoadFormat.Docx` dan alirkan file. | +| Gambar berupa grafik vektor **EMF/WMF** | Mungkin diubah menjadi raster secara tidak sengaja | Konversi menjadi PNG via `ImageSaveOptions` sebelum menyimpan. | +| PDF/UA gagal validasi pada **tabel bersarang** | Penandaan dapat menjadi ambigu | Aktifkan `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` untuk membantu mesin. | +| Perlu **mempertahankan gaya khusus** | Markdown memiliki kemampuan styling terbatas | Ekspor file CSS bersamaan dengan Markdown dan referensikan. | + +## Contoh Kerja Lengkap (Semua Kode Bersama) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Jalankan program, dan Anda akan menemukan `doc.md` (dengan persamaan LaTeX dan tautan gambar bersih) serta `doc.pdf` (sepenuhnya mematuhi PDF/UA‑2) berada di `YOUR_DIRECTORY`. + +## Gambaran Visual + +![contoh mengonversi word ke markdown](https://example.com/placeholder.png "contoh mengonversi word ke markdown – menunjukkan input Word, output Markdown, dan file PDF/UA") + +*Alt text:* **contoh mengonversi word ke markdown** – diagram alur konversi dari file Word ke Markdown dan PDF/UA. + +## Ringkasan & Langkah Selanjutnya + +Kami baru saja **mengonversi Word ke Markdown** sambil menjaga persamaan tetap utuh, menyimpan gambar dalam folder yang rapi, dan menghasilkan file **save as PDF/UA** yang lolos pemeriksaan aksesibilitas. Poin pentingnya adalah: + +- Gunakan `LoadOptions.RecoveryMode.Relaxed` untuk menoleransi file Word yang tidak sempurna. +- Atur `OfficeMathExportMode` ke `LaTeX` untuk rendering persamaan yang bersih. +- Implementasikan `ResourceSavingCallback` untuk mengontrol output gambar. +- Aktifkan `PdfCompliance.PdfUAXmpA2` dan `ExportFloatingShapesAsInlineTag` untuk PDF yang mematuhi standar. + +### Apa yang Bisa Dijelajahi Selanjutnya? + +- **CSS khusus untuk Markdown** – menghasilkan stylesheet yang mencerminkan gaya Word Anda. +- **Pemrosesan batch** – iterasi melalui direktori file `.docx` untuk mengotomatiskan migrasi besar. +- **Fitur PDF/UA lanjutan** – menambahkan tag khusus, mengatur atribut bahasa, atau menyematkan deskripsi audio. +- **Integrasi dengan CI/CD** – memastikan setiap build menghasilkan PDF yang dapat diakses secara otomatis. + +Jika Anda mengalami masalah, periksa kembali bahwa versi Aspose.Words Anda cocok dengan API yang digunakan di sini, dan ingat bahwa dokumentasi pustaka tersebut merupakan referensi sekunder yang solid. + +Selamat coding, dan semoga dokumen Anda tetap indah **dan** dapat diakses! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/programming-with-txtsaveoptions/_index.md b/words/indonesian/net/programming-with-txtsaveoptions/_index.md index fc57b5423a..74660dc6a2 100644 --- a/words/indonesian/net/programming-with-txtsaveoptions/_index.md +++ b/words/indonesian/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Bahasa Indonesia: --- | --- Bahasa Indonesia: | [Tambahkan Tanda Bidi di Dokumen Word](./add-bidi-marks/) | Pelajari cara menambahkan tanda dua arah (Bidi) dalam dokumen Word menggunakan Aspose.Words untuk .NET dengan panduan ini. Pastikan arah teks yang tepat untuk konten multibahasa. Bahasa Indonesia: | [Gunakan Karakter Tab Per Level Untuk Indentasi Daftar](./use-tab-character-per-level-for-list-indentation/) | Pelajari cara membuat daftar bertingkat dengan indentasi tab menggunakan Aspose.Words untuk .NET. Ikuti panduan ini untuk pemformatan daftar yang tepat dalam dokumen Anda. Bahasa Indonesia: | [Gunakan Karakter Spasi Per Level Untuk Indentasi Daftar](./use-space-character-per-level-for-list-indentation/) | Pelajari cara membuat daftar bertingkat dengan indentasi karakter spasi di Aspose.Words untuk .NET. Panduan langkah demi langkah untuk pemformatan dokumen yang tepat. | - +| [Simpan docx sebagai txt – Ekspor Persamaan Word ke LaTeX dengan C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Pelajari cara mengekspor persamaan Word ke format LaTeX saat menyimpan dokumen DOCX sebagai file TXT menggunakan C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/indonesian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..81fd5e2e47 --- /dev/null +++ b/words/indonesian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Simpan docx sebagai txt dengan Aspose.Words – konversi Word ke txt dengan + cepat dan pelajari cara mengekspor persamaan matematika sebagai LaTeX. Kode C# sederhana, + tidak memerlukan alat tambahan. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: id +og_description: Simpan docx sebagai txt di C# dan lihat cara mengekspor matematika + ke LaTeX. Ikuti panduan langkah demi langkah ini untuk mengonversi Word ke txt dengan + persamaan tetap utuh. +og_title: Simpan DOCX sebagai TXT – Ekspor Persamaan Word ke LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: simpan docx sebagai txt – Ekspor persamaan Word ke LaTeX dengan C# +url: /id/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# simpan docx sebagai txt – Ekspor persamaan Word ke LaTeX dengan C# + +Pernah perlu **save docx as txt** tetapi khawatir persamaan Anda akan menghilang atau menjadi karakter tak terbaca? Anda bukan satu-satunya. Banyak pengembang mengalami hal yang sama ketika mereka mencoba **convert word to txt** untuk pemrosesan lanjutan, terutama ketika file sumber berisi objek Office Math. + +Berita baiknya? Dengan beberapa baris C# dan opsi yang tepat, Anda tidak hanya dapat **convert Word to txt** tetapi juga mempertahankan setiap persamaan sebagai markup LaTeX yang bersih. Dalam tutorial ini kami akan membahas seluruh proses, menjelaskan mengapa setiap pengaturan penting, dan menunjukkan cara memverifikasi hasilnya. + +Kami akan membahas: + +* Menginstal pustaka Aspose.Words untuk .NET +* Memuat file `.docx` yang berisi persamaan matematika +* Mengonfigurasi `TxtSaveOptions` sehingga **how to export math** menjadi string yang ramah LaTeX +* Menyimpan file dan memeriksa output + +Pada akhir tutorial, Anda akan memiliki potongan kode yang dapat digunakan kembali yang memungkinkan Anda **save docx as txt** sambil mempertahankan setiap formula sebagai LaTeX—sempurna untuk pipeline ilmiah, generator situs statis, atau alur kerja apa pun yang memerlukan matematika dalam teks biasa. + +--- + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +* .NET 6.0 atau lebih baru (kode ini juga bekerja dengan .NET Framework 4.6+) +* Visual Studio 2022 (atau IDE lain yang Anda sukai) +* Paket NuGet **Aspose.Words for .NET** – instal dengan + +```bash +dotnet add package Aspose.Words +``` + +Tidak diperlukan konverter tambahan atau alat eksternal; Aspose.Words menangani semua proses secara internal. + +--- + +## Langkah 1: Instal dan referensikan Aspose.Words + +Pertama, tambahkan pustaka ke proyek Anda. Jika Anda menggunakan baris perintah, jalankan perintah di atas. Di Visual Studio Anda juga dapat klik kanan **Dependencies → Manage NuGet Packages** dan cari *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Gunakan versi stabil terbaru (per April 2026 versi 24.10). Rilis yang lebih baru membawa perbaikan bug untuk penanganan OfficeMath, sehingga Anda menghindari simbol yang hilang secara tak terduga. + +--- + +## Langkah 2: Muat dokumen sumber + +Sekarang kita memuat file `.docx` yang berisi persamaan yang ingin Anda pertahankan. Kelas `Document` mengabstraksi seluruh file Word, memberi Anda akses ke teks, gambar, dan objek Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Mengapa harus dimuat dulu? Aspose.Words mem-parsing file menjadi model objek, memungkinkan kami memeriksa atau memodifikasi konten sebelum memutuskan cara mengekspornya. Di sinilah keputusan **how to export math** mulai berpengaruh. + +--- + +## Langkah 3: Konfigurasikan TxtSaveOptions untuk ekspor LaTeX + +Inti solusi adalah kelas `TxtSaveOptions`. Secara default, menyimpan ke TXT menghapus seluruh Office Math. Menetapkan `OfficeMathExportMode` ke `LaTeX` memberi tahu pustaka untuk menerjemahkan setiap persamaan ke representasi LaTeX‑nya. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Mengapa LaTeX?** LaTeX adalah bahasa universal penerbitan ilmiah. Dengan mengekspor matematika dengan cara ini, Anda mempertahankan semantik persamaan alih‑alih gambar datar atau string yang rusak. Jika kemudian Anda memasukkan TXT ke prosesor Markdown yang mendukung MathJax, persamaan akan dirender dengan sempurna. + +--- + +## Langkah 4: Simpan dokumen sebagai teks biasa + +Dengan opsi yang sudah dikonfigurasi, langkah terakhir cukup satu baris kode yang menulis file ke disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Itu saja—`.docx` Anda kini menjadi file `.txt` di mana setiap persamaan muncul sebagai potongan LaTeX, siap untuk diproses lebih lanjut. + +--- + +## Memverifikasi output (Cara menyimpan txt dengan benar) + +Buka `MathSample.txt` di editor teks apa pun. Anda seharusnya melihat sesuatu seperti: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Jika Anda menemukan karakter khusus Word (misalnya `?` atau simbol yang hilang), periksa kembali bahwa: + +* Anda menggunakan versi Aspose.Words terbaru (versi lama memiliki bug pada OfficeMath). +* Dokumen sumber memang berisi objek **OfficeMath**—bukan objek Legacy Equation Editor. Untuk yang terakhir, Anda mungkin perlu mengonversinya secara manual atau menggunakan metode `ConvertMathToOfficeMath` sebelum menyimpan. + +--- + +## Variasi Umum & Kasus Tepi + +| Situasi | Apa yang harus dilakukan | +|-----------|------------| +| **Objek Legacy Equation Editor** | Panggil `doc.ConvertMathToOfficeMath()` sebelum langkah 3. | +| **Anda membutuhkan matematika Unicode biasa, bukan LaTeX** | Setel `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Dokumen besar (100 + MB)** | Stream operasi penyimpanan menggunakan `doc.Save(Stream, txtOptions)` untuk menghindari penggunaan memori yang tinggi. | +| **Anda ingin mempertahankan nama file asli** | Gunakan `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` saat membangun jalur output. | + +Penyesuaian ini menjawab pertanyaan “**how to export math**” untuk berbagai pipeline, memastikan solusi Anda tetap kuat terlepas dari sumbernya. + +--- + +## Contoh Kerja Penuh (Semua langkah dalam satu tempat) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Jalankan program, buka file `.txt` yang dihasilkan, dan Anda akan melihat persamaan LaTeX tertanam tepat di tempatnya. Ini adalah cara paling langsung untuk **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/indonesian/net/working-with-fonts/_index.md b/words/indonesian/net/working-with-fonts/_index.md index 11693f2f17..ba5f8cd87d 100644 --- a/words/indonesian/net/working-with-fonts/_index.md +++ b/words/indonesian/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ Bahasa Indonesia: [Atur Folder Font](./set-fonts-folder/) | Pelajari cara mengat | [Terima Pemberitahuan Peringatan](./receive-warning-notification/) Pelajari cara menerima pemberitahuan peringatan saat menggunakan Aspose.Words untuk .NET dan mengelola masalah atau peringatan apa pun dalam dokumen Anda. Bahasa Indonesia: | [Contoh Sumber Font Steam Sumber Daya](./resource-steam-font-source-example/) | Pelajari cara menggunakan Resource Stream Font Source untuk memuat font kustom ke Aspose.Words untuk .NET. Bahasa Indonesia: | [Dapatkan Substitusi Tanpa Sufiks](./get-substitution-without-suffixes/) | Dalam tutorial ini, pelajari cara mendapatkan penggantian tanpa sufiks dalam dokumen Word dengan Aspose.Words untuk .NET. | - +| [Penggantian Font Aspose – Deteksi Font yang Hilang dalam Dokumen Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Pelajari cara mendeteksi font yang hilang dalam dokumen Word menggunakan Aspose.Words untuk .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/indonesian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/indonesian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..31d661005e --- /dev/null +++ b/words/indonesian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Panduan substitusi font Aspose untuk mendeteksi font yang hilang saat + memuat dokumen Word. Pelajari cara mengonfigurasi pengaturan font dan menangani + font yang hilang secara efisien. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: id +og_description: Panduan substitusi font Aspose untuk mendeteksi font yang hilang saat + memuat dokumen Word. Pelajari cara mengonfigurasi pengaturan font dan menangani + font yang hilang secara efisien. +og_title: Penggantian Font Aspose – Deteksi Font yang Hilang dalam Dokumen Word +tags: +- Aspose.Words +- C# +- Font Management +title: Penggantian Font Aspose – Deteksi Font yang Hilang dalam Dokumen Word +url: /id/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Mendeteksi Font yang Hilang dalam Dokumen Word + +Pernah menemukan file Word yang tampak sempurna di satu mesin tetapi menunjukkan perubahan font yang aneh di mesin lain? Itu adalah masalah klasik **aspose font substitution**, dan biasanya berarti beberapa font tidak ada di sistem target. Dalam tutorial ini kami akan menunjukkan, langkah demi langkah, cara **mendeteksi font yang hilang** saat Anda **memuat dokumen Word**, cara **mengonfigurasi pengaturan font**, dan apa yang harus dilakukan untuk **menangani font yang hilang** dengan elegan. + +Kami akan membahas contoh C# lengkap yang dapat dijalankan, menjelaskan mengapa setiap baris penting, dan bahkan menunjukkan output konsol yang seharusnya Anda dapatkan. Pada akhir tutorial Anda akan dapat mendeteksi penggantian font begitu dokumen dimuat—tanpa tebakan. + +## Apa yang Akan Anda Pelajari + +- Cara mengaktifkan kolektor diagnostik Aspose.Words untuk peringatan font. +- Kode tepat yang diperlukan untuk **memuat dokumen Word** dengan **pengaturan font** khusus. +- Cara mengiterasi objek `WarningInfo` untuk menampilkan setiap font yang diganti. +- Tips untuk menekan peringatan yang tidak diinginkan atau menyediakan font cadangan. +- Contoh siap‑jalankan yang dapat Anda salin‑tempel ke Visual Studio. + +### Prasyarat + +- .NET 6.0 atau lebih baru (API berfungsi sama pada .NET Framework). +- Aspose.Words untuk .NET (paket NuGet `Aspose.Words`). +- File Word yang merujuk pada font yang tidak terpasang di sistem Anda (misalnya, `MissingFont.docx`). + +Jika Anda sudah memiliki semua itu, mari kita mulai. + +## Langkah 1 – Aktifkan Kolektor Diagnostik (Konfigurasi Pengaturan Font) + +Pertama-tama: Aspose.Words hanya mencatat peringatan penggantian font jika Anda mengaktifkannya. Hal ini dilakukan dengan membuat objek `FontSettings` dan menetapkannya ke instance `LoadOptions`. Anggap ini seperti menyalakan “lampu debug” untuk penanganan font. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Mengapa?** +Tanpa objek `FontSettings` kolektor peringatan tetap diam, dan Anda tidak akan pernah tahu font mana yang diganti. Dengan menginisialisasinya kosong, kami membiarkan Aspose menggunakan font sistem default *dan* melacak setiap penggantian. + +> **Pro tip:** Jika Anda mengetahui folder tertentu berisi font perusahaan, arahkan `FontSettings` ke sana dengan `SetFontsFolder("path")`. Hal ini dapat mengurangi jumlah peringatan font yang hilang. + +## Langkah 2 – Muat Dokumen dengan Opsi yang Dikonfigurasi (Muat Dokumen Word) + +Sekarang kolektor sudah aktif, muat file `.docx` Anda menggunakan `LoadOptions` yang sama. Ini adalah saat Aspose memindai dokumen, mencari setiap referensi font, dan memutuskan apakah penggantian diperlukan. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Mengapa ini penting?** +Jika Anda hanya memanggil `new Document("MissingFont.docx")`, pengaturan default akan diterapkan *dan* daftar peringatan tetap kosong. Menyertakan `loadOptions` memastikan kolektor diagnostik terhubung ke alur pemuatan. + +## Langkah 3 – Ambil dan Tampilkan Peringatan Penggantian Font (Deteksi Font yang Hilang) + +Setelah dokumen berada di memori, Aspose menyimpan semua peringatan di `document.WarningCallback.Warnings`. Lakukan iterasi pada koleksi tersebut, filter untuk `WarningType.FontSubstitution`, dan cetak deskripsinya. Setiap deskripsi memberi tahu Anda font mana yang hilang dan font apa yang digunakan sebagai gantinya. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Output konsol yang diharapkan** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Output tersebut memberi tahu Anda secara tepat font mana yang hilang pada mesin yang menjalankan kode. Anda kini dapat memutuskan apakah akan menginstal font yang hilang, menyematkannya ke dalam dokumen, atau mempertahankan penggantian. + +![Output konsol yang menampilkan peringatan penggantian font aspose](/images/aspose-font-substitution-console.png) + +*Teks alt gambar:* penggantian font aspose – output konsol yang menampilkan daftar font yang diganti + +## Langkah 4 – Opsional: Sesuaikan Perilaku Penggantian (Tangani Font yang Hilang) + +Terkadang Anda tidak hanya ingin mengetahui *bahwa* sebuah penggantian terjadi—Anda ingin mengontrol *bagaimana* itu terjadi. Aspose.Words memungkinkan Anda mendaftarkan `IFontSubstitutionRule` khusus. Berikut contoh singkat yang memaksa setiap font yang hilang menggunakan fallback ke `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Kapan Anda akan menggunakan ini?** +Jika Anda menghasilkan PDF untuk layanan web dan Anda tahu setiap klien dapat merender `Tahoma`, memaksa fallback menjamin konsistensi visual tanpa harus mengirimkan puluhan file font. + +## Contoh Lengkap yang Berfungsi (Semua Langkah Digabungkan) + +Berikut seluruh program yang dapat Anda tempel ke dalam proyek konsol baru. Program ini dapat dikompilasi apa adanya, dengan asumsi Anda telah menginstal paket NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Jalankan program, perhatikan konsol, dan Anda akan melihat setiap peristiwa font yang hilang dicetak. Dari situ Anda dapat memutuskan apakah akan menginstal font yang hilang, menyematkannya, atau mempertahankan fallback. + +## Pertanyaan yang Sering Diajukan + +**Q: Apakah ini bekerja dengan konversi PDF?** +Ya. Ketika Anda kemudian memanggil `doc.Save("output.pdf")`, font apa pun yang diganti selama pemuatan akan menjadi font yang disematkan dalam PDF. Jadi menangkap peringatan lebih awal membantu Anda menghindari perubahan font yang tidak terduga pada PDF akhir. + +**Q: Bagaimana jika saya memiliki banyak dokumen untuk diproses?** +Bungkus logika pemuatan dalam blok try‑catch dan gunakan kembali satu instance `FontSettings` untuk semua dokumen. Hal ini mengurangi beban dan menjaga kolektor peringatan tetap aktif untuk setiap file. + +**Q: Bisakah saya menonaktifkan peringatan sepenuhnya?** +Anda dapat mengatur `loadOptions.WarningCallback = null;` sebelum memuat, tetapi Anda akan kehilangan kemampuan untuk **mendeteksi font yang hilang**—yang biasanya bukan yang Anda inginkan. + +## Kesimpulan + +Kami telah membahas semua yang Anda perlukan untuk menguasai **aspose font substitution**: mengaktifkan kolektor diagnostik, memuat file Word dengan **pengaturan font** khusus, mengekstrak daftar font yang hilang, dan bahkan mengganti aturan penggantian default untuk **menangani font yang hilang** sesuai keinginan Anda. Dengan hanya beberapa baris C#, Anda mendapatkan visibilitas penuh terhadap masalah font yang biasanya tersembunyi di balik perubahan tata letak yang halus. + +Langkah selanjutnya? Coba sematkan font asli ke dalam dokumen dengan `FontSettings.SetFontsFolder` atau jelajahi `FontSourceBase` untuk memuat font dari basis data. Anda juga dapat bereksperimen dengan koleksi `Document.BuiltInStyle` untuk melihat bagaimana perubahan font pada tingkat gaya menyebar. + +Masih ada pertanyaan tentang Aspose.Words atau manajemen font? Tinggalkan komentar, jelajahi dokumentasi resmi Aspose, atau buat proyek baru dan coba kode di atas. Selamat coding, dan semoga dokumen Anda selalu ditampilkan persis seperti yang diharapkan! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/basic-conversions/_index.md b/words/italian/net/basic-conversions/_index.md index 9f8ae95ae3..637b30c4c3 100644 --- a/words/italian/net/basic-conversions/_index.md +++ b/words/italian/net/basic-conversions/_index.md @@ -34,6 +34,7 @@ | [Salva PDF in formato Word (Docx)](./pdf-to-docx/) | Scopri come convertire un PDF in un documento Word (Docx) utilizzando Aspose.Words per .NET in questa guida dettagliata e passo passo. Perfetta per gli sviluppatori. | | [Come esportare LaTeX da Word – Guida passo‑passo](./how-to-export-latex-from-word-step-by-step-guide/) | Scopri come esportare contenuti LaTeX da documenti Word usando Aspose.Words per .NET, con esempi pratici e istruzioni dettagliate. | | [Convertire Word in PDF in C# usando Aspose.Words – Guida](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Scopri come convertire documenti Word in PDF con C# usando Aspose.Words, con esempi di codice e passaggi dettagliati. | +| [Converti Word in PDF in C# – Guida completa con Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Scopri come convertire documenti Word in PDF con C# usando Aspose.Words, con esempi di codice e istruzioni passo‑passo. | | [Salva Word come PDF con Aspose.Words – Guida completa C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Scopri come salvare documenti Word in PDF usando Aspose.Words con una guida completa in C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/italian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..41c8df850a --- /dev/null +++ b/words/italian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-04-05 +description: Converti Word in PDF in C# usando Aspose.Words. Scopri come salvare docx + come PDF, esportare PDF accessibile e caricare documenti Word in modo efficiente. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: it +og_description: Converti Word in PDF in C# con una guida passo‑passo. Scopri come + salvare un file docx come PDF, esportare un PDF accessibile e caricare un documento + Word usando Aspose.Words. +og_title: Converti Word in PDF con C# – Tutorial completo di Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Converti Word in PDF con C# – Guida completa con Aspose.Words +url: /it/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti Word in PDF in C# – Tutorial di Programmazione Completo + +Ti sei mai chiesto come **convertire Word in PDF** senza lottare con strumenti da riga di comando ingombranti o servizi di terze parti? Non sei l'unico. Molti sviluppatori si trovano di fronte a questo ostacolo quando un cliente richiede un PDF accessibile direttamente da un file DOCX. La buona notizia? Con poche righe di C# e la potente libreria Aspose.Words, puoi trasformare un documento Word in un PDF conforme agli standard in un attimo. + +In questa guida percorreremo tutto ciò che devi sapere: dalle basi di **caricare documento Word**, passando per la configurazione delle opzioni corrette per **come esportare PDF accessibile**, e infine salvando il risultato così potrai **salvare docx come pdf** in modo affidabile. Alla fine avrai uno snippet pronto all'uso che potrai inserire in qualsiasi progetto .NET. + +> **Suggerimento professionale:** Se stai puntando alla conformità PDF/UA‑2 (lo standard di accessibilità richiesto da molte agenzie governative), lo stesso codice funziona senza passaggi aggiuntivi—basta impostare il flag `PdfCompliance` corretto. + +--- + +## Cosa Imparerai + +- Come **caricare documento Word** usando Aspose.Words in C#. +- Le impostazioni esatte necessarie per **come esportare PDF accessibile** (PDF/UA‑2). +- Un esempio completo e eseguibile che **salva docx come pdf** con una singola chiamata di metodo. +- Problemi comuni quando **c# converti docx pdf** e come evitarli. +- Metodi rapidi per verificare che il PDF generato soddisfi le aspettative di accessibilità. + +Nessuno strumento esterno, nessun file di configurazione oscuro—solo puro codice C# che puoi compilare oggi. + +--- + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +1. **.NET 6.0** (o qualsiasi versione .NET recente) installata. I framework più vecchi funzionano comunque, ma la sintassi qui sotto assume l'SDK moderno. +2. Una **licenza** per Aspose.Words per .NET. La libreria offre una prova gratuita, ma per la produzione avrai bisogno di una chiave valida. +3. Il pacchetto NuGet **Aspose.Words** aggiunto al tuo progetto: + +```bash +dotnet add package Aspose.Words +``` + +Tutto qui—nessun binario aggiuntivo, nessun interop COM, solo un riferimento NuGet pulito. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +--- + +## Implementazione Passo‑per‑Passo + +Di seguito suddividiamo il processo in blocchi logici. Ogni passo contiene un piccolo snippet di codice, una spiegazione del **perché** è importante, e un suggerimento basato sull'uso reale. + +### ## Converti Word in PDF – Carica il Documento Sorgente + +La prima cosa da fare è **caricare documento Word** in memoria. Aspose.Words astrae l'analisi OpenXML, così puoi lavorare con file DOCX, DOC o anche RTF senza preoccuparti delle particolarità del formato. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Perché è importante:** +Il caricamento del file crea un oggetto `Document` che rappresenta l'intero file Word, includendo intestazioni, piè di pagina, stili e metadati nascosti. Se salti questo passo o provi a leggere il file come flusso grezzo, perderai le informazioni di layout che in seguito determinano l'aspetto del PDF. + +> **Nota a margine:** Lo stesso costruttore `Document` funziona per `.doc` e `.rtf`. Questo significa che puoi **c# convertire docx pdf** anche quando la sorgente non è strettamente un DOCX. + +### ## Salva DOCX come PDF – Configura la Conformità PDF/UA‑2 + +Ora che il documento è in memoria, diciamo ad Aspose.Words come vogliamo che il PDF venga generato. Per la maggior parte dei casi d'uso, le impostazioni predefinite vanno bene, ma quando ti serve un **PDF accessibile** devi abilitare il flag di conformità PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Perché è importante:** +`PdfCompliance.PdfUAXmpA2` indica alla libreria di incorporare i tag e le strutture necessarie di cui i lettori di schermo hanno bisogno. Senza questo flag, potresti ottenere un PDF dall'aspetto perfetto ma che non supera un audit di accessibilità. + +> **Suggerimento:** Se ti serve solo un PDF normale, puoi rimuovere la riga `Compliance`. Il resto delle opzioni ti fornisce comunque un output di alta qualità. + +### ## Converti Word in PDF – Scrivi il File + +Con le opzioni pronte, l'ultimo passo è **salvare docx come pdf**. Questa singola chiamata esegue tutto il lavoro pesante: conversione del layout, incorporamento dei font e aggiunta dei tag di accessibilità. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Cosa ottieni:** +- Un file PDF in `outputPath` che rispecchia il layout di Word. +- Se hai usato il flag `PdfUAXmpA2`, il PDF sarà contrassegnato come conforme a PDF/UA‑2. +- Tutti i font sono incorporati, quindi il file appare identico su qualsiasi macchina. + +### ## Verifica il PDF Accessibile (Opzionale ma Consigliato) + +Dopo la conversione, è una buona idea ricontrollare che il PDF effettivamente **come esportare PDF accessibile** correttamente. Puoi usare strumenti gratuiti come il “Controllo Accessibilità” di Adobe Acrobat Reader o il validatore open‑source `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Se il validatore non segnala errori, hai convertito con successo **word in pdf** con pieno supporto di accessibilità. + +### ## Problemi Comuni Quando Converti DOCX in PDF con C# + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| Missing fonts | Il DOCX di origine utilizza un font personalizzato non installato sul server. | Imposta `EmbedFullFonts = true` o installa il font sulla macchina. | +| Large file size | Le immagini sono incorporate a piena risoluzione. | Usa `ImageCompression = PdfImageCompression.Jpeg` e imposta `JpegQuality` a un valore più basso. | +| Broken hyperlinks | I collegamenti puntano a percorsi relativi che non esistono sul client. | Assicurati che gli URL siano assoluti o regola la proprietà `HyperlinkTarget`. | +| Accessibility tags missing | Flag `Compliance` non impostato. | Aggiungi `Compliance = PdfCompliance.PdfUAXmpA2` come mostrato sopra. | + +Tenendo presenti questi aspetti, la tua routine **c# convert docx pdf** sarà robusta e pronta per la produzione. + +--- + +## Esempio Completo Funzionante + +Mettendo tutto insieme, ecco un'app console autonoma che puoi compilare ed eseguire subito. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Risultato atteso:** Dopo aver eseguito il programma, troverai `output.pdf` in `C:\Docs`. Aprilo con qualsiasi visualizzatore PDF; il layout dovrebbe corrispondere a `input.docx` pixel per pixel, e un controllo di accessibilità confermerà la conformità a PDF/UA‑2. + +--- + +## Conclusione + +Abbiamo appena illustrato una soluzione completa, end‑to‑end, su come **convertire word in pdf** usando C# e Aspose.Words. **Caricando documento Word**, configurando le corrette `PdfSaveOptions` e infine **salvando docx come pdf**, ottieni un PDF di alta qualità e accessibile con un codice minimo. Che tu stia costruendo un microservizio di generazione di documenti, un convertitore batch on‑premise, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-markdownsaveoptions/_index.md b/words/italian/net/programming-with-markdownsaveoptions/_index.md index b690ecf4d4..954e061cf2 100644 --- a/words/italian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/italian/net/programming-with-markdownsaveoptions/_index.md @@ -30,9 +30,10 @@ | [Salva docx come markdown – Guida completa C# con equazioni LaTeX](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | Impara a convertire file DOCX in Markdown includendo equazioni LaTeX con una guida completa in C#. | | [Salva docx come markdown – Guida completa C# con estrazione immagini](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Impara a convertire file DOCX in Markdown includendo l'estrazione delle immagini con una guida completa in C#. | | [Come esportare Markdown da Word – Guida completa C#](./how-to-export-markdown-from-word-complete-c-guide/) | Scopri come esportare documenti Word in Markdown con una guida completa in C#. | -| [Come esportare Markdown da DOCX – Guida completa](./how-to-export-markdown-from-docx-complete-guide/) | Scopri come esportare documenti DOCX in Markdown con una guida completa in C#. | +| [Come esportare Markdown da DOCX – Guida completa](./how-to-export-markdown-from-docx-complete-guide/) | Scopri come esportare documenti DOCX in Markdown con una guida completa. | | [Come salvare Markdown da DOCX – Guida passo‑passo](./how-to-save-markdown-from-docx-step-by-step-guide/) | Scopri come salvare documenti DOCX in Markdown con una guida passo‑passo completa. | - +| [Converti DOCX in Markdown – Estrai immagini da DOCX con Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Scopri come convertire DOCX in Markdown estraendo le immagini con Aspose.Words per .NET. | +| [Converti Word in Markdown – Guida completa con esportazione PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Scopri come convertire documenti Word in Markdown e generarne PDF/UA con una guida completa in C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/italian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..4cc80aecdd --- /dev/null +++ b/words/italian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Scopri come convertire DOCX in Markdown ed estrarre le immagini da DOCX + in C#. Guida passo‑passo con codice completo e consigli. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: it +og_description: Converti DOCX in Markdown ed estrai le immagini da DOCX usando Aspose.Words. + Tutorial completo in C# con codice, spiegazione e consigli sulle migliori pratiche. +og_title: Converti DOCX in Markdown – Estrai le immagini da DOCX in C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Converti DOCX in Markdown – Estrai le immagini da DOCX con Aspose.Words +url: /it/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti DOCX in Markdown – Estrai immagini da DOCX in C# + +Hai mai avuto bisogno di **convertire DOCX in Markdown** ma hai avuto problemi con le immagini che scompaiono nell'output? Non sei l'unico. In molti progetti la versione markdown è perfetta per il version‑control o i generatori di siti statici, però le immagini vengono lasciate indietro, trasformando un documento ricco in un file di testo spoglio. + +La buona notizia? Con poche righe di C# e Aspose.Words puoi **convertire DOCX in Markdown** *e* **estrarre immagini da DOCX** automaticamente. Questa guida ti accompagna passo passo, spiega perché ogni elemento è importante e ti mostra anche come mantenere ordinata la cartella delle immagini. + +## Cosa imparerai + +- Come caricare un DOCX che contiene immagini. +- Come definire un `IResourceSavingCallback` personalizzato che decide dove viene salvata ogni immagine. +- Come configurare `MarkdownSaveOptions` affinché il markdown generato faccia riferimento correttamente alle immagini estratte. +- Suggerimenti per gestire casi particolari come nomi di immagine duplicati o formati non PNG. +- Un esempio di codice completo, pronto per il copia‑incolla, che puoi eseguire subito. + +### Prerequisiti + +- .NET 6.0 o versioni successive (l'API funziona su .NET Core, .NET Framework e .NET 5+). +- Una licenza per **Aspose.Words for .NET** (la versione di prova gratuita è sufficiente per i test). +- Familiarità di base con C# e Visual Studio (o il tuo IDE preferito). + +Se li hai, immergiamoci. + +--- + +## Passo 1: Configura il progetto e installa Aspose.Words + +Per prima cosa, crea una nuova app console (o integrala in una soluzione esistente). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Suggerimento:** Usa l'ultima versione NuGet (a partire da aprile 2026 è la 24.12) per ottenere le più recenti migliorie di esportazione markdown. + +--- + +## Passo 2: Crea un callback per salvare le immagini dove desideri + +Aspose.Words ti consente di intercettare ogni risorsa (immagini, SVG, ecc.) che viene scritta durante l'esportazione markdown. Implementando `IResourceSavingCallback` puoi: + +1. Scegliere una cartella che si trovi accanto al tuo file markdown. +2. Generare un nome file unico (così non sovrascrivi mai un'immagine esistente). +3. Decidere il formato (qui forziamo PNG per coerenza). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Perché un nome basato su GUID? + +Se il DOCX di origine contiene due immagini con lo stesso nome originale, un semplice copia‑incolla sovrascriverebbe una delle due. Usare `Guid.NewGuid()` garantisce l'unicità, il che è particolarmente utile quando esegui la conversione più volte in una pipeline automatizzata. + +--- + +## Passo 3: Carica il DOCX e configura le opzioni Markdown + +Ora carichiamo il documento in memoria e colleghiamo il callback appena creato. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Cosa fa il codice, passo per passo + +| Step | Purpose | +|------|---------| +| **Definisci i percorsi** | Mantiene il progetto flessibile; puoi puntare a qualsiasi cartella senza ricompilare. | +| **Carica il DOCX** | `Document` analizza il file Word, rendendo accessibili tutti gli elementi (paragrafi, tabelle, immagini). | +| **Configura `MarkdownSaveOptions`** | `ResourceSavingCallback` è il gancio che estrae le immagini. Senza di esso, Aspose.Words incorporerebbe le immagini come stringhe base64 o le eliminerebbe del tutto, a seconda delle impostazioni. | +| **Salva** | `doc.Save` scrive il file markdown e attiva il callback per ogni immagine. | + +--- + +## Passo 4: Verifica l'output – Cosa dovresti vedere? + +Dopo aver eseguito il programma, apri `DocWithImages.md`. Noterai i link alle immagini markdown che appaiono così: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +E in `C:\Docs\MarkdownResources` troverai una serie di file PNG con nomi GUID. Aprine uno qualsiasi – dovrebbe essere identico alle immagini incorporate nel DOCX originale. + +Se apri il file markdown in un visualizzatore che rispetta i percorsi relativi (ad esempio l'anteprima di VS Code, GitHub o un generatore di siti statici), le immagini verranno visualizzate esattamente come in Word. + +### Problemi comuni e come evitarli + +| Sintomo | Causa probabile | Soluzione | +|---------|-----------------|-----------| +| Le immagini appaiono come link interrotti | `ResourceFileName` non è stato impostato, quindi il markdown punta a un file inesistente. | Assicurati che `args.ResourceFileName = newFileName;` sia impostato nel callback. | +| I file PNG sono molto grandi | Le immagini originali erano JPEG o BMP; convertirle in PNG può aumentare le dimensioni. | Rileva il formato originale tramite `args.ResourceContentType` e conservalo: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Le immagini duplicate appaiono ancora | Hai usato un nome file statico invece di un GUID. | Torna alla logica GUID o aggiungi un contatore per tipo di immagine. | +| La conversione genera `FileNotFoundException` | Il percorso del DOCX di origine è errato o la cartella non ha i permessi di lettura. | Verifica il percorso e concedi i permessi di file‑system appropriati. | + +--- + +## Passo 5: Ottimizzazioni avanzate (Opzionale) + +### 5.1 Conserva i formati originali delle immagini + +Se desideri che le immagini di output mantengano le loro estensioni originali, modifica il callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Incorpora le immagini come Base64 (quando *non* vuoi file separati) + +A volte è preferibile un markdown in un unico file (ad esempio per inviarlo via email). Modifica l'opzione: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Ma ricorda: **estrarre immagini da DOCX** è l'obiettivo principale per la maggior parte dei flussi di lavoro di siti statici, quindi l'approccio con cartella è solitamente la scelta migliore. + +--- + +## Esempio completo funzionante (pronto per copia‑incolla) + +Di seguito trovi l'intero programma in un unico file. Sostituisci i percorsi con i tuoi e esegui. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Eseguilo con `dotnet run`. Quando la console stampa la riga ✅, apri il file markdown e dovresti vedere le immagini visualizzate correttamente. + +--- + +## Conclusione + +Ora disponi di una **soluzione completa, pronta per la produzione, per convertire DOCX in Markdown ed estrarre immagini da DOCX** usando Aspose.Words in C#. La parola chiave principale appare in tutta la guida, rafforzando la rilevanza sia per i motori di ricerca sia per gli assistenti AI. + +In un unico passaggio il codice: + +1. Carica un documento Word. +2. Intercetta ogni immagine tramite `IResourceSavingCallback`. +3. Salva ogni immagine in una cartella prevedibile con un nome unico. +4. Genera markdown che fa riferimento a quelle immagini. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/italian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..c882b9c14d --- /dev/null +++ b/words/italian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Converti Word in Markdown rapidamente e impara anche come salvare come + PDF/UA in C#. Codice passo‑passo, consigli e gestione dei casi limite. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: it +og_description: Converti Word in Markdown e salva come PDF/UA con Aspose.Words. Scopri + il perché, il come e i consigli di best‑practice in una guida concisa. +og_title: Converti Word in Markdown – Tutorial completo C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Converti Word in Markdown – Guida completa con esportazione PDF/UA +url: /it/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converti Word in Markdown – Guida completa con esportazione PDF/UA + +Ti sei mai chiesto come **convertire Word in Markdown** senza perdere equazioni o immagini? Non sei il solo. Molti sviluppatori hanno bisogno di un modo affidabile per trasformare file `.docx` in Markdown pulito mantenendo la possibilità di **salvare come PDF/UA** per PDF conformi alle linee guida di accessibilità. In questo tutorial percorreremo una soluzione completa, pronta all'uso, usando Aspose.Words per .NET, spiegheremo perché ogni impostazione è importante e ti mostreremo come gestire le parti più complesse, come OfficeMath e le forme fluttuanti. + +Entro la fine di questa guida avrai un unico programma C# che: + +1. Carica un documento Word con recupero rilassato (così i file corrotti non interrompono l'esecuzione). +2. Lo esporta in Markdown, trasformando le equazioni in LaTeX e salvando le immagini tramite una callback personalizzata. +3. Salva lo stesso documento come file PDF/UA‑2 conforme, incorporando le forme fluttuanti come tag inline. + +Sembra molto? Nessun problema—iniziamo. + +## Di cosa avrai bisogno + +- **Aspose.Words per .NET** (ultima versione, 23.x al momento della stesura). +- Un ambiente di sviluppo .NET (Visual Studio 2022, Rider o la CLI `dotnet`). +- Un file Word di esempio (`input.docx`) posizionato in una cartella a cui puoi fare riferimento. +- Familiarità di base con la sintassi C#—nulla di esotico, solo qualche `using`. + +> **Consiglio esperto:** Se usi un gestore di pacchetti NuGet, aggiungi la libreria con +> `dotnet add package Aspose.Words` o tramite l'interfaccia NuGet di Visual Studio. + +## Passo 1 – Carica il documento Word con recupero rilassato + +Quando ricevi file Word da fonti esterne potrebbero contenere piccole corruzioni. Abilitare il recupero **Relaxed** dice ad Aspose.Words di continuare invece di lanciare un'eccezione. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Perché è importante:** +- `RecoveryMode.Relaxed` impedisce che un singolo paragrafo malformato abortisca l'intera conversione. +- Fornire un oggetto `FontSettings` assicura che eventuali font mancanti vengano sostituiti in modo elegante, cosa cruciale quando successivamente renderizzi le equazioni in LaTeX. + +## Passo 2 – Esporta in Markdown (OfficeMath → LaTeX, Immagini via Callback) + +Markdown non dispone di un modo nativo per rappresentare le equazioni Word. Aspose.Words può tradurre gli oggetti **OfficeMath** in LaTeX, che la maggior parte dei renderer Markdown comprende. Le immagini, invece, devono essere salvate da qualche parte; una **callback di salvataggio delle risorse** personalizzata ti dà il pieno controllo sulla struttura delle cartelle e sulla denominazione. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### La callback di salvataggio delle risorse + +Di seguito trovi una piccola implementazione che memorizza ogni immagine in una sottocartella chiamata `images` e assegna ai file i nomi `img001.png`, `img002.png`, ecc. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Perché ti serve:** +- Senza una callback, Aspose.Words crea una cartella piatta con nomi GUID casuali, il che rende il versionamento ingombrante. +- Controllando lo schema di denominazione mantieni il repository Markdown ordinato e riproducibile. + +### Output Markdown previsto + +Apri `doc.md` dopo l'esecuzione e vedrai: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Le equazioni appaiono come LaTeX racchiuso in `$$ … $$`, e le immagini fanno riferimento alla cartella `images` appena creata. + +## Passo 3 – Esporta in PDF/UA‑2 (pronto per l’accessibilità) + +Se devi condividere il documento con utenti che si affidano a lettori di schermo o altre tecnologie assistive, la conformità **PDF/UA‑2** è lo standard d'oro. Aspose.Words può imporla con un unico flag e può anche appiattire le forme fluttuanti in tag inline così da non perderle durante la conversione. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Perché PDF/UA è importante:** +- PDF/UA (Universal Accessibility) garantisce che il PDF risultante contenga tag appropriati, ordine di lettura logico e testo alternativo per le immagini. +- Impostare `ExportFloatingShapesAsInlineTag` assicura che forme come caselle di testo o callout non vengano omesse o spostate—a un errore comune nella conversione di layout complessi. + +### Verifica della conformità PDF/UA + +Dopo l'esportazione, apri il PDF in Adobe Acrobat Pro e avvia **“Accessibility Check”** (Strumenti → Accessibilità → Controllo completo). Se lo strumento riporta **0 errori**, hai avuto successo. + +## Casi limite e problemi comuni + +| Situazione | Cosa controllare | Correzione / Raccomandazione | +|------------------------------------------|-------------------------------------------------------|-----------------------------------------------------------| +| Il file Word contiene **font non supportati** | I font potrebbero essere sostituiti, rompendo il layout delle equazioni | Fornisci un `FontSettings` personalizzato con font di fallback. | +| Documenti molto grandi (> 100 MB) | Pressione sulla memoria durante la conversione | Usa `LoadOptions` con `LoadFormat.Docx` e streamma il file. | +| Le immagini sono grafiche vettoriali **EMF/WMF** | Potrebbero essere rasterizzate involontariamente | Convertile in PNG tramite `ImageSaveOptions` prima del salvataggio. | +| PDF/UA non supera la validazione su **tabelle nidificate** | Il tagging può diventare ambiguo | Abilita `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` per aiutare il motore. | +| È necessario **preservare stili personalizzati** | Markdown ha capacità di styling limitate | Esporta un file CSS insieme al Markdown e riferiscilo. | + +## Esempio completo funzionante (tutto il codice insieme) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Esegui il programma e troverai sia `doc.md` (con equazioni LaTeX e link alle immagini puliti) sia `doc.pdf` (completamente conforme a PDF/UA‑2) nella cartella `YOUR_DIRECTORY`. + +## Panoramica visiva + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Testo alternativo:* **convert word to markdown example** – diagramma del flusso di conversione da un file Word a Markdown e PDF/UA. + +## Riepilogo e prossimi passi + +Abbiamo appena **convertito Word in Markdown** mantenendo intatte le equazioni, salvato le immagini in una cartella ordinata e prodotto un file **PDF/UA** che supera i controlli di accessibilità. I punti chiave sono: + +- Usa `LoadOptions.RecoveryMode.Relaxed` per tollerare file Word imperfetti. +- Imposta `OfficeMathExportMode` su `LaTeX` per una resa pulita delle equazioni. +- Implementa una `ResourceSavingCallback` per controllare l'output delle immagini. +- Abilita `PdfCompliance.PdfUAXmpA2` e `ExportFloatingShapesAsInlineTag` per un PDF conforme agli standard. + +### Cosa esplorare dopo? + +- **CSS personalizzato per Markdown** – genera un foglio di stile che rispecchi gli stili di Word. +- **Elaborazione batch** – itera su una directory di file `.docx` per automatizzare migrazioni su larga scala. +- **Funzionalità avanzate PDF/UA** – aggiungi tag personalizzati, imposta attributi di lingua o incorpora descrizioni audio. +- **Integrazione con CI/CD** – assicurati che ogni build produca PDF accessibili automaticamente. + +Se incontri difficoltà, verifica che la versione di Aspose.Words corrisponda all'API usata qui, e ricorda che la documentazione della libreria è un'ottima fonte di riferimento secondario. + +Buon coding, e che i tuoi documenti rimangano sia **belli** sia accessibili! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/programming-with-txtsaveoptions/_index.md b/words/italian/net/programming-with-txtsaveoptions/_index.md index 63b26d774e..a3122c1eef 100644 --- a/words/italian/net/programming-with-txtsaveoptions/_index.md +++ b/words/italian/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Grazie a questi tutorial, potrai sfruttare appieno le funzionalità di Aspose.Wo | [Aggiungere segni Bidi nel documento Word](./add-bidi-marks/) | Scopri come aggiungere marcatori bidirezionali (Bidi) nei documenti Word utilizzando Aspose.Words per .NET con questa guida. Garantisci il corretto orientamento del testo per i contenuti multilingue. | | [Usa il carattere di tabulazione per livello per l'indentazione dell'elenco](./use-tab-character-per-level-for-list-indentation/) | Scopri come creare elenchi multilivello con rientro a tabulazione utilizzando Aspose.Words per .NET. Segui questa guida per formattare gli elenchi in modo preciso nei tuoi documenti. | | [Usa il carattere spazio per livello per l'indentazione dell'elenco](./use-space-character-per-level-for-list-indentation/) | Scopri come creare elenchi multilivello con rientro tramite spazi in Aspose.Words per .NET. Guida passo passo per una formattazione precisa dei documenti. | - +| [Salva docx come txt – Esporta le equazioni Word in LaTeX con C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Scopri come convertire le equazioni di Word in LaTeX durante il salvataggio di documenti DOCX in file TXT usando C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/italian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..91aabb419f --- /dev/null +++ b/words/italian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Salva docx come txt con Aspose.Words – converti rapidamente Word in txt + e scopri come esportare le equazioni matematiche in LaTeX. Codice C# semplice, nessun + tool aggiuntivo necessario. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: it +og_description: Salva docx come txt in C# e scopri come esportare la matematica in + LaTeX. Segui questa guida passo‑passo per convertire Word in txt mantenendo intatte + le equazioni. +og_title: Salva docx come txt – Esporta le equazioni di Word in LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Salva docx come txt – Esporta le equazioni Word in LaTeX con C# +url: /it/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# salva docx come txt – Esporta le equazioni Word in LaTeX con C# + +Ti è mai capitato di **save docx as txt** ma temere che le tue equazioni scompaiano o diventino incomprensibili? Non sei l'unico. Molti sviluppatori si trovano di fronte a questo ostacolo quando cercano di **convert word to txt** per l'elaborazione successiva, soprattutto quando il file di origine contiene oggetti Office Math. + +Buone notizie? Con poche righe di C# e le opzioni giuste, puoi non solo **convert Word to txt** ma anche mantenere ogni equazione come markup LaTeX pulito. In questo tutorial percorreremo l'intero processo, spiegheremo perché ogni impostazione è importante e ti mostreremo come verificare il risultato. + +Copriremo: + +* Installare la libreria Aspose.Words per .NET +* Caricare un `.docx` che contiene equazioni matematiche +* Configurare `TxtSaveOptions` in modo che **how to export math** diventi una stringa compatibile con LaTeX‑friendly +* Salvare il file e controllare l'output + +Alla fine, avrai uno snippet riutilizzabile che ti permette di **save docx as txt** preservando ogni formula in LaTeX—perfetto per pipeline scientifiche, generatori di siti statici o qualsiasi flusso di lavoro che richieda matematica in plain‑text. + +--- + +## Prerequisiti + +Prima di immergerci, assicurati di avere: + +* .NET 6.0 o successivo (il codice funziona anche con .NET Framework 4.6+) +* Visual Studio 2022 (o qualsiasi IDE tu preferisca) +* Il pacchetto NuGet **Aspose.Words for .NET** – installalo con + +```bash +dotnet add package Aspose.Words +``` + +Non sono richiesti convertitori aggiuntivi o strumenti esterni; Aspose.Words gestisce internamente le operazioni più complesse. + +--- + +## Passo 1: Installare e referenziare Aspose.Words + +Per prima cosa, aggiungi la libreria al tuo progetto. Se usi la riga di comando, esegui il comando sopra. In Visual Studio puoi anche fare clic con il tasto destro su **Dependencies → Manage NuGet Packages** e cercare *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Consiglio professionale:** Usa l'ultima versione stabile (a partire da aprile 2026 è la 24.10). Le versioni più recenti includono correzioni di bug per la gestione di OfficeMath, così eviterai simboli mancanti inaspettati. + +--- + +## Passo 2: Caricare il documento sorgente + +Ora carichiamo il `.docx` che contiene le equazioni che desideri conservare. La classe `Document` astrae l'intero file Word, fornendoti l'accesso a testo, immagini e oggetti Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Perché caricarlo prima? Aspose.Words analizza il file in un modello di oggetti, permettendoci di ispezionare o modificare il contenuto prima di decidere come esportarlo. È qui che le decisioni su **how to export math** iniziano a contare. + +--- + +## Passo 3: Configurare TxtSaveOptions per l'esportazione LaTeX + +Il cuore della soluzione è la classe `TxtSaveOptions`. Per impostazione predefinita, il salvataggio in TXT rimuove completamente Office Math. Impostare `OfficeMathExportMode` su `LaTeX` indica alla libreria di tradurre ogni equazione nella sua rappresentazione LaTeX. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Perché LaTeX?** LaTeX è la lingua franca della pubblicazione scientifica. Esportando la matematica in questo modo, mantieni la semantica dell'equazione invece di un'immagine piatta o una stringa incomprensibile. Se in seguito inserisci il TXT in un processore Markdown che supporta MathJax, le equazioni verranno renderizzate perfettamente. + +--- + +## Passo 4: Salvare il documento come plain‑text + +Con le opzioni configurate, l'ultimo passo è una singola riga di codice che scrive il file su disco. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Fatto—il tuo `.docx` è ora un file `.txt` in cui ogni equazione appare come snippet LaTeX, pronto per l'elaborazione successiva. + +--- + +## Verifica dell'output (Come salvare correttamente txt) + +Apri `MathSample.txt` in qualsiasi editor di testo. Dovresti vedere qualcosa di simile: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Se noti caratteri specifici di Word grezzi (ad es., `?` o simboli mancanti), verifica che: + +* Stai usando una versione recente di Aspose.Words (le versioni più vecchie avevano bug con OfficeMath). +* Il documento sorgente contiene effettivamente oggetti **OfficeMath**—non oggetti legacy dell'Equation Editor. Per questi ultimi, potresti doverli convertire manualmente o usare il metodo `ConvertMathToOfficeMath` prima del salvataggio. + +--- + +## Variazioni comuni e casi limite + +| Situazione | Cosa fare | +|-----------|------------| +| **Legacy Equation Editor** objects | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **You need plain Unicode math, not LaTeX** | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **You want to keep the original file name** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +Queste modifiche rispondono alla domanda “**how to export math**” per diversi pipeline, garantendo che la tua soluzione sia robusta indipendentemente dalla sorgente. + +--- + +## Esempio completo funzionante (Tutti i passaggi in un unico posto) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Esegui il programma, apri il `.txt` generato e vedrai le equazioni LaTeX incorporate proprio dove dovevano essere. Questo è il modo più semplice per **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/italian/net/working-with-fonts/_index.md b/words/italian/net/working-with-fonts/_index.md index 7049c8dca1..40c113fa61 100644 --- a/words/italian/net/working-with-fonts/_index.md +++ b/words/italian/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ Che tu voglia formattare il testo con diversi font, impostare regole di sostituz | [Ricevi notifica di avviso](./receive-warning-notification/) Scopri come ricevere una notifica di avviso quando usi Aspose.Words per .NET e come gestire eventuali problemi o avvisi nei tuoi documenti. | [Esempio di sorgente del font Steam Resource](./resource-steam-font-source-example/) | Scopri come utilizzare Resource Stream Font Source per caricare font personalizzati in Aspose.Words per .NET. | | [Ottieni la sostituzione senza suffissi](./get-substitution-without-suffixes/) | In questo tutorial imparerai come ottenere override senza suffisso in un documento Word con Aspose.Words per .NET. | - +| [Sostituzione dei Font Aspose – Rileva i Font Mancanti nei Documenti Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Scopri come rilevare i font mancanti nei documenti Word usando la sostituzione dei font di Aspose. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/italian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/italian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..15841d71a7 --- /dev/null +++ b/words/italian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Guida alla sostituzione dei font Aspose per rilevare i font mancanti + durante il caricamento di un documento Word. Scopri come configurare le impostazioni + dei font e gestire efficacemente i font mancanti. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: it +og_description: Guida alla sostituzione dei font di Aspose per rilevare i font mancanti + durante il caricamento di un documento Word. Scopri come configurare le impostazioni + dei font e gestire i font mancanti in modo efficiente. +og_title: Sostituzione dei Font Aspose – Rileva i Font Mancanti nei Documenti Word +tags: +- Aspose.Words +- C# +- Font Management +title: Sostituzione dei Font Aspose – Rileva i Font Mancanti nei Documenti Word +url: /it/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Sostituzione dei Font Aspose – Rilevare i Font Mancanti nei Documenti Word + +Ti è mai capitato di avere un file Word che appare perfetto su un computer ma mostra strani cambiamenti di font su un altro? Questo è il classico **aspose font substitution** problem, e di solito significa che alcuni font mancano sul sistema di destinazione. In questo tutorial ti mostreremo, passo dopo passo, come **detect missing fonts** quando **load a Word document**, come **configure font settings**, e cosa fare per **handle missing fonts** in modo elegante. + +Ti guideremo attraverso un esempio completo e eseguibile in C#, spiegheremo perché ogni riga è importante e ti mostreremo anche l'output della console che dovresti vedere. Alla fine sarai in grado di individuare le sostituzioni di font nel momento in cui un documento viene caricato—senza congetture. + +## Cosa Imparerai + +- Come abilitare il diagnostic collector di Aspose.Words per gli avvisi sui font. +- Il codice esatto necessario per **load a Word document** con **font settings** personalizzate. +- Come iterare sugli oggetti `WarningInfo` per elencare ogni font sostituito. +- Suggerimenti per sopprimere gli avvisi indesiderati o fornire font di fallback. +- Un esempio pronto all'uso che puoi copiare‑incollare in Visual Studio. + +### Prerequisiti + +- .NET 6.0 o successivo (l'API funziona allo stesso modo su .NET Framework). +- Aspose.Words per .NET (pacchetto NuGet `Aspose.Words`). +- Un file Word che faccia riferimento a un font che non hai installato (ad es., `MissingFont.docx`). + +Se hai tutto questo, immergiamoci. + +## Passo 1 – Abilitare il Diagnostic Collector (Configurare le Impostazioni dei Font) + +Prima di tutto: Aspose.Words registra gli avvisi di sostituzione dei font solo se glielo chiedi. Questo si fa creando un oggetto `FontSettings` e assegnandolo a un'istanza di `LoadOptions`. Pensalo come accendere le “lucette di debug” per la gestione dei font. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Perché?** +Senza un oggetto `FontSettings` il collector degli avvisi rimane silenzioso, e non saprai mai quali font sono stati sostituiti. Inizializzandolo vuoto lasciamo che Aspose usi i font di sistema predefiniti *e* tenga traccia di eventuali sostituzioni. + +> **Pro tip:** Se sai che una cartella specifica contiene i font aziendali, punta `FontSettings` lì con `SetFontsFolder("path")`. Questo può ridurre il numero di avvisi di font mancanti. + +## Passo 2 – Caricare il Documento con le Opzioni Configurate (Caricare Documento Word) + +Ora che il collector è attivo, carica il tuo file `.docx` usando le stesse `LoadOptions`. Questo è il momento in cui Aspose analizza il documento, cerca ogni riferimento a un font e decide se è necessaria una sostituzione. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Perché è importante?** +Se ti limitassi a chiamare `new Document("MissingFont.docx")`, verrebbero applicate le impostazioni predefinite *e* la lista degli avvisi rimarrebbe vuota. Passare `loadOptions` garantisce che il diagnostic collector sia collegato al processo di caricamento. + +## Passo 3 – Recuperare e Visualizzare gli Avvisi di Sostituzione dei Font (Rilevare i Font Mancanti) + +Dopo che il documento è in memoria, Aspose conserva gli avvisi in `document.WarningCallback.Warnings`. Scorri quella collezione, filtra per `WarningType.FontSubstitution` e stampa la descrizione. Ogni descrizione ti indica quale font era mancante e quale è stato usato al suo posto. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Output console previsto** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Quell'output ti indica esattamente quali font mancano sulla macchina che esegue il codice. Ora puoi decidere se installare i font mancanti, incorporarli nel documento, o mantenere la sostituzione. + +![Output della console che mostra gli avvisi di sostituzione dei font Aspose](/images/aspose-font-substitution-console.png) + +*Testo alternativo dell'immagine:* sostituzione dei font Aspose – output della console che elenca i font sostituiti + +## Passo 4 – Opzionale: Personalizzare il Comportamento di Sostituzione (Gestire i Font Mancanti) + +A volte non ti basta sapere *che* è avvenuta una sostituzione—vuoi controllare *come* avviene. Aspose.Words ti permette di registrare una regola personalizzata `IFontSubstitutionRule`. Di seguito un esempio rapido che forza qualsiasi font mancante a ricadere su `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Quando useresti questo?** +Se generi PDF per un servizio web e sai che tutti i client possono renderizzare `Tahoma`, forzare il fallback garantisce coerenza visiva senza dover distribuire decine di file di font. + +## Esempio Completo Funzionante (Tutti i Passi Combinati) + +Ecco l'intero programma che puoi incollare in un nuovo progetto console. Compila così com'è, a patto che tu abbia installato il pacchetto NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Esegui il programma, osserva la console, e vedrai stampato ogni evento di font mancante. Da lì potrai decidere se installare i font mancanti, incorporarli, o mantenere il fallback. + +## Domande Frequenti + +**Q: Questo funziona con la conversione PDF?** +Sì. Quando successivamente chiami `doc.Save("output.pdf")`, i font che sono stati sostituiti durante il caricamento saranno quelli incorporati nel PDF. Quindi intercettare gli avvisi in anticipo ti aiuta a evitare sorprese di cambiamenti di font nel PDF finale. + +**Q: E se devo elaborare molti documenti?** +Avvolgi la logica di caricamento in un blocco try‑catch e riutilizza una singola istanza di `FontSettings` per tutti i documenti. Questo riduce l'overhead e mantiene attivo il collector degli avvisi per ogni file. + +**Q: Posso sopprimere completamente gli avvisi?** +Puoi impostare `loadOptions.WarningCallback = null;` prima del caricamento, ma perderai la possibilità di **detect missing fonts**—cosa che di solito non è desiderata. + +## Conclusione + +Abbiamo coperto tutto ciò che ti serve per padroneggiare **aspose font substitution**: abilitare il diagnostic collector, caricare un file Word con **font settings** personalizzate, estrarre l'elenco dei font mancanti e persino sovrascrivere la regola di sostituzione predefinita per **handle missing fonts** a modo tuo. Con poche righe di C# ottieni piena visibilità sui problemi di font che altrimenti si nasconderebbero dietro sottili cambiamenti di layout. + +Passi successivi? Prova a incorporare i font originali nel documento con `FontSettings.SetFontsFolder` o esplora `FontSourceBase` per caricare i font da un database. Potresti anche sperimentare con la collezione `Document.BuiltInStyle` per vedere come le modifiche a livello di stile propagano i cambiamenti di font. + +Hai altre domande su Aspose.Words o sulla gestione dei font? Lascia un commento, consulta la documentazione ufficiale di Aspose, o avvia un nuovo progetto e gioca con il codice sopra. Buona programmazione, e che i tuoi documenti vengano sempre renderizzati esattamente come previsto! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/basic-conversions/_index.md b/words/japanese/net/basic-conversions/_index.md index d77fb6e793..075bf5a56f 100644 --- a/words/japanese/net/basic-conversions/_index.md +++ b/words/japanese/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [Word から LaTeX をエクスポートする方法 – ステップバイステップ ガイド](./how-to-export-latex-from-word-step-by-step-guide/) Aspose.Words for .NET を使用して、Word 文書を LaTeX 形式にエクスポートする方法をステップバイステップで解説します。 | | [C# で Word を PDF に変換する – ガイド](./convert-word-to-pdf-in-c-using-aspose-words-guide/) Aspose.Words for .NET を使用して C# で Word 文書を PDF に変換する方法を、ステップバイステップで解説します。コード例付きで開発者に最適です。 | | [Aspose.WordsでWordをPDFとして保存 – 完全なC#ガイド](./save-word-as-pdf-with-aspose-words-complete-c-guide/) Aspose.Words for .NET を使用して C# で Word 文書を PDF に変換する完全ガイドです。コード例付きで開発者に最適です。 | +| [C# で Word を PDF に変換 – Aspose.Words 完全ガイド](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) Aspose.Words for .NET を使用して C# で Word 文書を PDF に変換する方法を、ステップバイステップで解説します。コード例付きで開発者に最適です。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/japanese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..a32c63cbc1 --- /dev/null +++ b/words/japanese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,194 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words を使用して C# で Word を PDF に変換します。docx を PDF として保存する方法、アクセシブルな + PDF をエクスポートする方法、そして Word ドキュメントを効率的に読み込む方法を学びましょう。 +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: ja +og_description: C#でWordをPDFに変換するステップバイステップガイド。docxをPDFとして保存する方法、アクセシブルPDFをエクスポートする方法、そして + Aspose.Words を使用して Word 文書を読み込む方法をご紹介します。 +og_title: C#でWordをPDFに変換する – 完全なAspose.Wordsチュートリアル +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: C#でWordをPDFに変換 – Aspose.Words完全ガイド +url: /ja/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でWordをPDFに変換 – 完全プログラミングチュートリアル + +Ever wondered how to **convert word to pdf** without wrestling with fiddly command‑line tools or third‑party services? You're not the only one. Many developers hit that wall when a client asks for an accessible PDF straight from a DOCX file. The good news? With a few lines of C# and the powerful Aspose.Words library, you can turn a Word document into a standards‑compliant PDF in a snap. + +このガイドでは、知っておくべきすべてを順に解説します:**load word document** の基本から、適切なオプション設定、**how to export accessible pdf** まで、最後に結果を保存して **save docx as pdf** を確実に行う方法までです。最後まで読めば、任意の .NET プロジェクトに組み込める実行可能なスニペットが手に入ります。 + +> **Pro tip:** PDF/UA‑2 準拠(多くの政府機関が求めるアクセシビリティ標準)を目指す場合、同じコードで追加の手順は不要です—適切な `PdfCompliance` フラグを設定するだけです。 + +## 学べること + +- Aspose.Words を使用した C# での **load word document** 方法。 +- **how to export accessible pdf** に必要な正確な設定(PDF/UA‑2)。 +- 1 回のメソッド呼び出しで **save docx as pdf** を実現する完全な実行可能サンプル。 +- **c# convert docx pdf** 時の一般的な落とし穴と回避方法。 +- 生成された PDF がアクセシビリティ要件を満たすかを素早く確認する方法。 + +外部ツールや不明瞭な設定ファイルは不要です—今日コンパイルできる純粋な C# コードだけです。 + +## 前提条件 + +本題に入る前に、以下が揃っていることを確認してください: + +1. **.NET 6.0**(または最新の .NET バージョン)をインストール済み。古いフレームワークでも動作しますが、以下の構文は最新 SDK を前提としています。 +2. Aspose.Words for .NET の **license**。ライブラリは無料トライアルを提供していますが、本番環境では有効なキーが必要です。 +3. プロジェクトに **Aspose.Words** NuGet パッケージを追加: + +```bash +dotnet add package Aspose.Words +``` + +以上です—追加のバイナリや COM 相互運用は不要で、クリーンな NuGet 参照だけです。 + +![Aspose.Words を使用した C# での Word を PDF に変換](image-placeholder.png "Aspose.Words を使用した C# での Word を PDF に変換") + +## ステップバイステップ実装 + +以下では、プロセスを論理的なチャンクに分割します。各ステップには小さなコードスニペット、**why** が重要な理由の説明、そして実務で得たヒントが含まれます。 + +### ## Word を PDF に変換 – ソースドキュメントの読み込み + +最初に行うべきことは、**load word document** をメモリに読み込むことです。Aspose.Words は OpenXML の解析を抽象化するため、DOCX、DOC、さらには RTF ファイルでもフォーマットの細かい違いを気にせずに扱えます。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +ファイルを読み込むことで、ヘッダー、フッター、スタイル、隠しメタデータを含む Word ファイル全体を表す `Document` オブジェクトが作成されます。このステップを省略したり、生のストリームとしてファイルを読み込もうとすると、後で PDF のレイアウトに影響する情報が失われます。 + +> **Side note:** 同じ `Document` コンストラクタは `.doc` と `.rtf` でも機能します。つまり、ソースが必ずしも DOCX でなくても **c# convert docx pdf** が可能です。 + +### ## DOCX を PDF に保存 – PDF/UA‑2 準拠の設定 + +ドキュメントがメモリ上にあるので、Aspose.Words に PDF の生成方法を指示します。多くのケースではデフォルト設定で問題ありませんが、**accessible PDF** が必要な場合は PDF/UA‑2 準拠フラグを有効にする必要があります。 + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +`PdfCompliance.PdfUAXmpA2` は、スクリーンリーダーが必要とするタグや構造を埋め込むようライブラリに指示します。このフラグがなければ、見た目は完璧でもアクセシビリティ監査に合格しない PDF が生成される可能性があります。 + +> **Tip:** 通常の PDF だけが必要な場合は、`Compliance` 行を省略できます。他のオプションだけでも高品質な出力が得られます。 + +### ## Word を PDF に変換 – ファイルを書き出す + +オプションが準備できたら、最後のステップは **save docx as pdf** です。この一呼び出しでレイアウト変換、フォント埋め込み、アクセシビリティタグ付けというすべての重い処理が行われます。 + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- `outputPath` に作成される PDF ファイルは Word のレイアウトを忠実に再現します。 +- `PdfUAXmpA2` フラグを使用した場合、PDF は PDF/UA‑2 準拠としてマークされます。 +- すべてのフォントが埋め込まれるため、どのマシンでも同一の見た目になります。 + +### ## アクセシブル PDF の検証(任意だが推奨) + +変換後、PDF が本当に **how to export accessible pdf** できているか二重チェックすることをおすすめします。Adobe Acrobat Reader の「Accessibility Check」やオープンソースの `pdfcpu` バリデータなどの無料ツールを使用できます。 + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +バリデータがエラーを報告しなければ、完全なアクセシビリティサポート付きで **convert word to pdf** に成功したことになります。 + +### ## C# で DOCX を PDF に変換する際の一般的な落とし穴 + +| 問題 | 発生理由 | 対策 | +|------|----------|------| +| フォントが欠如 | ソースの DOCX がサーバーにインストールされていないカスタムフォントを使用しています。 | `EmbedFullFonts = true` を設定するか、マシンにフォントをインストールしてください。 | +| ファイルサイズが大きい | 画像がフル解像度で埋め込まれています。 | `ImageCompression = PdfImageCompression.Jpeg` を使用し、`JpegQuality` を低めに設定してください。 | +| ハイパーリンクが壊れる | リンクがクライアントに存在しない相対パスを指しています。 | URL を絶対パスにするか、`HyperlinkTarget` プロパティを調整してください。 | +| アクセシビリティタグが欠如 | `Compliance` フラグが設定されていません。 | 上記のように `Compliance = PdfCompliance.PdfUAXmpA2` を追加してください。 | + +これらを意識すれば、**c# convert docx pdf** の手順が堅牢で本番環境に適したものになります。 + +## 完全な動作例 + +すべてをまとめると、以下はすぐにコンパイルして実行できる自己完結型コンソールアプリです。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** プログラムを実行すると、`C:\Docs` に `output.pdf` が作成されます。任意の PDF ビューアで開くと、レイアウトは `input.docx` とピクセル単位で一致し、アクセシビリティチェックで PDF/UA‑2 準拠が確認されます。 + +## 結論 + +ここまでで、C# と Aspose.Words を使用して **convert word to pdf** を行う完全なエンドツーエンドのソリューションを解説しました。**load word document**、適切な `PdfSaveOptions` の設定、そして最終的に **save docx as pdf** を行うことで、最小限のコードで高品質かつアクセシブルな PDF が得られます。ドキュメント生成マイクロサービスやオンプレミスのバッチコンバータを構築する場合でも、 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-markdownsaveoptions/_index.md b/words/japanese/net/programming-with-markdownsaveoptions/_index.md index e40c007092..1a87d76bb1 100644 --- a/words/japanese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/japanese/net/programming-with-markdownsaveoptions/_index.md @@ -32,6 +32,8 @@ MarkdownSaveOptions を使用した Words Processing は、Aspose.Words for .NET | [Word から Markdown をエクスポートする方法 – 完全 C# ガイド](./how-to-export-markdown-from-word-complete-c-guide/) Aspose.Words for .NET を使用して、Word 文書を Markdown にエクスポートする完全な C# ガイドです。ステップバイステップで解説します。 | | [DOCX から Markdown にエクスポートする方法 – 完全ガイド](./how-to-export-markdown-from-docx-complete-guide/) Aspose.Words for .NET を使用して、DOCX 文書を Markdown にエクスポートする完全なガイドです。ステップバイステップで解説します。 | | [DOCX から Markdown に保存する方法 – ステップバイステップ ガイド](./how-to-save-markdown-from-docx-step-by-step-guide/) Aspose.Words for .NET を使用して、DOCX ファイルを Markdown に変換し保存する手順をステップバイステップで解説します。 | +| [docx を Markdown に変換 – 画像抽出付き完全 C# ガイド](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) Aspose.Words for .NET を使用して、DOCX ファイルから画像を抽出しながら Markdown に変換する手順をステップバイステップで解説します。 | +| [Word を Markdown に変換 – PDF/UA エクスポート付き完全ガイド](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) Aspose.Words for .NET を使用して、Word 文書を Markdown に変換し、PDF/UA 形式でエクスポートする完全な手順を解説します。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/japanese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..737591201e --- /dev/null +++ b/words/japanese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-04-05 +description: C#でDOCXをMarkdownに変換し、DOCXから画像を抽出する方法を学びましょう。フルコードとヒント付きのステップバイステップガイドです。 +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: ja +og_description: Aspose.Words を使用して DOCX を Markdown に変換し、DOCX から画像を抽出します。コード、解説、ベストプラクティスのヒントを含む完全な + C# チュートリアル。 +og_title: DOCX を Markdown に変換 – C# で DOCX から画像を抽出 +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX を Markdown に変換 – Aspose.Words で DOCX から画像を抽出 +url: /ja/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX を Markdown に変換 – C# で DOCX から画像を抽出 + +DOCX を **Markdown に変換** したいが、出力で画像が消えてしまうことに悩んだことはありませんか? あなただけではありません。多くのプロジェクトで Markdown バージョンはバージョン管理や静的サイトジェネレータに最適ですが、画像が残らず、リッチな文書が無味乾燥なテキストファイルになってしまいます。 + +良いニュースです。数行の C# と Aspose.Words を使えば、**DOCX を Markdown に変換** しながら **DOCX から画像を自動的に抽出** できます。このガイドでは、全工程を順を追って解説し、各要素がなぜ重要かを説明し、画像フォルダーを整理する方法まで示します。 + +## 本チュートリアルで学べること + +- 画像を含む DOCX の読み込み方法 +- 画像の保存先を決定するカスタム `IResourceSavingCallback` の定義方法 +- 抽出した画像を正しく参照できるように `MarkdownSaveOptions` を設定する方法 +- 重複画像名や PNG 以外の形式といったエッジケースへの対処法 +- 今日からすぐに実行できる、コピー&ペースト可能な完全サンプルコード + +### 前提条件 + +- .NET 6.0 以上(API は .NET Core、.NET Framework、.NET 5+ でも動作) +- **Aspose.Words for .NET** のライセンス(無料トライアルでもテスト可能) +- C# と Visual Studio(またはお好みの IDE)に関する基本的な知識 + +これらが揃っていれば、さっそく始めましょう。 + +--- + +## Step 1: Set Up the Project and Install Aspose.Words + +まず、新しいコンソール アプリを作成します(既存のソリューションに統合しても構いません)。 + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tip:** 最新の NuGet バージョン(2026年4月時点で 24.12)を使用すると、最新の Markdown エクスポート機能が利用できます。 + +--- + +## Step 2: Create a Callback to Save Images Where You Want Them + +Aspose.Words は Markdown エクスポート中に書き出されるすべてのリソース(画像、SVG など)をフックできます。`IResourceSavingCallback` を実装することで、以下が可能になります。 + +1. Markdown ファイルの隣に配置するフォルダーを選択 +2. ユニークなファイル名を生成(既存画像を上書きしないように) +3. 形式を決定(ここでは一貫性のため PNG に統一) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### なぜ GUID ベースの名前にするのか? + +元の DOCX に同名の画像が複数含まれている場合、単純にコピー&ペーストするとどちらかが上書きされてしまいます。`Guid.NewGuid()` を使用すれば一意性が保証されるため、特に自動化パイプラインで何度も変換を実行する際に便利です。 + +--- + +## Step 3: Load the DOCX and Wire Up the Markdown Options + +次に、ドキュメントをメモリに読み込み、先ほど作成したコールバックを設定します。 + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### コードの流れをステップごとに解説 + +| Step | Purpose | +|------|---------| +| **Define paths** | プロジェクトの柔軟性を保ち、再コンパイルせずに任意のフォルダーを指せるようにします。 | +| **Load the DOCX** | `Document` が Word ファイルを解析し、段落・表・画像などすべての要素にアクセスできるようにします。 | +| **Configure `MarkdownSaveOptions`** | `ResourceSavingCallback` が画像抽出のフックになります。これが無いと、Aspose.Words は画像を Base64 文字列として埋め込むか、設定次第で完全に除外してしまいます。 | +| **Save** | `doc.Save` が Markdown ファイルを書き出し、画像ごとにコールバックを呼び出します。 | + +--- + +## Step 4: Verify the Output – What Should You See? + +プログラムを実行したら `DocWithImages.md` を開きます。以下のような Markdown 画像リンクが生成されているはずです。 + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +そして `C:\Docs\MarkdownResources` フォルダー内に、GUID 名の PNG ファイルが多数作成されます。任意のファイルを開くと、元の DOCX に埋め込まれていた画像と同一であることが確認できます。 + +相対パスを尊重するビューア(例: VS Code のプレビュー、GitHub、静的サイトジェネレータ)で Markdown を開くと、画像は Word と同様に正しく表示されます。 + +### よくある落とし穴と回避策 + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| 画像が壊れたリンクとして表示される | `ResourceFileName` が設定されていないため、Markdown が存在しないファイルを指している | コールバック内で `args.ResourceFileName = newFileName;` を確実に設定 | +| PNG ファイルが巨大になる | 元画像が JPEG や BMP で、PNG へ変換したためサイズが増加 | `args.ResourceContentType` で元形式を検出し、拡張子を保持: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| 重複画像がまだ残る | 静的なファイル名を使用したため GUID が使われていない | GUID ロジックに戻すか、画像タイプごとにカウンタを追加 | +| `FileNotFoundException` がスローされる | DOCX のパスが間違っている、またはフォルダーに読み取り権限がない | パスを確認し、適切なファイルシステム権限を付与 | + +--- + +## Step 5: Advanced Tweaks (Optional) + +### 5.1 Preserve Original Image Formats + +出力画像の拡張子を元のままにしたい場合は、コールバックを次のように変更します。 + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Embed Images as Base64 (When You *Don’t* Want Separate Files) + +単一ファイルの Markdown が欲しいケース(例: メール送信時)では、以下のオプションに変更します。 + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +ただし、**extract images from DOCX** がほとんどの静的サイトワークフローの主目的であるため、フォルダー方式が一般的に推奨されます。 + +--- + +## Full Working Example (Copy‑Paste Ready) + +以下は 1 ファイルにまとめた完全なプログラムです。パスを自分の環境に合わせて置き換え、実行してください。 + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +`dotnet run` で実行します。コンソールに ✅ が表示されたら、Markdown ファイルを開き、画像が正しく表示されていることを確認してください。 + +--- + +## Conclusion + +これで **DOCX を Markdown に変換し、C# で DOCX から画像を抽出する** 完全な本番環境向けソリューションが手に入りました。ガイド全体で主要キーワードが繰り返し登場するため、検索エンジンや AI アシスタントに対する関連性も高まります。 + +コードは次の 4 ステップで完結します。 + +1. Word 文書をロード +2. `IResourceSavingCallback` で全画像をフック +3. ユニークな名前で予測可能なフォルダーに保存 +4. 画像を参照する Markdown を生成 + +ここからは、例えば + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/japanese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..83a3be25b2 --- /dev/null +++ b/words/japanese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-05 +description: Word を Markdown に素早く変換し、C# で PDF/UA として保存する方法も学べます。ステップバイステップのコード、ヒント、エッジケースの対処法。 +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: ja +og_description: Aspose.WordsでWordをMarkdownに変換し、PDF/UAとして保存。なぜ行うか、やり方、ベストプラクティスのコツを一つの簡潔なガイドで学べます。 +og_title: Word を Markdown に変換 – 完全な C# チュートリアル +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word を Markdown に変換する – PDF/UA エクスポート付き完全ガイド +url: /ja/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word を Markdown に変換 – PDF/UA エクスポート付き完全ガイド + +数式や画像を失わずに **Word を Markdown に変換** する方法を考えたことはありませんか? あなただけではありません。多くの開発者が `.docx` ファイルをクリーンな Markdown に変換し、さらにアクセシビリティに準拠した PDF を作成するために **PDF/UA として保存** できる信頼できる方法を求めています。このチュートリアルでは、Aspose.Words for .NET を使用した完全な実行可能ソリューションを順に解説し、各設定がなぜ重要かを説明し、OfficeMath やフローティングシェイプといったやや難しい部分の扱い方を示します。 + +このガイドの最後までに、次のことができる単一の C# プログラムが手に入ります: + +1. リラックスリカバリで Word 文書を読み込み(破損したファイルでも実行が中断されません)。 +2. Markdown にエクスポートし、数式を LaTeX に変換し、画像はカスタムコールバックで保存します。 +3. 同じ文書を PDF/UA‑2 準拠のファイルとして保存し、フローティングシェイプをインラインタグとして埋め込みます。 + +たくさんあるように聞こえますか? 心配無用です—さっそく始めましょう。 + +## 必要なもの + +- **Aspose.Words for .NET**(執筆時点での最新バージョン 23.x)。 +- .NET 開発環境(Visual Studio 2022、Rider、または `dotnet` CLI)。 +- 参照できるフォルダーに配置したサンプル Word ファイル(`input.docx`)。 +- C# 構文の基本的な知識—特別なことはなく、いくつかの `using` 文だけです。 + +> **プロのコツ:** NuGet パッケージマネージャーを使用している場合は、次のコマンドでライブラリを追加してください +> `dotnet add package Aspose.Words` または Visual Studio の NuGet UI から。 + +## Step 1 – リラックスリカバリで Word 文書を読み込む + +外部から受け取った Word ファイルには軽度の破損が含まれていることがあります。**Relaxed** リカバリを有効にすると、Aspose.Words は例外をスローせずに処理を続行します。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**なぜ重要か:** +- `RecoveryMode.Relaxed` は、単一の不正な段落が変換全体を中止するのを防ぎます。 +- `FontSettings` オブジェクトを提供することで、欠落したフォントが適切に代替され、後で数式を LaTeX にレンダリングする際に重要です。 + +## Step 2 – Markdown へエクスポート(OfficeMath → LaTeX、画像はコールバックで) + +Markdown には Word の数式を表すネイティブな方法がありません。Aspose.Words は **OfficeMath** オブジェクトを LaTeX に変換でき、ほとんどの Markdown レンダラーが理解できます。ただし、画像はどこかに保存する必要があります。カスタム **リソース保存コールバック** を使用すると、フォルダー構造と名前付けを完全に制御できます。 + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### リソース保存コールバック + +以下は、すべての画像を `images` というサブフォルダーに保存し、ファイル名を `img001.png`、`img002.png` などと付ける小さな実装例です。 + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**なぜ必要か:** +- コールバックがないと、Aspose.Words はランダムな GUID 名のフラットなフォルダーを作成し、バージョン管理が乱雑になります。 +- 名前付けスキームを制御することで、Markdown リポジトリを整然と再現可能に保てます。 + +### 期待される Markdown 出力 + +実行後に `doc.md` を開くと、次のようになります: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +数式は `$$ … $$` で囲まれた LaTeX として表示され、画像は先ほど作成した `images` フォルダーを参照します。 + +## Step 3 – PDF/UA‑2 へエクスポート(アクセシビリティ対応) + +スクリーンリーダーやその他の支援技術に依存するユーザーと文書を共有する必要がある場合、**PDF/UA‑2** 準拠が金字塔です。Aspose.Words は単一のフラグでこれを強制でき、フローティングシェイプをインラインタグにフラット化して変換時に失われないようにすることもできます。 + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**なぜ PDF/UA が重要か:** +- PDF/UA(Universal Accessibility)は、生成された PDF に適切なタグ付け、論理的な読み順、画像の代替テキストが含まれることを保証します。 +- `ExportFloatingShapesAsInlineTag` を設定すると、テキストボックスやコールアウトなどのシェイプが省略されたり位置がずれたりすることを防げます—複雑なレイアウト変換時の一般的な落とし穴です。 + +### PDF/UA 準拠の検証 + +エクスポート後、Adobe Acrobat Pro で PDF を開き、**“Accessibility Check”**(ツール → アクセシビリティ → フルチェック)を実行します。ツールが **0 エラー** を報告すれば成功です。 + +## エッジケースと一般的な落とし穴 + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word ファイルに **未対応フォント** が含まれる | フォントが代替され、数式のレイアウトが崩れる可能性 | `FontSettings` にフォールバックフォントを設定する。 | +| 大容量ドキュメント(> 100 MB) | 変換中のメモリ圧迫 | `LoadOptions` に `LoadFormat.Docx` を指定し、ファイルをストリームで読み込む。 | +| 画像が **EMF/WMF** ベクターグラフィック | 意図せずラスタライズされる可能性 | 保存前に `ImageSaveOptions` を使用して PNG に変換する。 | +| PDF/UA が **入れ子テーブル** で検証に失敗 | タグ付けが曖昧になる | `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` を有効にしてエンジンを支援する。 | +| **カスタムスタイルの保持** が必要 | Markdown のスタイリング機能が限定的 | Markdown と一緒に CSS ファイルをエクスポートし、参照する。 | + +## 完全動作例(すべてのコードをまとめて) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +プログラムを実行すると、`YOUR_DIRECTORY` に `doc.md`(LaTeX 数式とクリーンな画像リンク付き)と `doc.pdf`(完全に PDF/UA‑2 準拠)の両方が作成されます。 + +## ビジュアル概要 + +![Word を Markdown に変換する例](https://example.com/placeholder.png "Word を Markdown に変換する例 – 入力 Word、Markdown 出力、PDF/UA ファイルを表示") + +*Alt text:* **Word を Markdown に変換する例** – Word ファイルから Markdown と PDF/UA への変換パイプラインの図。 + +## まとめと次のステップ + +私たちは **Word を Markdown に変換** し、数式をそのまま保持し、画像を整理されたフォルダーに保存し、アクセシビリティチェックに合格する **PDF/UA として保存** できるファイルを作成しました。主なポイントは次のとおりです: + +- `LoadOptions.RecoveryMode.Relaxed` を使用して、完璧でない Word ファイルを許容する。 +- `OfficeMathExportMode` を `LaTeX` に設定し、数式をクリーンにレンダリングする。 +- `ResourceSavingCallback` を実装して画像出力を制御する。 +- `PdfCompliance.PdfUAXmpA2` と `ExportFloatingShapesAsInlineTag` を有効にして、標準準拠の PDF を作成する。 + +### 次に探求すべきことは? + +- **Custom CSS for Markdown** – Word のスタイルを反映したスタイルシートを生成する。 +- **Batch processing** – `.docx` ファイルが入ったディレクトリをループして、大規模な移行を自動化する。 +- **Advanced PDF/UA features** – カスタムタグを追加したり、言語属性を設定したり、音声説明を埋め込んだりする。 +- **Integration with CI/CD** – すべてのビルドで自動的にアクセシブルな PDF を生成することを保証する。 + +問題が発生した場合は、使用している Aspose.Words のバージョンがここで使用した API と一致しているか再確認し、ライブラリの公式ドキュメントが信頼できる二次参照であることを覚えておいてください。 + +コーディングを楽しんで、あなたの文書が美しく **かつ** アクセシブルであり続けますように! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/programming-with-txtsaveoptions/_index.md b/words/japanese/net/programming-with-txtsaveoptions/_index.md index daee4aa39b..6d49b103a4 100644 --- a/words/japanese/net/programming-with-txtsaveoptions/_index.md +++ b/words/japanese/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Aspose.Words for .NET のチュートリアルでは、Word 文書の操作を | [Word文書にBidiマークを追加する](./add-bidi-marks/) このガイドでは、Aspose.Words for .NET を使用して Word 文書に双方向(Bidi)マークを追加する方法を学びます。多言語コンテンツで適切なテキスト方向を確保します。 | | [リストのインデントにはレベルごとにタブ文字を使用する](./use-tab-character-per-level-for-list-indentation/) Aspose.Words for .NET を使用して、タブ付きインデント付きの多階層リストを作成する方法を学びましょう。このガイドに従って、ドキュメント内のリストを正確に書式設定しましょう。 | | [リストのインデントにはレベルごとにスペース文字を使用する](./use-space-character-per-level-for-list-indentation/) Aspose.Words for .NET で、スペース文字によるインデントを含む多階層リストを作成する方法を学びましょう。ドキュメントの正確な書式設定のためのステップバイステップガイドです。 | - +| [docx を txt として保存 – C# で Word の数式を LaTeX にエクスポート](./save-docx-as-txt-export-word-equations-to-latex-with-c/) Aspose.Words for .NET を使用して、docx をテキストに変換し、数式を LaTeX 形式でエクスポートする方法を学びます。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/japanese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..49bae35469 --- /dev/null +++ b/words/japanese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Wordsでdocxをtxtに保存 – Wordをすばやくtxtに変換し、数式をLaTeXとしてエクスポートする方法を学びましょう。シンプルなC#コードで、追加ツールは不要です。 +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: ja +og_description: C#でdocxをtxtとして保存し、数式をLaTeXにエクスポートする方法を確認してください。手順に従って、数式をそのまま残した状態でWordをtxtに変換するガイドです。 +og_title: docx を txt に保存 – Word の数式を LaTeX にエクスポート +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx を txt に保存 – C# で Word の数式を LaTeX にエクスポート +url: /ja/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx を txt に保存 – C# で Word の数式を LaTeX にエクスポート + +Ever needed to **save docx as txt** but worried that your equations would disappear or turn into unreadable gibberish? You're not the only one. Many developers hit that wall when they try to **convert word to txt** for downstream processing, especially when the source file contains Office Math objects. + +**docx を txt に保存したい**が、数式が消えてしまったり読めない文字化けになることを心配したことはありませんか? あなただけではありません。特にソースファイルに Office Math オブジェクトが含まれている場合、下流処理のために **convert word to txt** を試みる多くの開発者が同じ壁にぶつかります。 + +The good news? With a few lines of C# and the right options, you can not only **convert Word to txt** but also keep every equation as clean LaTeX markup. In this tutorial we’ll walk through the whole process, explain why each setting matters, and show you how to verify the result. + +良いニュースです。数行の C# と適切なオプションさえあれば、**convert Word to txt** できるだけでなく、すべての数式をきれいな LaTeX マークアップとして保持できます。このチュートリアルでは、全工程を順に解説し、各設定がなぜ重要かを説明し、結果の検証方法を示します。 + +We'll cover: + +* Installing the Aspose.Words for .NET library +* Loading a `.docx` that contains math equations +* Configuring `TxtSaveOptions` so that **how to export math** becomes a LaTeX‑friendly string +* Saving the file and checking the output + +以下をカバーします: + +* Aspose.Words for .NET ライブラリのインストール +* 数式を含む `.docx` の読み込み +* `TxtSaveOptions` を設定し、**how to export math** を LaTeX 形式の文字列に変換 +* ファイルを保存し、出力を確認 + +By the end, you’ll have a reusable snippet that lets you **save docx as txt** while preserving every formula as LaTeX—perfect for scientific pipelines, static site generators, or any workflow that needs plain‑text math. + +最終的に、**save docx as txt** しながらすべての数式を LaTeX として保持できる再利用可能なスニペットが手に入ります。科学的パイプライン、静的サイトジェネレータ、またはプレーンテキストの数式が必要なあらゆるワークフローに最適です。 + +--- + +## Prerequisites + +## 前提条件 + +Before we dive in, make sure you have: + +始める前に、以下が揃っていることを確認してください: + +* .NET 6.0 or later (the code works with .NET Framework 4.6+ as well) +* Visual Studio 2022 (or any IDE you prefer) +* The **Aspose.Words for .NET** NuGet package – install it with + +```bash +dotnet add package Aspose.Words +``` + +* .NET 6.0 以降(コードは .NET Framework 4.6 以降でも動作します) +* Visual Studio 2022(またはお好みの IDE) +* **Aspose.Words for .NET** NuGet パッケージ – 以下のコマンドでインストール + +No additional converters or external tools are required; Aspose.Words handles the heavy lifting internally. + +追加のコンバータや外部ツールは不要です。Aspose.Words が内部で重い処理をすべて行います。 + +--- + +## Step 1: Install and reference Aspose.Words + +## 手順 1: Aspose.Words をインストールして参照設定 + +First, add the library to your project. If you’re using the command line, run the command above. In Visual Studio you can also right‑click **Dependencies → Manage NuGet Packages** and search for *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Use the latest stable version (as of April 2026 it’s 24.10). Newer releases bring bug fixes for OfficeMath handling, so you’ll avoid surprising missing symbols. + +> **プロのコツ:** 最新の安定版を使用してください(2026年4月時点で 24.10)。新しいリリースは OfficeMath の処理に関するバグ修正が含まれており、予期せぬ記号欠損を回避できます。 + +--- + +## Step 2: Load the source document + +## 手順 2: ソースドキュメントを読み込む + +Now we pull the `.docx` that contains the equations you want to keep. The `Document` class abstracts the whole Word file, giving you access to text, images, and Office Math objects. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Why load it first? Aspose.Words parses the file into an object model, allowing us to inspect or modify content before we decide how to export it. This is where **how to export math** decisions start to matter. + +最初に読み込む理由は何ですか? Aspose.Words はファイルをオブジェクトモデルに解析し、エクスポート方法を決定する前に内容を検査・変更できるようにします。ここで **how to export math** の選択が重要になります。 + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +## 手順 3: LaTeX エクスポート用に TxtSaveOptions を設定 + +The heart of the solution is the `TxtSaveOptions` class. By default, saving to TXT strips out Office Math entirely. Setting `OfficeMathExportMode` to `LaTeX` tells the library to translate each equation into its LaTeX representation. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX is the lingua franca of scientific publishing. By exporting math this way, you keep the semantics of the equation instead of a flat image or a garbled string. If you later feed the TXT into a Markdown processor that supports MathJax, the equations will render perfectly. + +**なぜ LaTeX か?** LaTeX は科学出版の共通言語です。この方法で数式をエクスポートすれば、画像や文字化けした文字列ではなく、数式の意味論を保持できます。後で MathJax 対応の Markdown プロセッサに TXT を渡せば、数式は正しくレンダリングされます。 + +--- + +## Step 4: Save the document as plain‑text + +## 手順 4: ドキュメントをプレーンテキストとして保存 + +With the options configured, the final step is a one‑liner that writes the file to disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +That’s it—your `.docx` is now a `.txt` file where every equation appears as a LaTeX snippet, ready for downstream consumption. + +以上です。`.docx` が `.txt` に変換され、すべての数式が LaTeX スニペットとして埋め込まれた状態になり、下流の処理にすぐ利用できます。 + +--- + +## Verifying the output (How to save txt correctly) + +## 出力の検証(txt を正しく保存する方法) + +Open `MathSample.txt` in any text editor. You should see something like: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +If you spot raw Word‑specific characters (e.g., `?` or missing symbols), double‑check that: + +`MathSample.txt` を任意のテキストエディタで開きます。以下のような内容が表示されるはずです: + +もし Word 固有の文字(例: `?` や欠損記号)が見つかったら、次を再確認してください: + +* You’re using a recent Aspose.Words version (older builds had bugs with OfficeMath). +* The source document actually contains **OfficeMath** objects—not legacy Equation Editor objects. For the latter, you may need to convert them manually or use the `ConvertMathToOfficeMath` method before saving. + +* 最新の Aspose.Words バージョンを使用しているか(古いビルドは OfficeMath のバグがありました)。 +* ソースドキュメントが実際に **OfficeMath** オブジェクトを含んでいるか(レガシーな Equation Editor オブジェクトではありません)。レガシーの場合は手動で変換するか、保存前に `ConvertMathToOfficeMath` メソッドを使用する必要があります。 + +--- + +## Common Variations & Edge Cases + +## よくあるバリエーションとエッジケース + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** objects | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **You need plain Unicode math, not LaTeX** | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **You want to keep the original file name** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +| 状況 | 対応策 | +|-----------|------------| +| **Legacy Equation Editor** オブジェクト | 手順 3 の前に `doc.ConvertMathToOfficeMath()` を呼び出す。 | +| **LaTeX ではなくプレーンな Unicode 数式が必要** | `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode` を設定する。 | +| **大容量ドキュメント(100 MB 超)** | メモリ使用量を抑えるために `doc.Save(Stream, txtOptions)` でストリーム保存する。 | +| **元のファイル名を保持したい** | 出力パス作成時に `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` を使用する。 | + +These tweaks answer the “**how to export math**” question for different pipelines, ensuring your solution is robust no matter the source. + +これらの調整により、さまざまなパイプラインでの “**how to export math**” の課題に対応でき、ソースに関係なく堅牢なソリューションが実現します。 + +--- + +## Full Working Example (All steps in one place) + +## 完全動作サンプル(すべての手順を一括で) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Run the program, open the generated `.txt`, and you’ll see the LaTeX equations embedded right where they belonged. This is the most straightforward way to **convert + +プログラムを実行し、生成された `.txt` を開くと、数式が正しい位置に LaTeX スニペットとして埋め込まれているのが確認できます。これが **convert** する最もシンプルな方法です。 + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/japanese/net/working-with-fonts/_index.md b/words/japanese/net/working-with-fonts/_index.md index 3e703a30da..b583682ea4 100644 --- a/words/japanese/net/working-with-fonts/_index.md +++ b/words/japanese/net/working-with-fonts/_index.md @@ -48,6 +48,7 @@ | [警告通知を受け取る](./receive-warning-notification/) Aspose.Words for .NET の使用時に警告通知を受信し、ドキュメント内の問題や警告を管理する方法について説明します。 | | [リソース Steam フォントソースの例](./resource-steam-font-source-example/) リソース ストリーム フォント ソースを使用してカスタム フォントを Aspose.Words for .NET に読み込む方法を学習します。 | | [接尾辞なしの置換を取得する](./get-substitution-without-suffixes/) このチュートリアルでは、Aspose.Words for .NET を使用して Word 文書でサフィックスなしのオーバーライドを取得する方法を学習します。 | +| [Aspose フォント置換 – Word 文書で欠落フォントを検出する](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) Aspose.Words for .NET を使用して、Word 文書内の欠落フォントを検出する方法をステップバイステップで学びます。 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/japanese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/japanese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..4c6ff27278 --- /dev/null +++ b/words/japanese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-04-05 +description: Aspose フォント置換ガイド:Word 文書の読み込み時に欠落フォントを検出する方法。フォント設定の構成と欠落フォントの効率的な処理方法を学びましょう。 +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: ja +og_description: Aspose フォント置換ガイド:Word 文書の読み込み時に欠落フォントを検出する方法。フォント設定の構成と欠落フォントの効率的な処理方法を学びましょう。 +og_title: Aspose フォント置換 – Word 文書の欠損フォントを検出 +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose フォント置換 – Word 文書の欠損フォントを検出 +url: /ja/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose フォント置換 – Word 文書で欠落フォントを検出する + +あるマシンでは完璧に見える Word ファイルが、別のマシンでは奇妙なフォント変更が起きたことはありませんか? それが典型的な **aspose font substitution** の問題で、通常は対象システムにフォントが欠落していることを意味します。このチュートリアルでは、**Word 文書をロードする際に欠落フォントを検出**する方法、**フォント設定を構成**する方法、そして **欠落フォントを優雅に処理**する方法をステップバイステップで解説します。 + +完全に実行可能な C# のサンプルを通して、各行が何を意味するのかを説明し、期待されるコンソール出力も示します。最後まで読めば、ドキュメントがロードされた瞬間にフォント置換を検出でき、推測に頼る必要はなくなります。 + +## 学べること + +- Aspose.Words のフォント警告用診断コレクタを有効にする方法。 +- カスタム **font settings** を使用して **Word 文書をロード** するための正確なコード。 +- `WarningInfo` オブジェクトを列挙して、置換されたフォントをすべてリストアップする方法。 +- 不要な警告を抑制したり、フォールバックフォントを提供したりするコツ。 +- Visual Studio にコピペできる、すぐに実行可能なサンプル。 + +### 前提条件 + +- .NET 6.0 以降(API は .NET Framework でも同様に動作)。 +- Aspose.Words for .NET(NuGet パッケージ `Aspose.Words`)。 +- インストールされていないフォントを参照している Word ファイル(例:`MissingFont.docx`)。 + +上記が揃っていれば、さっそく始めましょう。 + +## Step 1 – 診断コレクタを有効にする(フォント設定の構成) + +まず最初に行うべきことは、Aspose.Words にフォント置換警告を記録させることです。これは `FontSettings` オブジェクトを作成し、`LoadOptions` インスタンスに割り当てることで実現します。フォント処理の「デバッグライト」をオンにするイメージです。 + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**なぜ必要か?** +`FontSettings` オブジェクトが無いと警告コレクタは黙ってしまい、どのフォントが置換されたか分かりません。空の設定で初期化することで、Aspose はデフォルトのシステムフォントを使用しつつ、置換情報を追跡します。 + +> **プロのコツ:** 企業フォントが格納された特定フォルダーがある場合は、`SetFontsFolder("path")` で `FontSettings` に指定しましょう。これにより欠落フォント警告の数を減らせます。 + +## Step 2 – 設定したオプションで文書をロードする(Word 文書のロード) + +コレクタが有効になったら、同じ `LoadOptions` を使って `.docx` ファイルをロードします。ここで Aspose は文書を走査し、すべてのフォント参照をチェックして置換が必要かどうかを判断します。 + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**なぜ重要か?** +単に `new Document("MissingFont.docx")` と呼び出すだけではデフォルト設定が適用され、警告リストは空のままです。`loadOptions` を渡すことで、診断コレクタがロードパイプラインにフックされます。 + +## Step 3 – フォント置換警告を取得して表示する(欠落フォントの検出) + +文書がメモリ上にロードされたら、Aspose は警告を `document.WarningCallback.Warnings` に格納します。そのコレクションを走査し、`WarningType.FontSubstitution` でフィルタリングして説明文を出力します。各説明文は「どのフォントが欠落し、代わりに何が使用されたか」を示します。 + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**期待されるコンソール出力** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +この出力は、コードを実行しているマシンで欠落しているフォントを正確に示します。これを元にフォントをインストールするか、文書に埋め込むか、置換のままにするかを判断できます。 + +![Console output showing aspose font substitution warnings](/images/aspose-font-substitution-console.png) + +*画像の代替テキスト:* aspose font substitution – 置換されたフォントを一覧表示したコンソール出力 + +## Step 4 – 任意:置換動作をカスタマイズする(欠落フォントの処理) + +単に置換が起きたことを知りたいだけでなく、**どのように**置換させるかを制御したい場合があります。Aspose.Words ではカスタム `IFontSubstitutionRule` を登録できます。以下は、欠落フォントがあればすべて `Tahoma` にフォールバックさせる簡単な例です。 + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**いつ使うべきか?** +Web サービスで PDF を生成し、クライアントがすべて `Tahoma` を表示できることが分かっている場合、フォールバックを強制することで多数のフォントファイルを配布せずに視覚的一貫性を保てます。 + +## 完全動作サンプル(全ステップ統合) + +新しいコンソールプロジェクトに貼り付けてそのままコンパイルできる、全体プログラムです。Aspose.Words の NuGet パッケージをインストールしていることが前提です。 + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +プログラムを実行し、コンソールを確認すれば、すべての欠落フォントイベントが出力されます。その後、フォントをインストールするか、埋め込むか、フォールバックのままにするかを決められます。 + +## Frequently Asked Questions + +**Q: PDF 変換でも同様に機能しますか?** +はい。後で `doc.Save("output.pdf")` を呼び出すと、ロード時に置換されたフォントが PDF に埋め込まれます。したがって、早期に警告を捕捉しておくことで、最終的な PDF で予期せぬフォント変更が起きるのを防げます。 + +**Q: 処理対象が多数の文書の場合はどうすれば良いですか?** +ロードロジックを try‑catch ブロックで囲み、`FontSettings` インスタンスを文書間で再利用してください。これによりオーバーヘッドが削減され、各ファイルで警告コレクタが有効なままになります。 + +**Q: 警告を完全に抑制することは可能ですか?** +`loadOptions.WarningCallback = null;` と設定すればロード時の警告は出ませんが、**欠落フォントの検出**ができなくなるため、通常は推奨されません。 + +## Conclusion + +**aspose font substitution** をマスターするために必要なすべてを網羅しました:診断コレクタの有効化、カスタム **font settings** での Word ファイルのロード、欠落フォント一覧の抽出、そしてデフォルト置換ルールを上書きして **欠落フォントを自分流に処理**する方法です。数行の C# で、レイアウトの微妙な変化の背後に潜むフォント問題を完全に可視化できます。 + +次のステップは? `FontSettings.SetFontsFolder` で元フォントを文書に埋め込んでみるか、`FontSourceBase` を使ってデータベースからフォントをロードする方法を探ってみてください。また、`Document.BuiltInStyle` コレクションを調べて、スタイルレベルでのフォント変更がどのように伝播するかを実験してみるのも面白いでしょう。 + +Aspose.Words やフォント管理についてさらに質問がありますか? コメントを残すか、公式 Aspose ドキュメントを参照するか、新しいプロジェクトを立ち上げて上記コードを試してみてください。コーディングを楽しみながら、文書が常に意図した通りに表示されることを願っています! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/basic-conversions/_index.md b/words/korean/net/basic-conversions/_index.md index 938bccaaa3..47d7377887 100644 --- a/words/korean/net/basic-conversions/_index.md +++ b/words/korean/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ | [Word에서 LaTeX 내보내기 – 단계별 가이드](./how-to-export-latex-from-word-step-by-step-guide/) | Aspose.Words for .NET을 사용하여 Word 문서에서 LaTeX 코드를 추출하고 내보내는 방법을 단계별로 안내합니다. | | [C#에서 Aspose.Words를 사용해 Word를 PDF로 변환 – 가이드](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aspose.Words for .NET을 사용하여 C#에서 Word 문서를 PDF로 변환하는 방법을 단계별로 안내합니다. | | [Aspose.Words로 Word를 PDF로 저장 – 완전한 C# 가이드](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words와 C#을 활용해 Word 문서를 PDF로 변환하는 전체 단계별 가이드입니다. | +| [C#에서 Aspose.Words를 사용해 Word를 PDF로 변환 – 전체 가이드](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Aspose.Words for .NET을 활용해 C#에서 Word 문서를 PDF로 변환하는 전체 가이드를 제공합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/korean/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..4357a9e0e2 --- /dev/null +++ b/words/korean/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words를 사용하여 C#에서 Word를 PDF로 변환합니다. docx를 PDF로 저장하고, 접근성 있는 PDF를 + 내보내며, Word 문서를 효율적으로 로드하는 방법을 배워보세요. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: ko +og_description: C#에서 Word를 PDF로 변환하는 단계별 가이드. docx를 PDF로 저장하고, 접근성 PDF를 내보내며, Aspose.Words를 + 사용해 Word 문서를 로드하는 방법을 알아보세요. +og_title: C#에서 Word를 PDF로 변환 – 완전한 Aspose.Words 튜토리얼 +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: C#에서 Word를 PDF로 변환 – Aspose.Words를 활용한 완전 가이드 +url: /ko/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 Word를 PDF로 변환 – 완전 프로그래밍 튜토리얼 + +복잡한 커맨드‑라인 도구나 서드‑파티 서비스를 사용하지 않고 **convert word to pdf** 하는 방법이 궁금하셨나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 클라이언트가 DOCX 파일에서 바로 접근 가능한 PDF를 요구할 때 이 문제에 부딪힙니다. 좋은 소식은? 몇 줄의 C# 코드와 강력한 Aspose.Words 라이브러리만 있으면 Word 문서를 표준‑준수 PDF로 순식간에 변환할 수 있다는 것입니다. + +이 가이드에서는 **load word document** 기본부터 **how to export accessible pdf** 를 위한 옵션 설정, 그리고 **save docx as pdf** 를 신뢰성 있게 저장하는 방법까지 모든 과정을 단계별로 살펴봅니다. 끝까지 읽으면 .NET 프로젝트 어디에든 바로 넣어 사용할 수 있는 실행 가능한 코드 스니펫을 얻게 됩니다. + +> **Pro tip:** PDF/UA‑2(많은 정부 기관이 요구하는 접근성 표준) 준수를 목표로 한다면, 같은 코드에 `PdfCompliance` 플래그만 올바르게 설정하면 추가 작업 없이 바로 사용할 수 있습니다. + +--- + +## What You’ll Learn + +- C#에서 Aspose.Words를 사용해 **load word document** 하는 방법 +- **how to export accessible pdf**(PDF/UA‑2)를 위해 필요한 정확한 설정 +- 한 메서드 호출만으로 **save docx as pdf** 를 수행하는 완전 실행 예제 +- **c# convert docx pdf** 시 흔히 마주치는 함정과 회피 방법 +- 생성된 PDF가 접근성 요구사항을 충족하는지 빠르게 확인하는 방법 + +외부 도구 없이, 복잡한 설정 파일 없이—오늘 바로 컴파일할 수 있는 순수 C# 코드만 제공합니다. + +--- + +## Prerequisites + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +1. **.NET 6.0**(또는 최신 .NET 버전) 설치 완료. 이전 프레임워크도 동작하지만 아래 구문은 최신 SDK를 기준으로 합니다. +2. Aspose.Words for .NET용 **license**. 라이브러리는 무료 체험판을 제공하지만, 실제 서비스에서는 유효한 키가 필요합니다. +3. 프로젝트에 **Aspose.Words** NuGet 패키지 추가: + +```bash +dotnet add package Aspose.Words +``` + +이것만 있으면 됩니다—추가 바이너리나 COM 인터옵 없이 깔끔한 NuGet 참조만 있으면 됩니다. + +--- + +![Aspose.Words를 사용한 C#에서 Word를 PDF로 변환](image-placeholder.png "Aspose.Words를 사용한 C#에서 Word를 PDF로 변환") + +--- + +## Step‑by‑Step Implementation + +아래에서는 전체 과정을 논리적인 단계로 나눕니다. 각 단계마다 작은 코드 스니펫, **왜** 중요한지에 대한 설명, 그리고 실제 현장에서 얻은 팁을 제공합니다. + +### ## Convert Word to PDF – Load the Source Document + +첫 번째로 해야 할 일은 **load word document** 를 메모리로 읽어들이는 것입니다. Aspose.Words는 OpenXML 파싱을 추상화해 주므로 DOCX, DOC, 심지어 RTF 파일도 형식상의 복잡함을 신경 쓰지 않고 작업할 수 있습니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +파일을 로드하면 전체 Word 파일을 나타내는 `Document` 객체가 생성됩니다. 여기에는 헤더, 푸터, 스타일, 숨겨진 메타데이터까지 모두 포함됩니다. 이 단계를 건너뛰거나 파일을 원시 스트림으로 읽어들이면 나중에 PDF 레이아웃을 결정하는 중요한 레이아웃 정보가 손실됩니다. + +> **Side note:** 동일한 `Document` 생성자는 `.doc`와 `.rtf`에도 동작합니다. 즉, 소스가 반드시 DOCX가 아니더라도 **c# convert docx pdf** 를 수행할 수 있습니다. + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +문서가 메모리에 로드되었으니 이제 Aspose.Words에 PDF 생성 방식을 알려줍니다. 대부분의 경우 기본 설정으로 충분하지만, **accessible PDF** 가 필요할 때는 PDF/UA‑2 준수 플래그를 활성화해야 합니다. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +`PdfCompliance.PdfUAXmpA2`는 화면 판독기가 필요로 하는 태그와 구조를 문서에 삽입하도록 라이브러리에 지시합니다. 이 플래그가 없으면 겉보기에는 완벽한 PDF가 생성되지만 접근성 감사에서 실패할 수 있습니다. + +> **Tip:** 일반 PDF만 필요하다면 `Compliance` 라인을 삭제해도 됩니다. 나머지 옵션만으로도 고품질 출력이 가능합니다. + +### ## Convert Word to PDF – Write the File + +옵션을 모두 설정했으면 마지막 단계인 **save docx as pdf** 를 수행합니다. 이 한 줄 호출이 레이아웃 변환, 글꼴 포함, 접근성 태깅 등 모든 무거운 작업을 처리합니다. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- `outputPath`에 저장된 PDF 파일은 Word 레이아웃을 그대로 재현합니다. +- `PdfUAXmpA2` 플래그를 사용했다면 PDF는 PDF/UA‑2 준수로 표시됩니다. +- 모든 글꼴이 포함되어 있어 어떤 **machine**에서도 동일하게 표시됩니다. + +### ## Verify the Accessible PDF (Optional but Recommended) + +변환이 끝난 뒤에는 PDF가 **how to export accessible pdf** 를 제대로 수행했는지 재차 확인하는 것이 좋습니다. Adobe Acrobat Reader의 “Accessibility Check”나 오픈소스 `pdfcpu` 검증 도구를 활용할 수 있습니다. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +검증 도구가 오류를 보고하지 않으면, **convert word to pdf** 를 완전한 접근성 지원과 함께 성공적으로 수행한 것입니다. + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| Missing fonts | 소스 DOCX가 서버에 설치되지 않은 사용자 정의 글꼴을 사용함 | `EmbedFullFonts = true` 로 설정하거나 해당 글꼴을 머신에 설치 | +| Large file size | 이미지가 원본 해상도로 그대로 삽입됨 | `ImageCompression = PdfImageCompression.Jpeg` 로 설정하고 `JpegQuality` 를 낮은 값으로 지정 | +| Broken hyperlinks | 링크가 클라이언트에 존재하지 않는 상대 경로를 가리킴 | URL을 절대 경로로 바꾸거나 `HyperlinkTarget` 속성을 조정 | +| Accessibility tags missing | `Compliance` 플래그가 설정되지 않음 | 위 예시와 같이 `Compliance = PdfCompliance.PdfUAXmpA2` 를 추가 | + +이러한 점들을 유념하면 **c# convert docx pdf** 작업을 견고하고 프로덕션 수준으로 만들 수 있습니다. + +--- + +## Full Working Example + +전체 과정을 하나로 합친, 지금 바로 컴파일하고 실행할 수 있는 콘솔 앱 예제입니다. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** 프로그램을 실행하면 `C:\Docs` 폴더에 `output.pdf` 가 생성됩니다. PDF 뷰어에서 열어보면 레이아웃이 `input.docx` 와 픽셀 단위까지 일치하고, 접근성 검사를 통해 PDF/UA‑2 준수가 확인됩니다. + +--- + +## Conclusion + +우리는 C#과 Aspose.Words를 사용해 **convert word to pdf** 하는 완전한 엔드‑투‑엔드 솔루션을 살펴보았습니다. **load word document** 로 문서를 읽고, 적절한 `PdfSaveOptions` 를 설정한 뒤, 마지막으로 **save docx as pdf** 를 호출하면 최소한의 코드로 고품질·접근성 PDF를 얻을 수 있습니다. 문서‑생성 마이크로서비스를 구축하든, 온‑프레미스 배치 변환기를 만들든, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-markdownsaveoptions/_index.md b/words/korean/net/programming-with-markdownsaveoptions/_index.md index 7958496a56..a2308dd4e2 100644 --- a/words/korean/net/programming-with-markdownsaveoptions/_index.md +++ b/words/korean/net/programming-with-markdownsaveoptions/_index.md @@ -22,7 +22,7 @@ | 제목 | 설명 | | --- | --- | | [표 내용 정렬을 사용하여 마크다운으로 내보내기](./export-into-markdown-with-table-content-alignment/) | Aspose.Words for .NET을 사용하여 정렬된 표가 있는 Word 문서를 Markdown으로 내보내는 방법을 알아보세요. 완벽한 Markdown 표를 만드는 단계별 가이드를 따라해 보세요. | -| [이미지 폴더 설정](./set-images-folder/) Aspose.Words for .NET을 사용하여 Word 문서를 적절한 표 정렬을 통해 Markdown으로 변환하세요. 완벽한 결과를 얻으려면 자세한 가이드를 따르세요. | +| [이미지 폴더 설정](./set-images-folder/) | Aspose.Words for .NET을 사용하여 Word 문서를 적절한 표 정렬을 통해 Markdown으로 변환하세요. 완벽한 결과를 얻으려면 자세한 가이드를 따르세요. | | [Word를 PDF로 저장하고 손상된 Word 복구 – C#에서 Word를 Markdown으로 변환](./save-word-as-pdf-and-recover-corrupted-word-convert-word-to/) | | | [접근성 PDF 만들기 및 Word를 Markdown으로 변환 – 전체 C# 가이드](./create-accessible-pdf-and-convert-word-to-markdown-full-c-gu/) | Aspose.Words for .NET을 사용하여 접근성 PDF를 생성하고 Word를 Markdown으로 변환하는 전체 C# 가이드 | | [Markdown 사용 방법: LaTeX 수식이 포함된 DOCX를 Markdown으로 변환](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) | Aspose.Words for .NET을 사용하여 LaTeX 수식이 포함된 DOCX 파일을 정확히 Markdown으로 변환하는 단계별 가이드 | @@ -32,6 +32,8 @@ | [Word에서 Markdown 내보내기 – 전체 C# 가이드](./how-to-export-markdown-from-word-complete-c-guide/) | Aspose.Words for .NET을 사용하여 Word 문서를 Markdown으로 내보내는 전체 C# 가이드 | | [DOCX에서 Markdown 저장 방법 – 단계별 가이드](./how-to-save-markdown-from-docx-step-by-step-guide/) | Aspose.Words for .NET을 사용하여 DOCX 파일을 Markdown으로 저장하는 단계별 가이드를 제공합니다. | | [DOCX에서 Markdown 내보내기 – 전체 C# 가이드](./how-to-export-markdown-from-docx-complete-guide/) | Aspose.Words for .NET을 사용하여 DOCX 파일을 Markdown으로 내보내는 전체 C# 가이드 | +| [docx를 markdown으로 변환 – 이미지 추출 포함 전체 C# 가이드](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Aspose.Words for .NET을 사용하여 DOCX 파일을 Markdown으로 변환하면서 이미지 추출하는 방법을 단계별로 안내합니다. | +| [Word를 Markdown으로 변환 – PDF/UA 내보내기 전체 가이드](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Aspose.Words for .NET을 사용하여 Word 문서를 Markdown으로 변환하고 PDF/UA 형식으로 내보내는 전체 단계별 가이드 | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/korean/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..564f4e79b3 --- /dev/null +++ b/words/korean/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: C#에서 DOCX를 Markdown으로 변환하고 DOCX에서 이미지를 추출하는 방법을 배워보세요. 전체 코드와 팁이 포함된 + 단계별 가이드. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: ko +og_description: Aspose.Words를 사용하여 DOCX를 Markdown으로 변환하고 DOCX에서 이미지를 추출합니다. 코드, 설명 + 및 모범 사례 팁이 포함된 완전한 C# 튜토리얼. +og_title: DOCX를 Markdown으로 변환 – C#에서 DOCX 이미지 추출 +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX를 Markdown으로 변환 – Aspose.Words로 DOCX에서 이미지 추출 +url: /ko/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX를 Markdown으로 변환 – C#에서 DOCX에서 이미지 추출 + +DOCX를 **Markdown으로 변환**하고 싶었지만 출력에서 이미지가 사라지는 문제를 겪어본 적 있나요? 당신만 그런 것이 아닙니다. 많은 프로젝트에서 Markdown 버전은 버전 관리나 정적 사이트 생성기에 최적이지만, 그림이 남지 않아 풍부한 문서가 텍스트만 남은 빈 파일이 됩니다. + +좋은 소식은? 몇 줄의 C# 코드와 Aspose.Words만 있으면 **DOCX를 Markdown으로 변환** *하고* **DOCX에서 이미지를 자동으로 추출**할 수 있습니다. 이 가이드는 전체 과정을 단계별로 안내하고, 각 요소가 왜 중요한지 설명하며, 이미지 폴더를 깔끔하게 유지하는 방법까지 보여줍니다. + +## 배울 내용 + +- 그림이 포함된 DOCX를 로드하는 방법 +- 각 이미지가 저장될 위치를 결정하는 커스텀 `IResourceSavingCallback` 정의 방법 +- 추출된 이미지를 올바르게 참조하도록 `MarkdownSaveOptions`를 설정하는 방법 +- 중복 이미지 이름이나 PNG가 아닌 포맷과 같은 엣지 케이스 처리 팁 +- 오늘 바로 실행할 수 있는 완전한 복사‑붙여넣기 가능한 코드 샘플 + +### 전제 조건 + +- .NET 6.0 이상 (.NET Core, .NET Framework, .NET 5+에서도 동작) +- **Aspose.Words for .NET** 라이선스 (무료 체험판으로 테스트 가능) +- C#와 Visual Studio(또는 선호하는 IDE)에 대한 기본 지식 + +위 조건을 갖췄다면, 바로 시작해봅시다. + +--- + +## 1단계: 프로젝트 설정 및 Aspose.Words 설치 + +먼저 새 콘솔 앱을 만들거나 기존 솔루션에 통합합니다. + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tip:** 최신 NuGet 버전(2026년 4월 현재 24.12)을 사용하면 최신 Markdown 내보내기 개선 사항을 받을 수 있습니다. + +--- + +## 2단계: 원하는 위치에 이미지를 저장하는 콜백 만들기 + +Aspose.Words는 Markdown 내보내기 중에 기록되는 모든 리소스(이미지, SVG 등)를 가로챌 수 있습니다. `IResourceSavingCallback`을 구현하면 다음을 할 수 있습니다. + +1. Markdown 파일 옆에 위치할 폴더 선택 +2. 기존 이미지를 덮어쓰지 않도록 고유 파일명 생성 +3. 형식 지정(여기서는 일관성을 위해 PNG 강제) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### 왜 GUID 기반 이름인가? + +원본 DOCX에 동일한 원본 이름을 가진 두 그림이 있을 경우, 단순 복사‑붙여넣기로는 하나가 덮어써집니다. `Guid.NewGuid()`를 사용하면 고유성이 보장되어 자동화 파이프라인에서 여러 번 변환할 때 특히 유용합니다. + +--- + +## 3단계: DOCX 로드 및 Markdown 옵션 연결 + +이제 문서를 메모리로 불러오고 방금 만든 콜백을 연결합니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### 코드가 수행하는 작업, 단계별 설명 + +| 단계 | 목적 | +|------|------| +| **Define paths** | 프로젝트를 유연하게 유지합니다. 재컴파일 없이도 원하는 폴더를 지정할 수 있습니다. | +| **Load the DOCX** | `Document`가 Word 파일을 파싱해 모든 요소(단락, 표, 그림)를 접근 가능하게 합니다. | +| **Configure `MarkdownSaveOptions`** | `ResourceSavingCallback`은 이미지를 추출하는 훅입니다. 이 콜백이 없으면 Aspose.Words는 이미지를 base64 문자열로 삽입하거나 전혀 저장하지 않을 수 있습니다. | +| **Save** | `doc.Save`가 Markdown 파일을 쓰고 각 이미지마다 콜백을 호출합니다. | + +--- + +## 4단계: 출력 확인 – 어떤 결과가 보여야 할까? + +프로그램을 실행한 뒤 `DocWithImages.md`를 열어보세요. 다음과 같은 Markdown 이미지 링크가 보일 것입니다. + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +그리고 `C:\Docs\MarkdownResources` 폴더 안에 GUID 이름을 가진 PNG 파일들이 생성됩니다. 파일을 하나 열어보면 원본 DOCX에 포함된 그림과 동일함을 확인할 수 있습니다. + +Markdown 파일을 상대 경로를 지원하는 뷰어(VS Code 프리뷰, GitHub, 정적 사이트 생성기 등)에서 열면 이미지가 Word에서 보였던 그대로 렌더링됩니다. + +### 흔히 발생하는 문제와 해결 방법 + +| 증상 | 가능 원인 | 해결 방법 | +|------|----------|----------| +| 이미지가 깨진 링크로 표시 | `ResourceFileName`이 설정되지 않아 Markdown이 존재하지 않는 파일을 가리킴 | 콜백 안에서 `args.ResourceFileName = newFileName;`을 설정하세요. | +| PNG 파일이 너무 큼 | 원본 이미지가 JPEG이나 BMP였으며 PNG로 변환하면서 용량이 증가 | `args.ResourceContentType`을 통해 원본 포맷을 감지하고 그대로 유지: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| 중복 이미지가 여전히 존재 | 정적 파일명을 사용했기 때문 | GUID 로직으로 되돌리거나 이미지 타입별 카운터를 추가하세요. | +| 변환 중 `FileNotFoundException` 발생 | DOCX 경로가 잘못됐거나 폴더에 읽기 권한이 없음 | 경로를 확인하고 파일 시스템 권한을 부여하세요. | + +--- + +## 5단계: 고급 조정 (선택 사항) + +### 5.1 원본 이미지 포맷 유지 + +출력 이미지가 원본 확장자를 유지하도록 하려면 콜백을 다음과 같이 수정합니다. + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 이미지를 Base64로 삽입 (별도 파일을 원하지 않을 때) + +단일 파일 Markdown이 필요할 때(예: 이메일 전송) 옵션을 변경합니다. + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +하지만 대부분 정적 사이트 워크플로우에서는 **DOCX에서 이미지 추출**이 주요 목표이므로 폴더 방식을 사용하는 것이 일반적으로 더 좋습니다. + +--- + +## 전체 작업 예제 (복사‑붙여넣기 준비) + +아래는 하나의 파일에 담긴 전체 프로그램입니다. 경로만 본인 환경에 맞게 바꾸고 실행하면 됩니다. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +`dotnet run`으로 실행하세요. 콘솔에 ✅ 라인이 출력되면 Markdown 파일을 열어 이미지가 정상적으로 렌더링되는지 확인합니다. + +--- + +## 결론 + +이제 **Aspose.Words를 사용해 C#에서 DOCX를 Markdown으로 변환하고 이미지를 추출**하는 **완전하고 프로덕션 수준의 솔루션**을 갖추었습니다. 주요 키워드가 가이드 전반에 걸쳐 등장해 검색 엔진과 AI 어시스턴트 모두에게 높은 관련성을 제공합니다. + +한 번에 수행되는 작업은 다음과 같습니다. + +1. Word 문서를 로드합니다. +2. `IResourceSavingCallback`을 통해 모든 이미지를 가로챕니다. +3. 고유한 이름으로 예측 가능한 폴더에 각 이미지를 저장합니다. +4. 해당 이미지를 참조하는 Markdown을 생성합니다. + +이제 다음을 할 수 있습니다. + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/korean/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..96738deb36 --- /dev/null +++ b/words/korean/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Word를 빠르게 Markdown으로 변환하고 C#에서 PDF/UA로 저장하는 방법을 배워보세요. 단계별 코드, 팁 및 예외 + 상황 처리. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: ko +og_description: Aspose.Words를 사용해 Word를 Markdown으로 변환하고 PDF/UA로 저장하세요. 이유와 방법, 모범 + 사례 팁을 한 권의 간결한 가이드에서 배워보세요. +og_title: Word를 Markdown으로 변환 – 완전한 C# 튜토리얼 +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word를 Markdown으로 변환 – PDF/UA 내보내기 포함 전체 가이드 +url: /ko/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word를 Markdown으로 변환 – PDF/UA 내보내기 전체 가이드 + +Word를 **Markdown으로 변환**하면서 수식이나 이미지를 잃어버린 적이 있나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 `.docx` 파일을 깔끔한 Markdown으로 바꾸면서도 접근성‑준수 PDF를 위해 **PDF/UA로 저장**할 수 있는 신뢰할 만한 방법을 필요로 합니다. 이 튜토리얼에서는 Aspose.Words for .NET을 사용한 완전한 실행 가능한 솔루션을 단계별로 살펴보고, 각 설정이 왜 중요한지 설명하며, OfficeMath와 떠다니는 도형 같은 까다로운 부분을 처리하는 방법을 보여드립니다. + +이 가이드를 끝까지 따라오면 다음을 수행하는 단일 C# 프로그램을 얻게 됩니다: + +1. 복구 모드를 완화(Relaxed)하여 Word 문서를 로드합니다(손상된 파일이 실행을 중단하지 않도록). +2. 수식을 LaTeX로 변환하고 이미지를 사용자 정의 콜백을 통해 저장하면서 Markdown으로 내보냅니다. +3. 동일한 문서를 PDF/UA‑2 준수 파일로 저장하고, 떠다니는 도형을 인라인 태그로 삽입합니다. + +많은 작업처럼 들리나요? 걱정 마세요—바로 시작합니다. + +## 준비물 + +- **Aspose.Words for .NET** (작성 시점 최신 버전, 23.x). +- .NET 개발 환경(Visual Studio 2022, Rider, 또는 `dotnet` CLI). +- 참조할 수 있는 폴더에 배치한 샘플 Word 파일(`input.docx`). +- C# 문법에 대한 기본적인 이해—특별한 지식은 필요 없으며 `using` 문 몇 개만 알면 됩니다. + +> **Pro tip:** NuGet 패키지 관리자를 사용한다면 다음 명령으로 라이브러리를 추가하세요. +> `dotnet add package Aspose.Words` 또는 Visual Studio NuGet UI를 통해 추가합니다. + +## Step 1 – Relaxed Recovery로 Word 문서 로드 + +외부 소스로부터 받은 Word 파일은 사소한 손상이 있을 수 있습니다. **Relaxed** 복구 모드를 활성화하면 Aspose.Words가 예외를 발생시키지 않고 계속 진행합니다. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**왜 중요한가:** +- `RecoveryMode.Relaxed`는 하나의 잘못된 단락이 전체 변환을 중단하는 일을 방지합니다. +- `FontSettings` 객체를 제공하면 누락된 글꼴이 부드럽게 대체되어, 이후 수식을 LaTeX로 렌더링할 때 필수적입니다. + +## Step 2 – Markdown으로 내보내기 (OfficeMath → LaTeX, 이미지 콜백 사용) + +Markdown은 Word 수식을 직접 표현할 방법이 없습니다. Aspose.Words는 **OfficeMath** 객체를 LaTeX로 변환할 수 있으며, 대부분의 Markdown 렌더러가 이를 이해합니다. 이미지는 별도로 저장해야 하는데, 사용자 정의 **resource‑saving 콜백**을 사용하면 폴더 구조와 파일 이름을 완전히 제어할 수 있습니다. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Resource‑Saving 콜백 + +아래는 모든 이미지를 `images`라는 하위 폴더에 저장하고 파일 이름을 `img001.png`, `img002.png` 등으로 지정하는 간단한 구현 예시입니다. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**왜 필요한가:** +- 콜백을 사용하지 않으면 Aspose.Words가 무작위 GUID 이름을 가진 평면 폴더를 생성해 버전 관리가 복잡해집니다. +- 파일 명명 방식을 직접 제어하면 Markdown 저장소를 깔끔하고 재현 가능하게 유지할 수 있습니다. + +### 예상되는 Markdown 출력 + +실행 후 `doc.md`를 열면 다음과 같은 내용이 보입니다: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +수식은 `$$ … $$` 로 감싼 LaTeX 형태로 나타나며, 이미지는 방금 만든 `images` 폴더를 참조합니다. + +## Step 3 – PDF/UA‑2로 내보내기 (접근성 준비) + +스크린 리더 등 보조 기술에 의존하는 사용자와 문서를 공유해야 한다면 **PDF/UA‑2** 준수가 최선의 선택입니다. Aspose.Words는 단일 플래그로 이를 강제할 수 있으며, 떠다니는 도형을 인라인 태그로 평탄화하여 변환 과정에서 손실되지 않게 할 수 있습니다. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**왜 PDF/UA가 중요한가:** +- PDF/UA(Universal Accessibility)는 결과 PDF에 올바른 태깅, 논리적인 읽기 순서, 이미지에 대한 대체 텍스트가 포함되도록 보장합니다. +- `ExportFloatingShapesAsInlineTag` 설정은 텍스트 상자나 호출 상자와 같은 도형이 누락되거나 잘못 배치되는 일반적인 함정을 방지합니다. + +### PDF/UA 준수 확인 방법 + +내보내기 후 Adobe Acrobat Pro에서 PDF를 열고 **“Accessibility Check”**(Tools → Accessibility → Full Check)를 실행합니다. 도구가 **0 errors**를 보고하면 성공적인 것입니다. + +## Edge Cases & Common Pitfalls + +| Situation | What to Watch For | Fix / Recommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word file contains **unsupported fonts** | Fonts may be substituted, breaking equation layout | Supply a custom `FontSettings` with fallback fonts. | +| Large documents (> 100 MB) | Memory pressure during conversion | Use `LoadOptions` with `LoadFormat.Docx` and stream the file. | +| Images are **EMF/WMF** vector graphics | They may be rasterized unintentionally | Convert them to PNG via `ImageSaveOptions` before saving. | +| PDF/UA fails validation on **nested tables** | Tagging can become ambiguous | Enable `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` to help the engine. | +| Need to **preserve custom styles** | Markdown has limited styling capabilities | Export a CSS file alongside the Markdown and reference it. | + +## Full Working Example (All Code Together) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +프로그램을 실행하면 `YOUR_DIRECTORY`에 `doc.md`(LaTeX 수식과 깔끔한 이미지 링크 포함)와 `doc.pdf`(완전 PDF/UA‑2 준수)가 모두 생성됩니다. + +## Visual Overview + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Alt text:* **convert word to markdown example** – Word 파일에서 Markdown 및 PDF/UA 파일로 변환되는 파이프라인을 보여주는 다이어그램. + +## Recap & Next Steps + +우리는 **Word를 Markdown으로 변환**하면서 수식을 그대로 유지하고, 이미지를 정돈된 폴더에 저장했으며, 접근성 검사를 통과하는 **PDF/UA 저장** 파일을 만들었습니다. 주요 포인트는 다음과 같습니다: + +- `LoadOptions.RecoveryMode.Relaxed`를 사용해 불완전한 Word 파일을 견딜 수 있게 합니다. +- `OfficeMathExportMode`를 `LaTeX`로 설정해 깔끔한 수식 렌더링을 제공합니다. +- `ResourceSavingCallback`을 구현해 이미지 출력 위치와 이름을 제어합니다. +- `PdfCompliance.PdfUAXmpA2`와 `ExportFloatingShapesAsInlineTag`를 활성화해 표준 준수 PDF를 생성합니다. + +### What to Explore Next? + +- **Custom CSS for Markdown** – Word 스타일을 반영하는 스타일시트를 생성합니다. +- **Batch processing** – `.docx` 파일이 들어있는 디렉터리를 순회해 대량 마이그레이션을 자동화합니다. +- **Advanced PDF/UA features** – 사용자 정의 태그 추가, 언어 속성 설정, 오디오 설명 삽입 등을 수행합니다. +- **Integration with CI/CD** – 모든 빌드에서 자동으로 접근성 PDF를 생성하도록 설정합니다. + +문제가 발생하면 Aspose.Words 버전이 여기서 사용한 API와 일치하는지 다시 확인하고, 라이브러리 자체 문서가 훌륭한 보조 참고 자료임을 기억하세요. + +행복한 코딩 되시고, 문서가 **아름다움과** 접근성을 모두 갖추길 바랍니다! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/programming-with-txtsaveoptions/_index.md b/words/korean/net/programming-with-txtsaveoptions/_index.md index 3d38efe5e7..aa436e856d 100644 --- a/words/korean/net/programming-with-txtsaveoptions/_index.md +++ b/words/korean/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Aspose.Words for .NET 튜토리얼은 Word 문서 조작과 관련하여 라이 | [Word 문서에 비디 마크 추가](./add-bidi-marks/) | 이 가이드를 통해 Aspose.Words for .NET을 사용하여 Word 문서에 양방향(Bidi) 표시를 추가하는 방법을 알아보세요. 다국어 콘텐츠의 텍스트 방향을 올바르게 설정하세요. | | [목록 들여쓰기를 위해 레벨당 탭 문자 사용](./use-tab-character-per-level-for-list-indentation/) | Aspose.Words for .NET을 사용하여 탭 들여쓰기가 적용된 다단계 목록을 만드는 방법을 알아보세요. 문서에서 정확한 목록 서식을 지정하려면 이 가이드를 따르세요. | | [목록 들여쓰기에 레벨당 공백 문자 사용](./use-space-character-per-level-for-list-indentation/) | Aspose.Words for .NET에서 공백 문자 들여쓰기를 적용한 다단계 목록을 만드는 방법을 알아보세요. 정확한 문서 서식 지정을 위한 단계별 가이드입니다. | - +| [docx를 txt로 저장 – C#로 Word 방정식을 LaTeX로 내보내기](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | C#를 사용하여 Word 문서의 방정식을 LaTeX 형식으로 변환하고 txt 파일로 저장하는 방법을 배웁니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/korean/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..904832d09d --- /dev/null +++ b/words/korean/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,212 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words로 docx를 txt로 저장 – Word를 빠르게 txt로 변환하고 수학 방정식을 LaTeX로 내보내는 + 방법을 배워보세요. 간단한 C# 코드, 추가 도구 없이 가능합니다. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: ko +og_description: C#에서 docx를 txt로 저장하고 수식을 LaTeX로 내보내는 방법을 확인하세요. 방정식을 그대로 유지하면서 Word를 + txt로 변환하는 단계별 가이드를 따라보세요. +og_title: docx를 txt로 저장 – Word 수식을 LaTeX로 내보내기 +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx를 txt로 저장 – C#로 Word 수식을 LaTeX로 내보내기 +url: /ko/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx를 txt로 저장 – C#으로 Word 수식을 LaTeX로 내보내기 + +Word 문서를 **txt로 저장**하려고 할 때 수식이 사라지거나 읽을 수 없는 문자로 변환될까 걱정한 적 있나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 **Word를 txt로 변환**하려고 할 때, 특히 원본 파일에 Office Math 객체가 포함되어 있을 경우 이 문제에 부딪힙니다. + +좋은 소식은? 몇 줄의 C# 코드와 올바른 옵션만 설정하면 **Word를 txt로 변환**할 뿐만 아니라 모든 수식을 깔끔한 LaTeX 마크업으로 유지할 수 있습니다. 이번 튜토리얼에서는 전체 과정을 단계별로 살펴보고, 각 설정이 왜 중요한지 설명하며, 결과를 검증하는 방법을 보여드립니다. + +다룰 내용: + +* Aspose.Words for .NET 라이브러리 설치 +* 수식이 포함된 `.docx` 로드 +* **수식을 내보내는 방법**을 LaTeX‑친화적인 문자열로 만들기 위해 `TxtSaveOptions` 구성 +* 파일 저장 및 출력 확인 + +끝까지 따라오면 **docx를 txt로 저장**하면서 모든 수식을 LaTeX 형태로 보존하는 재사용 가능한 스니펫을 얻게 됩니다. 과학 파이프라인, 정적 사이트 생성기, 혹은 순수 텍스트 수식이 필요한 모든 워크플로에 완벽합니다. + +--- + +## Prerequisites + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +* .NET 6.0 이상 (코드는 .NET Framework 4.6+에서도 동작) +* Visual Studio 2022 (또는 선호하는 IDE) +* **Aspose.Words for .NET** NuGet 패키지 – 아래 명령으로 설치 + +```bash +dotnet add package Aspose.Words +``` + +추가 변환기나 외부 도구는 필요 없습니다. Aspose.Words가 내부적으로 모든 작업을 처리합니다. + +--- + +## Step 1: Install and reference Aspose.Words + +먼저 라이브러리를 프로젝트에 추가합니다. 명령줄을 사용한다면 위 명령을 실행하면 됩니다. Visual Studio에서는 **Dependencies → Manage NuGet Packages**를 마우스 오른쪽 버튼으로 클릭하고 *Aspose.Words*를 검색해 추가할 수도 있습니다. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** 최신 안정 버전(2026년 4월 현재 24.10)을 사용하세요. 최신 릴리스는 OfficeMath 처리와 관련된 버그가 수정되어 예상치 못한 기호 누락을 방지할 수 있습니다. + +--- + +## Step 2: Load the source document + +이제 수식이 들어 있는 `.docx` 파일을 불러옵니다. `Document` 클래스는 전체 Word 파일을 추상화하여 텍스트, 이미지, Office Math 객체에 접근할 수 있게 해줍니다. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +왜 먼저 로드해야 할까요? Aspose.Words가 파일을 객체 모델로 파싱해 주므로, 내보내기 방식을 결정하기 전에 내용 검토 및 수정이 가능합니다. 여기서 **수식을 내보내는 방법**에 대한 선택이 의미를 갖게 됩니다. + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +솔루션의 핵심은 `TxtSaveOptions` 클래스입니다. 기본적으로 TXT 저장 시 Office Math가 완전히 제거됩니다. `OfficeMathExportMode`를 `LaTeX`로 설정하면 라이브러리가 각 수식을 LaTeX 표현으로 변환합니다. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**왜 LaTeX인가요?** LaTeX는 과학 출판의 표준 언어입니다. 이렇게 수식을 내보내면 평면 이미지나 깨진 문자열이 아니라 수식의 의미를 그대로 보존할 수 있습니다. 이후에 Markdown 프로세서가 MathJax를 지원한다면, TXT 파일의 수식이 완벽히 렌더링됩니다. + +--- + +## Step 4: Save the document as plain‑text + +옵션을 설정했으니 이제 한 줄 코드로 파일을 디스크에 저장합니다. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +이것으로 끝! 이제 `.docx` 파일이 `.txt` 파일로 변환되었으며, 모든 수식이 LaTeX 스니펫 형태로 포함되어 downstream에서 바로 사용할 수 있습니다. + +--- + +## Verifying the output (How to save txt correctly) + +`MathSample.txt`를 텍스트 편집기로 열어보세요. 다음과 같은 내용이 보일 것입니다: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +만약 Word‑특유의 문자(예: `?` 혹은 누락된 기호)가 보인다면 다음을 확인하세요: + +* 최신 Aspose.Words 버전을 사용하고 있는지(구버전은 OfficeMath 버그가 존재). +* 원본 문서에 실제 **OfficeMath** 객체가 포함되어 있는지—구식 Equation Editor 객체라면 수동 변환이 필요하거나 저장 전에 `ConvertMathToOfficeMath` 메서드를 호출해야 합니다. + +--- + +## Common Variations & Edge Cases + +| Situation | What to do | +|-----------|------------| +| **Legacy Equation Editor** objects | `doc.ConvertMathToOfficeMath()`을 3단계 전에 호출합니다. | +| **LaTeX가 아니라 일반 Unicode 수식이 필요** | `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode` 로 설정합니다. | +| **대용량 문서(100 + MB)** | 메모리 사용량을 줄이기 위해 `doc.Save(Stream, txtOptions)` 로 스트리밍 저장합니다. | +| **원본 파일명을 유지하고 싶을 때** | 출력 경로를 만들 때 `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` 를 사용합니다. | + +이러한 조정은 다양한 파이프라인에서 **수식을 내보내는 방법**에 대한 답을 제공하며, 소스가 어떠하든 견고한 솔루션을 보장합니다. + +--- + +## Full Working Example (All steps in one place) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +프로그램을 실행하고 생성된 `.txt` 파일을 열어보면, LaTeX 수식이 원래 위치에 그대로 삽입된 것을 확인할 수 있습니다. 이것이 **convert** + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/korean/net/working-with-fonts/_index.md b/words/korean/net/working-with-fonts/_index.md index 6f0e573229..e97bae4204 100644 --- a/words/korean/net/working-with-fonts/_index.md +++ b/words/korean/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ | [경고 알림 수신](./receive-warning-notification/) Aspose.Words for .NET을 사용할 때 경고 알림을 받는 방법과 문서의 문제나 경고를 관리하는 방법을 알아보세요. | | [리소스 Steam 글꼴 소스 예시](./resource-steam-font-source-example/) | Aspose.Words for .NET에 사용자 정의 글꼴을 로드하기 위해 Resource Stream 글꼴 소스를 사용하는 방법을 알아보세요. | | [접미사 없이 대체 가져오기](./get-substitution-without-suffixes/) | 이 튜토리얼에서는 Aspose.Words for .NET을 사용하여 Word 문서에서 접미사 없는 재정의를 얻는 방법을 알아봅니다. | - +| [Aspose 글꼴 대체 – Word 문서에서 누락된 글꼴 감지](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Aspose.Words for .NET을 사용하여 Word 문서에서 누락된 글꼴을 감지하고 대체하는 방법을 단계별로 안내합니다. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/korean/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/korean/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..0f493a9c21 --- /dev/null +++ b/words/korean/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-04-05 +description: Aspose 글꼴 대체 가이드를 통해 Word 문서를 로드할 때 누락된 글꼴을 감지하고, 글꼴 설정을 구성하여 누락된 글꼴을 + 효율적으로 처리하는 방법을 배워보세요. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: ko +og_description: 'Aspose 글꼴 대체 가이드: Word 문서를 로드할 때 누락된 글꼴을 감지합니다. 글꼴 설정을 구성하고 누락된 글꼴을 + 효율적으로 처리하는 방법을 배워보세요.' +og_title: Aspose 글꼴 대체 – Word 문서에서 누락된 글꼴 감지 +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose 폰트 대체 – Word 문서에서 누락된 폰트 감지 +url: /ko/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Word 문서에서 누락된 글꼴 감지 + +한 컴퓨터에서는 완벽하게 보이던 Word 파일이 다른 컴퓨터에서는 이상한 글꼴 변경이 나타난 적이 있나요? 그것이 바로 클래식한 **aspose font substitution** 문제이며, 일반적으로 대상 시스템에 일부 글꼴이 없다는 의미입니다. 이 튜토리얼에서는 **Word 문서를 로드할 때 누락된 글꼴을 감지하는 방법**, **글꼴 설정을 구성하는 방법**, 그리고 **누락된 글꼴을 우아하게 처리하는 방법**을 단계별로 보여드립니다. + +전체 실행 가능한 C# 예제를 단계별로 살펴보고, 각 라인이 왜 중요한지 설명하며, 기대되는 콘솔 출력도 보여드립니다. 끝까지 읽으면 문서가 로드되는 순간 글꼴 대체를 즉시 파악할 수 있게 됩니다—추측이 필요 없습니다. + +## 배울 내용 + +- Aspose.Words의 글꼴 경고 진단 컬렉터를 활성화하는 방법. +- 맞춤 **font settings**를 사용하여 **Word 문서를 로드**하는 데 필요한 정확한 코드. +- `WarningInfo` 객체를 반복하여 모든 대체된 글꼴을 나열하는 방법. +- 원치 않는 경고를 억제하거나 대체 글꼴을 제공하기 위한 팁. +- Visual Studio에 복사‑붙여넣기 할 수 있는 바로 실행 가능한 샘플. + +### 전제 조건 + +- .NET 6.0 이상 (API는 .NET Framework에서도 동일하게 작동합니다). +- Aspose.Words for .NET (NuGet 패키지 `Aspose.Words`). +- 설치되지 않은 글꼴을 참조하는 Word 파일 (예: `MissingFont.docx`). + +위 조건을 갖추셨다면, 시작해봅시다. + +## Step 1 – 진단 컬렉터 활성화 (Font Settings 구성) + +먼저, Aspose.Words는 명시적으로 설정하면 글꼴 대체 경고를 기록합니다. 이는 `FontSettings` 객체를 생성하고 이를 `LoadOptions` 인스턴스에 할당함으로써 이루어집니다. 글꼴 처리를 위한 “디버그 라이트”를 켜는 것과 같습니다. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**왜?** +`FontSettings` 객체가 없으면 경고 컬렉터가 조용히 동작하며, 어떤 글꼴이 교체되었는지 알 수 없습니다. 빈 객체를 초기화함으로써 Aspose가 기본 시스템 글꼴을 사용하도록 하고 *또한* 모든 대체를 추적하도록 합니다. + +> **Pro tip:** 특정 폴더에 회사 글꼴이 들어있다면 `SetFontsFolder("path")` 로 `FontSettings`에 지정하세요. 이렇게 하면 누락된 글꼴 경고 수를 줄일 수 있습니다. + +## Step 2 – 구성된 옵션으로 문서 로드 (Word 문서 로드) + +컬렉터가 활성화되었으니, 동일한 `LoadOptions`를 사용해 `.docx` 파일을 로드합니다. 이때 Aspose가 문서를 스캔하고 모든 글꼴 참조를 확인하여 대체가 필요한지 판단합니다. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**왜 중요한가요?** +단순히 `new Document("MissingFont.docx")`를 호출하면 기본 설정이 적용되고 *경고 목록은 비어* 있습니다. `loadOptions`를 전달하면 진단 컬렉터가 로드 파이프라인에 연결됩니다. + +## Step 3 – 글꼴 대체 경고 가져오기 및 표시 (누락된 글꼴 감지) + +문서가 메모리에 로드된 후, Aspose는 모든 경고를 `document.WarningCallback.Warnings`에 저장합니다. 해당 컬렉션을 순회하면서 `WarningType.FontSubstitution`을 필터링하고 설명을 출력합니다. 각 설명은 어떤 글꼴이 누락되었고 대신 어떤 글꼴이 사용되었는지를 알려줍니다. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Expected console output** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +이 출력은 코드를 실행한 머신에서 정확히 어떤 글꼴이 누락되었는지를 알려줍니다. 이제 누락된 글꼴을 설치할지, 문서에 포함시킬지, 혹은 대체 상태를 유지할지 결정할 수 있습니다. + +![aspose 글꼴 대체 경고를 보여주는 콘솔 출력](/images/aspose-font-substitution-console.png) + +*이미지 대체 텍스트:* aspose 글꼴 대체 – 대체된 글꼴을 나열한 콘솔 출력 + +## Step 4 – 선택 사항: 대체 동작 사용자 정의 (누락된 글꼴 처리) + +때때로 단순히 *대체가 발생했다*는 사실만 알면 충분하지 않고, *어떻게* 대체되는지를 제어하고 싶을 때가 있습니다. Aspose.Words는 사용자 정의 `IFontSubstitutionRule`을 등록할 수 있게 합니다. 아래 예시는 누락된 모든 글꼴을 `Tahoma`로 강제 대체하도록 합니다. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**언제 사용하나요?** +웹 서비스용 PDF를 생성하고 모든 클라이언트가 `Tahoma`를 렌더링할 수 있다는 것을 안다면, 강제 대체를 통해 수십 개의 글꼴 파일을 배포하지 않아도 시각적 일관성을 보장할 수 있습니다. + +## 전체 작업 예제 (모든 단계 결합) + +새 콘솔 프로젝트에 붙여넣을 수 있는 전체 프로그램입니다. Aspose.Words NuGet 패키지를 설치했다고 가정하면 그대로 컴파일됩니다. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +프로그램을 실행하고 콘솔을 확인하면 모든 누락된 글꼴 이벤트가 출력되는 것을 볼 수 있습니다. 이를 통해 누락된 글꼴을 설치할지, 포함시킬지, 혹은 대체 상태를 유지할지 결정할 수 있습니다. + +## 자주 묻는 질문 + +**Q: PDF 변환에도 적용되나요?** +네. 나중에 `doc.Save("output.pdf")`를 호출하면 로드 중에 대체된 모든 글꼴이 PDF에 포함됩니다. 따라서 경고를 미리 포착하면 최종 PDF에서 예상치 못한 글꼴 변경을 방지할 수 있습니다. + +**Q: 처리할 문서가 많다면 어떻게 해야 하나요?** +로드 로직을 try‑catch 블록으로 감싸고 여러 문서에 걸쳐 단일 `FontSettings` 인스턴스를 재사용하세요. 이렇게 하면 오버헤드가 줄어들고 각 파일에 대해 경고 컬렉터가 활성화됩니다. + +**Q: 경고를 완전히 억제할 수 있나요?** +로드하기 전에 `loadOptions.WarningCallback = null;` 로 설정할 수 있지만, **누락된 글꼴을 감지**하는 기능을 잃게 됩니다—대부분의 경우 원하지 않는 동작입니다. + +## 결론 + +우리는 **aspose font substitution**을 마스터하기 위해 필요한 모든 내용을 다루었습니다: 진단 컬렉터 활성화, 맞춤 **font settings**로 Word 파일 로드, 누락된 글꼴 목록 추출, 그리고 기본 대체 규칙을 재정의하여 **누락된 글꼴을 직접 처리**하는 방법까지. 몇 줄의 C# 코드만으로도 미묘한 레이아웃 변화 뒤에 숨겨진 글꼴 문제를 완전히 파악할 수 있습니다. + +다음 단계는? `FontSettings.SetFontsFolder`를 사용해 원본 글꼴을 문서에 포함시키거나 `FontSourceBase`를 탐색해 데이터베이스에서 글꼴을 로드해 보세요. 또한 `Document.BuiltInStyle` 컬렉션을 실험해 스타일 수준의 글꼴 변경이 어떻게 전파되는지 확인할 수 있습니다. + +Aspose.Words나 글꼴 관리에 대해 더 궁금한 점이 있나요? 댓글을 남기거나 공식 Aspose 문서를 살펴보거나 새로운 프로젝트를 시작해 위 코드를 직접 실험해 보세요. 즐거운 코딩 되시고, 문서가 항상 의도한 대로 렌더링되길 바랍니다! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/basic-conversions/_index.md b/words/polish/net/basic-conversions/_index.md index 209d5ec211..09b66b1a07 100644 --- a/words/polish/net/basic-conversions/_index.md +++ b/words/polish/net/basic-conversions/_index.md @@ -23,8 +23,9 @@ Basic Conversions przeprowadzi Cię przez podstawowe konwersje dokumentów przy | --- | --- | | [Konwertuj Doc do Docx](./doc-to-docx/) | Dowiedz się, jak przekonwertować DOC na DOCX za pomocą Aspose.Words dla .NET. Przewodnik krok po kroku z przykładami kodu. Idealny dla programistów. | | [Konwertuj Docx do RTF](./docx-to-rtf/) | Dowiedz się, jak przekonwertować DOCX na RTF za pomocą Aspose.Words dla .NET dzięki naszemu przewodnikowi krok po kroku. Łatwa konwersja dla bezproblemowego przetwarzania dokumentów. | -| [Konwertuj plik Word do PDF](./docx-to-pdf/) Dowiedz się, jak łatwo konwertować pliki Word do PDF za pomocą Aspose.Words dla .NET z naszym przewodnikiem. Idealne dla programistów poszukujących szybkiej i niezawodnej konwersji dokumentów. | +| [Konwertuj plik Word do PDF](./docx-to-pdf/) Dowiedz się, jak łatwo konwertować pliki Word do PDF za pomocą Aspose.Words dla .NET z naszym przewodnikiem. Idealne dla programistów poszukujących szybkiej i niezawodnej konwersji dokumentów. | | [Konwertuj Word do PDF w C# przy użyciu Aspose.Words – przewodnik](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Dowiedz się, jak w prosty sposób konwertować dokumenty Word do PDF w C# przy użyciu biblioteki Aspose.Words. | +| [Konwertuj Word do PDF w C# – Pełny przewodnik z Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Dowiedz się, jak w pełni konwertować dokumenty Word do PDF w C# przy użyciu Aspose.Words. Szczegółowy przewodnik krok po kroku. | | [Konwertuj Docx na Bajt](./docx-to-byte/) | Dowiedz się, jak przekonwertować Docx na tablicę bajtów w .NET przy użyciu Aspose.Words w celu wydajnego przetwarzania dokumentów. Zawiera przewodnik krok po kroku. | | [Konwertuj Docx do Epub](./docx-to-epub/) | Łatwa konwersja DOCX do EPUB za pomocą Aspose.Words dla .NET. Skorzystaj z naszego samouczka, aby zapewnić sobie bezproblemową integrację z aplikacjami .NET. | | [Konwertuj Docx na Mhtml i wysyłaj e-mailem](./docx-to-mhtml-and-sending-email/) | Dowiedz się, jak konwertować DOCX na MHTML i wysyłać e-maile za pomocą Aspose.Words dla .NET w tym przewodniku krok po kroku. Zwiększ swoją produktywność dzięki łatwej automatyzacji. | diff --git a/words/polish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/polish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..fab7e17640 --- /dev/null +++ b/words/polish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,196 @@ +--- +category: general +date: 2026-04-05 +description: Konwertuj Word na PDF w C# przy użyciu Aspose.Words. Dowiedz się, jak + zapisać plik docx jako PDF, wyeksportować dostępny PDF oraz efektywnie wczytywać + dokument Word. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: pl +og_description: Konwertuj dokumenty Word na PDF w C# z przewodnikiem krok po kroku. + Dowiedz się, jak zapisać plik docx jako PDF, wyeksportować dostępny PDF oraz wczytać + dokument Word przy użyciu Aspose.Words. +og_title: Konwertuj Word do PDF w C# – Kompletny poradnik Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Konwertuj Word do PDF w C# – Pełny przewodnik z Aspose.Words +url: /pl/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertowanie Word do PDF w C# – Kompletny poradnik programistyczny + +Zastanawiałeś się kiedyś, jak **convert word to pdf** bez walki z skomplikowanymi narzędziami wiersza poleceń lub usługami zewnętrznymi? Nie jesteś jedyny. Wielu programistów napotyka ten problem, gdy klient prosi o dostępny PDF bezpośrednio z pliku DOCX. Dobra wiadomość? Kilka linii C# i potężna biblioteka Aspose.Words pozwala w mgnieniu oka przekształcić dokument Word w zgodny ze standardami PDF. + +W tym przewodniku przejdziemy przez wszystko, co musisz wiedzieć: od podstaw **load word document**, przez konfigurację odpowiednich opcji do **how to export accessible pdf**, aż po zapisanie wyniku, abyś mógł **save docx as pdf** w sposób niezawodny. Po zakończeniu będziesz mieć gotowy fragment kodu, który możesz wkleić do dowolnego projektu .NET. + +> **Pro tip:** Jeśli celujesz w zgodność z PDF/UA‑2 (standard dostępności wymagany przez wiele agencji rządowych), ten sam kod działa bez dodatkowych kroków — wystarczy ustawić odpowiednią flagę `PdfCompliance`. + +## Czego się nauczysz + +- Jak **load word document** przy użyciu Aspose.Words w C#. +- Dokładne ustawienia potrzebne do **how to export accessible pdf** (PDF/UA‑2). +- Kompletny, uruchamialny przykład, który **save docx as pdf** jednym wywołaniem metody. +- Typowe pułapki przy **c# convert docx pdf** i jak ich uniknąć. +- Szybkie sposoby na weryfikację, że wygenerowany PDF spełnia oczekiwania dostępności. + +Brak zewnętrznych narzędzi, brak niejasnych plików konfiguracyjnych — tylko czysty kod C#, który możesz skompilować już dziś. + +## Wymagania wstępne + +Zanim zanurkujemy, upewnij się, że masz: + +1. **.NET 6.0** (lub dowolną nowszą wersję .NET) zainstalowaną. Starsze frameworki również działają, ale składnia poniżej zakłada nowoczesny SDK. +2. Licencję **license** dla Aspose.Words for .NET. Biblioteka oferuje darmowy trial, ale w produkcji będziesz potrzebować ważnego klucza. +3. Pakiet NuGet **Aspose.Words** dodany do projektu: + +```bash +dotnet add package Aspose.Words +``` + +To wszystko — żadnych dodatkowych binarek, żadnego COM interop, tylko czyste odwołanie NuGet. + +![konwertowanie word do pdf przy użyciu Aspose.Words w C#](image-placeholder.png "konwertowanie word do pdf przy użyciu Aspose.Words w C#") + +## Implementacja krok po kroku + +Poniżej dzielimy proces na logiczne fragmenty. Każdy krok zawiera mały fragment kodu, wyjaśnienie **dlaczego** jest istotny oraz wskazówkę wynikającą z praktycznego użycia. + +### ## Konwertowanie Word do PDF – Ładowanie dokumentu źródłowego + +Pierwszą rzeczą, którą musisz zrobić, jest **load word document** do pamięci. Aspose.Words ukrywa szczegóły parsowania OpenXML, więc możesz pracować z plikami DOCX, DOC lub nawet RTF, nie martwiąc się o dziwactwa formatu. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Dlaczego to jest ważne:** +Załadowanie pliku tworzy obiekt `Document`, który reprezentuje cały plik Word, w tym nagłówki, stopki, style i ukryte metadane. Jeśli pominiesz ten krok lub spróbujesz odczytać plik jako surowy strumień, utracisz informacje o układzie, które później decydują o wyglądzie PDF. + +> **Side note:** Ten sam konstruktor `Document` działa dla `.doc` i `.rtf`. Oznacza to, że możesz **c# convert docx pdf** nawet gdy źródło nie jest ściśle DOCX. + +### ## Zapisz DOCX jako PDF – Konfiguracja zgodności PDF/UA‑2 + +Teraz, gdy dokument jest w pamięci, informujemy Aspose.Words, jak ma zostać wygenerowany PDF. Dla większości przypadków domyślne ustawienia są wystarczające, ale gdy potrzebujesz **accessible PDF**, musisz włączyć flagę zgodności PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Dlaczego to jest ważne:** +`PdfCompliance.PdfUAXmpA2` instruuje bibliotekę, aby osadziła niezbędne tagi i struktury, na których polegają czytniki ekranu. Bez tej flagi możesz otrzymać idealnie wyglądający PDF, który nie przejdzie audytu dostępności. + +> **Tip:** Jeśli potrzebujesz tylko zwykłego PDF, możesz pominąć linię `Compliance`. Reszta opcji nadal zapewnia wysokiej jakości wynik. + +### ## Konwertowanie Word do PDF – Zapis pliku + +Mając gotowe opcje, ostatnim krokiem jest **save docx as pdf**. To pojedyncze wywołanie wykonuje całą ciężką pracę: konwersję układu, osadzanie czcionek i tagowanie dostępności. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Co otrzymujesz:** +- Plik PDF w `outputPath`, który odzwierciedla układ Word. +- Jeśli użyto flagi `PdfUAXmpA2`, PDF będzie oznaczony jako zgodny z PDF/UA‑2. +- Wszystkie czcionki są osadzone, więc plik wygląda identycznie na każdej maszynie. + +### ## Weryfikacja dostępnego PDF (Opcjonalnie, ale zalecane) + +Po konwersji warto dwukrotnie sprawdzić, czy PDF naprawdę **how to export accessible pdf** poprawnie. Możesz użyć darmowych narzędzi, takich jak „Accessibility Check” w Adobe Acrobat Reader lub walidatora open‑source `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Jeśli walidator nie zgłasza błędów, udało Ci się **convert word to pdf** z pełnym wsparciem dostępności. + +### ## Typowe pułapki przy konwersji C# DOCX do PDF + +| Problem | Dlaczego się dzieje | Rozwiązanie | +|-------|----------------|-----| +| Brakujące czcionki | Źródłowy DOCX używa niestandardowej czcionki, która nie jest zainstalowana na serwerze. | Ustaw `EmbedFullFonts = true` lub zainstaluj czcionkę na maszynie. | +| Duży rozmiar pliku | Obrazy są osadzone w pełnej rozdzielczości. | Użyj `ImageCompression = PdfImageCompression.Jpeg` i ustaw `JpegQuality` na niższą wartość. | +| Uszkodzone hiperłącza | Linki wskazują na ścieżki względne, które nie istnieją po stronie klienta. | Upewnij się, że URL‑e są bezwzględne lub dostosuj właściwość `HyperlinkTarget`. | +| Brak tagów dostępności | Flaga `Compliance` nie jest ustawiona. | Dodaj `Compliance = PdfCompliance.PdfUAXmpA2` jak pokazano powyżej. | + +Pamiętając o tych kwestiach, uczynisz swoją procedurę **c# convert docx pdf** solidną i gotową do produkcji. + +## Pełny działający przykład + +Łącząc wszystko razem, oto samodzielna aplikacja konsolowa, którą możesz skompilować i uruchomić od razu. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** Po uruchomieniu programu znajdziesz `output.pdf` w `C:\Docs`. Otwórz go w dowolnym przeglądarce PDF; układ powinien dokładnie odpowiadać `input.docx`, a sprawdzenie dostępności potwierdzi zgodność z PDF/UA‑2. + +## Podsumowanie + +Właśnie przeszliśmy przez kompletną, kompleksową rozwiązanie, jak **convert word to pdf** przy użyciu C# i Aspose.Words. Dzięki **load word document**, skonfigurowaniu odpowiednich `PdfSaveOptions` i w końcu **save docx as pdf**, otrzymujesz wysokiej jakości, dostępny PDF przy minimalnym kodzie. Niezależnie od tego, czy tworzysz mikroserwis generujący dokumenty, czy konwerter wsadowy działający lokalnie, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-markdownsaveoptions/_index.md b/words/polish/net/programming-with-markdownsaveoptions/_index.md index 1b3955d9fc..f3c9be05f8 100644 --- a/words/polish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/polish/net/programming-with-markdownsaveoptions/_index.md @@ -46,6 +46,12 @@ Kompletny przewodnik krok po kroku, jak zapisać plik DOCX jako Markdown przy u ### [Jak wyeksportować Markdown z DOCX – Kompletny przewodnik](./how-to-export-markdown-from-docx-complete-guide/) Kompletny przewodnik pokazujący, jak wyeksportować pliki DOCX do formatu Markdown przy użyciu Aspose.Words dla .NET. +### [Konwertuj DOCX do Markdown – wyodrębnij obrazy z DOCX przy użyciu Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Dowiedz się, jak wyodrębnić obrazy z plików DOCX podczas konwersji do formatu Markdown przy użyciu Aspose.Words dla .NET. + +### [Konwertuj Word do Markdown – Pełny przewodnik z eksportem PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +Kompletny przewodnik C# pokazujący, jak konwertować dokumenty Word do Markdown oraz eksportować je jako PDF/UA przy użyciu Aspose.Words. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/polish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..cbe1a18b58 --- /dev/null +++ b/words/polish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Dowiedz się, jak konwertować DOCX na Markdown i wyodrębniać obrazy z + DOCX w C#. Przewodnik krok po kroku z pełnym kodem i wskazówkami. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: pl +og_description: Konwertuj DOCX na Markdown i wyodrębniaj obrazy z DOCX przy użyciu + Aspose.Words. Kompletny samouczek C# z kodem, wyjaśnieniem i wskazówkami najlepszych + praktyk. +og_title: Konwertuj DOCX na Markdown – Wyodrębnij obrazy z DOCX w C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Konwertuj DOCX na Markdown – wyodrębnij obrazy z DOCX przy użyciu Aspose.Words +url: /pl/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertuj DOCX do Markdown – Wyodrębnij obrazy z DOCX w C# + +Kiedykolwiek potrzebowałeś **konwertować DOCX do Markdown**, ale miałeś problem z tym, że obrazy znikają w wyniku? Nie jesteś jedyny. W wielu projektach wersja markdown jest idealna do kontroli wersji lub generatorów stron statycznych, jednak obrazy zostają pominięte, zamieniając bogaty dokument w pusty plik tekstowy. + +Dobre wieści? Dzięki kilku liniom C# i Aspose.Words możesz **konwertować DOCX do Markdown** *oraz* **wyodrębniać obrazy z DOCX** automatycznie. Ten przewodnik przeprowadzi Cię przez cały proces, wyjaśni, dlaczego każdy element ma znaczenie, i pokaże, jak utrzymać porządek w folderze z obrazami. + +## Co się nauczysz + +- Jak załadować DOCX zawierający obrazy. +- Jak zdefiniować własny `IResourceSavingCallback`, który decyduje, gdzie trafia każdy obraz. +- Jak skonfigurować `MarkdownSaveOptions`, aby wygenerowany markdown prawidłowo odwoływał się do wyodrębnionych obrazów. +- Wskazówki dotyczące obsługi przypadków brzegowych, takich jak duplikaty nazw obrazów lub formaty inne niż PNG. +- Pełny, gotowy do skopiowania i wklejenia przykład kodu, który możesz uruchomić już dziś. + +### Wymagania wstępne + +- .NET 6.0 lub nowszy (API działa na .NET Core, .NET Framework oraz .NET 5+). +- Licencja na **Aspose.Words for .NET** (bezpłatna wersja próbna wystarczy do testów). +- Podstawowa znajomość C# i Visual Studio (lub ulubionego IDE). + +Jeśli masz to wszystko, zanurzmy się. + +--- + +## Krok 1: Przygotuj projekt i zainstaluj Aspose.Words + +Najpierw utwórz nową aplikację konsolową (lub zintegrować ją z istniejącym rozwiązaniem). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Porada:** Użyj najnowszej wersji NuGet (stan na kwiecień 2026 to 24.12), aby uzyskać najnowsze ulepszenia eksportu markdown. + +--- + +## Krok 2: Utwórz callback, aby zapisywać obrazy tam, gdzie chcesz + +Aspose.Words pozwala przechwycić każdy zasób (obrazy, SVG itp.), który jest zapisywany podczas eksportu markdown. Implementując `IResourceSavingCallback` możesz: + +1. Wybrać folder znajdujący się obok pliku markdown. +2. Wygenerować unikalną nazwę pliku (aby nigdy nie nadpisać istniejącego obrazu). +3. Zadecydować o formacie (tutaj wymuszamy PNG dla spójności). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Dlaczego nazwa oparta na GUID? + +Jeśli źródłowy DOCX zawiera dwa obrazy o tej samej pierwotnej nazwie, proste kopiowanie i wklejanie nadpisałoby jeden z nich. Użycie `Guid.NewGuid()` zapewnia unikalność, co jest szczególnie przydatne przy wielokrotnym uruchamianiu konwersji w zautomatyzowanym potoku. + +--- + +## Krok 3: Załaduj DOCX i skonfiguruj opcje Markdown + +Teraz wczytujemy dokument do pamięci i podłączamy właśnie utworzony callback. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Co robi kod, krok po kroku + +| Krok | Cel | +|------|-----| +| **Zdefiniuj ścieżki** | Utrzymuje projekt elastycznym; możesz wskazać dowolny folder bez konieczności rekompilacji. | +| **Załaduj DOCX** | `Document` parsuje plik Word, udostępniając wszystkie elementy (akapity, tabele, obrazy). | +| **Skonfiguruj `MarkdownSaveOptions`** | `ResourceSavingCallback` jest hakiem, który wyodrębnia obrazy. Bez niego Aspose.Words osadziłby obrazy jako ciągi base64 lub całkowicie je pominął, w zależności od ustawień. | +| **Zapisz** | `doc.Save` zapisuje plik markdown i wywołuje callback dla każdego obrazu. | + +--- + +## Krok 4: Zweryfikuj wynik – co powinieneś zobaczyć? + +Po uruchomieniu programu otwórz `DocWithImages.md`. Zauważysz linki do obrazów w markdown, które wyglądają tak: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +A w `C:\Docs\MarkdownResources` znajdziesz serię plików PNG o nazwach GUID. Otwórz dowolny z nich – powinien być identyczny z obrazem osadzonym w oryginalnym DOCX. + +Jeśli otworzysz plik markdown w przeglądarce, która respektuje ścieżki względne (np. podgląd w VS Code, GitHub lub generator stron statycznych), obrazy zostaną wyświetlone tak samo jak w Wordzie. + +### Typowe pułapki i jak ich uniknąć + +| Objaw | Prawdopodobna przyczyna | Rozwiązanie | +|-------|--------------------------|-------------| +| Obrazy wyświetlają się jako uszkodzone linki | `ResourceFileName` nie został ustawiony, więc markdown wskazuje na nieistniejący plik. | Upewnij się, że w callbacku jest `args.ResourceFileName = newFileName;`. | +| Pliki PNG są bardzo duże | Oryginalne obrazy były JPEG lub BMP; konwersja do PNG może zwiększyć rozmiar. | Wykryj oryginalny format za pomocą `args.ResourceContentType` i zachowaj go: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplikaty obrazów nadal się pojawiają | Użyto statycznej nazwy pliku zamiast GUID. | Wróć do logiki GUID lub dodaj licznik dla każdego typu obrazu. | +| Konwersja rzuca `FileNotFoundException` | Ścieżka do źródłowego DOCX jest nieprawidłowa lub folder nie ma uprawnień do odczytu. | Sprawdź ścieżkę i przyznaj odpowiednie prawa systemu plików. | + +--- + +## Krok 5: Zaawansowane modyfikacje (opcjonalnie) + +### 5.1 Zachowaj oryginalne formaty obrazów + +Jeśli chcesz, aby wyjściowe obrazy zachowały swoje pierwotne rozszerzenia, zmodyfikuj callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Osadzaj obrazy jako Base64 (gdy *nie* chcesz osobnych plików) + +Czasami wygodniejszy jest markdown w jednym pliku (np. do wysyłki e‑mail). Zmień opcję: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Jednak pamiętaj: **wyodrębniać obrazy z DOCX** jest głównym celem w większości przepływów pracy z generatorami stron statycznych, więc podejście z folderem jest zazwyczaj lepszym wyborem. + +--- + +## Pełny działający przykład (gotowy do kopiowania i wklejania) + +Poniżej znajduje się cały program w jednym pliku. Wystarczy podmienić ścieżki na własne i uruchomić. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Uruchom go poleceniem `dotnet run`. Gdy konsola wyświetli linię z ✅, otwórz plik markdown i powinieneś zobaczyć obrazy poprawnie wyświetlone. + +--- + +## Podsumowanie + +Masz teraz **kompletną, gotową do produkcji metodę konwertowania DOCX do Markdown i wyodrębniania obrazów z DOCX** przy użyciu Aspose.Words w C#. Główne słowo kluczowe pojawia się w całym przewodniku, podkreślając jego znaczenie zarówno dla wyszukiwarek, jak i asystentów AI. + +W jednym przebiegu kod: + +1. Ładuje dokument Word. +2. Przechwytuje każdy obraz za pomocą `IResourceSavingCallback`. +3. Zapisuje każdy obraz w przewidywalnym folderze pod unikalną nazwą. +4. Generuje markdown, który odwołuje się do tych obrazów. + +From here you can: +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/polish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..be6800c8b5 --- /dev/null +++ b/words/polish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-05 +description: Szybko konwertuj Worda na Markdown i dowiedz się, jak zapisać jako PDF/UA + w C#. Krok po kroku kod, wskazówki i obsługa przypadków brzegowych. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: pl +og_description: Konwertuj Word na Markdown i zapisz jako PDF/UA przy użyciu Aspose.Words. + Dowiedz się, dlaczego, jak to zrobić oraz poznaj wskazówki najlepszych praktyk w + jednym zwięzłym przewodniku. +og_title: Konwertuj Word na Markdown – Kompletny samouczek C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Konwertuj Word na Markdown – Pełny przewodnik z eksportem PDF/UA +url: /pl/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwertowanie Word do Markdown – Pełny przewodnik z eksportem PDF/UA + +Zastanawiałeś się kiedyś, jak **convert Word to Markdown** bez utraty równań czy obrazów? Nie jesteś jedyny. Wielu programistów potrzebuje niezawodnego sposobu na przekształcenie plików `.docx` w czysty Markdown, jednocześnie zachowując możliwość **save as PDF/UA** dla PDF‑ów zgodnych z wymogami dostępności. W tym samouczku przeprowadzimy Cię przez kompletną, gotową do uruchomienia rozwiązanie przy użyciu Aspose.Words for .NET, wyjaśnimy, dlaczego każde ustawienie ma znaczenie, i pokażemy, jak radzić sobie z trudniejszymi elementami, takimi jak OfficeMath i pływające kształty. + +Pod koniec tego przewodnika będziesz mieć pojedynczy program w C#, który: + +1. Wczytuje dokument Word z relaksowanym odzyskiwaniem (aby uszkodzone pliki nie przerywały działania). +2. Eksportuje go do Markdown, przekształcając równania w LaTeX i zapisując obrazy za pomocą niestandardowego callbacku. +3. Zapisuje ten sam dokument jako plik zgodny z PDF/UA‑2, osadzając pływające kształty jako tagi inline. + +Brzmi jak sporo? Bez obaw — zanurzmy się. + +## Czego będziesz potrzebować + +- **Aspose.Words for .NET** (najnowsza wersja, 23.x w momencie pisania). +- Środowisko programistyczne .NET (Visual Studio 2022, Rider lub `dotnet` CLI). +- Przykładowy plik Word (`input.docx`) umieszczony w folderze, do którego możesz odwołać się. +- Podstawowa znajomość składni C# — nic egzotycznego, tylko kilka instrukcji `using`. + +> **Wskazówka:** Jeśli używasz menedżera pakietów NuGet, dodaj bibliotekę przy użyciu +> `dotnet add package Aspose.Words` lub przez interfejs NuGet w Visual Studio. + +## Krok 1 – Wczytaj dokument Word z relaksowanym odzyskiwaniem + +Kiedy otrzymujesz pliki Word z zewnętrznych źródeł, mogą one zawierać drobne uszkodzenia. Włączenie odzyskiwania **Relaxed** powoduje, że Aspose.Words kontynuuje działanie zamiast rzucać wyjątek. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Dlaczego to jest ważne:** +- `RecoveryMode.Relaxed` zapobiega, aby pojedynczy niepoprawny akapit przerywał całą konwersję. +- Dostarczenie obiektu `FontSettings` zapewnia, że brakujące czcionki są zastępowane w sposób elegancki, co jest kluczowe przy późniejszym renderowaniu równań jako LaTeX. + +## Krok 2 – Eksport do Markdown (OfficeMath → LaTeX, obrazy przez Callback) + +Markdown nie posiada natywnego sposobu reprezentacji równań Word. Aspose.Words może przetłumaczyć obiekty **OfficeMath** na LaTeX, który rozumie większość rendererów Markdown. Obrazy jednak muszą być gdzieś zapisane; niestandardowy **resource‑saving callback** daje pełną kontrolę nad strukturą folderów i nazewnictwem. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback zapisywania zasobów + +Poniżej znajduje się mała implementacja, która zapisuje każdy obraz w podfolderze o nazwie `images` i nazywa pliki `img001.png`, `img002.png` itd. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Dlaczego tego potrzebujesz:** +- Bez callbacku Aspose.Words tworzy płaski folder z losowymi nazwami GUID, co utrudnia kontrolę wersji. +- Kontrolując schemat nazewnictwa, utrzymujesz repozytorium Markdown w porządku i zapewniasz powtarzalność. + +### Oczekiwany wynik Markdown + +Otwórz `doc.md` po uruchomieniu i zobaczysz: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Równania pojawiają się jako LaTeX otoczone `$$ … $$`, a obrazy odwołują się do folderu `images`, który właśnie utworzyłeś. + +## Krok 3 – Eksport do PDF/UA‑2 (gotowy pod kątem dostępności) + +Jeśli musisz udostępnić dokument użytkownikom korzystającym z czytników ekranu lub innych technologii wspomagających, zgodność z **PDF/UA‑2** jest złotym standardem. Aspose.Words może wymusić to jednym flagiem, a także spłaszczyć pływające kształty do tagów inline, aby nie zginęły podczas konwersji. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Dlaczego PDF/UA jest ważny:** +- PDF/UA (Universal Accessibility) zapewnia, że wynikowy PDF zawiera odpowiednie tagowanie, logiczną kolejność czytania oraz tekst alternatywny dla obrazów. +- Ustawienie `ExportFloatingShapesAsInlineTag` zapewnia, że kształty takie jak pola tekstowe czy dymki nie są pomijane ani niepoprawnie rozmieszczone — częsty problem przy konwersji złożonych układów. + +### Weryfikacja zgodności PDF/UA + +Po eksporcie otwórz PDF w Adobe Acrobat Pro i uruchom **„Accessibility Check”** (Narzędzia → Accessibility → Full Check). Jeśli narzędzie zgłosi **0 błędów**, udało Ci się. + +## Przypadki brzegowe i typowe pułapki + +| Sytuacja | Na co zwrócić uwagę | Rozwiązanie / Rekomendacja | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Plik Word zawiera **unsupported fonts** | Czcionki mogą być zastąpione, co psuje układ równań | Podaj własny obiekt `FontSettings` z czcionkami zapasowymi. | +| Duże dokumenty (> 100 MB) | Obciążenie pamięci podczas konwersji | Użyj `LoadOptions` z `LoadFormat.Docx` i strumieniuj plik. | +| Obrazy są grafiką wektorową **EMF/WMF** | Mogą zostać niezamierzenie rasteryzowane | Przekonwertuj je na PNG przy użyciu `ImageSaveOptions` przed zapisem. | +| PDF/UA nie przechodzi walidacji przy **nested tables** | Tagowanie może stać się niejednoznaczne | Włącz `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit`, aby pomóc silnikowi. | +| Potrzeba **preserve custom styles** | Markdown ma ograniczone możliwości stylizacji | Wyeksportuj plik CSS razem z Markdown i odwołaj się do niego. | + +## Pełny działający przykład (cały kod razem) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Uruchom program, a znajdziesz zarówno `doc.md` (z równaniami LaTeX i czystymi linkami do obrazów), jak i `doc.pdf` (w pełni zgodny z PDF/UA‑2) w folderze `YOUR_DIRECTORY`. + +## Przegląd wizualny + +![przykład konwersji word do markdown](https://example.com/placeholder.png "przykład konwersji word do markdown – pokazuje wejściowy Word, wyjściowy Markdown i plik PDF/UA") + +*Alt text:* **przykład konwersji word do markdown** – diagram przedstawiający przepływ konwersji z pliku Word do Markdown i PDF/UA. + +## Podsumowanie i kolejne kroki + +Właśnie **converted Word to Markdown** zachowując równania w całości, zapisaliśmy obrazy w uporządkowanym folderze i wyprodukowaliśmy plik **save as PDF/UA**, który przechodzi kontrole dostępności. Najważniejsze wnioski to: + +- Użyj `LoadOptions.RecoveryMode.Relaxed`, aby tolerować nieidealne pliki Word. +- Ustaw `OfficeMathExportMode` na `LaTeX`, aby uzyskać czyste renderowanie równań. +- Zaimplementuj `ResourceSavingCallback`, aby kontrolować wyjście obrazów. +- Włącz `PdfCompliance.PdfUAXmpA2` oraz `ExportFloatingShapesAsInlineTag`, aby uzyskać PDF zgodny ze standardami. + +### Co warto zbadać dalej? + +- **Custom CSS for Markdown** – wygeneruj arkusz stylów odzwierciedlający style z Word. +- **Batch processing** – przeiteruj katalog z plikami `.docx`, aby zautomatyzować duże migracje. +- **Advanced PDF/UA features** – dodaj własne tagi, ustaw atrybuty języka lub osadź opisy audio. +- **Integration with CI/CD** – zapewnij, że każde buildowanie automatycznie generuje dostępne PDF‑y. + +Jeśli napotkasz problem, sprawdź ponownie, czy wersja Aspose.Words odpowiada używanemu tutaj API, i pamiętaj, że dokumentacja biblioteki jest solidnym dodatkowym źródłem. + +Szczęśliwego kodowania, i niech Twoje dokumenty pozostaną zarówno piękne **i** dostępne! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/programming-with-txtsaveoptions/_index.md b/words/polish/net/programming-with-txtsaveoptions/_index.md index 44581dd48c..611eb48405 100644 --- a/words/polish/net/programming-with-txtsaveoptions/_index.md +++ b/words/polish/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Dzięki tym samouczkom będziesz w stanie w pełni wykorzystać funkcjonalności | [Dodaj znaczniki Bidi w dokumencie Word](./add-bidi-marks/) | Dowiedz się, jak dodawać znaki dwukierunkowe (Bidi) w dokumentach Worda przy użyciu Aspose.Words dla .NET z tego przewodnika. Zapewnij właściwy kierunek tekstu dla treści wielojęzycznych. | | [Użyj znaku tabulacji na poziomie, aby uzyskać wcięcie listy](./use-tab-character-per-level-for-list-indentation/) | Dowiedz się, jak tworzyć listy wielopoziomowe z wcięciami tabulacyjnymi przy użyciu Aspose.Words dla .NET. Postępuj zgodnie z tym przewodnikiem, aby uzyskać precyzyjne formatowanie listy w dokumentach. | | [Użyj znaku spacji na każdym poziomie do wcięcia listy](./use-space-character-per-level-for-list-indentation/) | Dowiedz się, jak tworzyć listy wielopoziomowe z wcięciem znaku spacji w Aspose.Words dla .NET. Przewodnik krok po kroku dotyczący precyzyjnego formatowania dokumentu. | - +| [Zapisz docx jako txt – Eksportuj równania Word do LaTeX w C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Dowiedz się, jak wyeksportować równania z dokumentu Word do formatu LaTeX przy zapisie jako plik txt przy użyciu C# i Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/polish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..70a5c2b618 --- /dev/null +++ b/words/polish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: zapisz docx jako txt przy użyciu Aspose.Words – szybko konwertuj Word + na txt i dowiedz się, jak eksportować równania matematyczne jako LaTeX. Prosty kod + C#, bez dodatkowych narzędzi. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: pl +og_description: Zapisz plik docx jako txt w C# i dowiedz się, jak wyeksportować równania + do LaTeX. Skorzystaj z tego przewodnika krok po kroku, aby przekonwertować Word + na txt z zachowanymi równaniami. +og_title: Zapisz docx jako txt – eksportuj równania Word do LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Zapisz docx jako txt – eksportuj równania Worda do LaTeX w C# +url: /pl/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# zapisz docx jako txt – Eksportuj równania Word do LaTeX w C# + +Czy kiedykolwiek potrzebowałeś **save docx as txt**, ale obawiałeś się, że twoje równania znikną lub zamienią się w nieczytelny bełkot? Nie jesteś sam. Wielu programistów napotyka ten problem, gdy próbują **convert word to txt** w celu dalszego przetwarzania, szczególnie gdy plik źródłowy zawiera obiekty Office Math. + +Dobre wieści? Dzięki kilku liniom C# i odpowiednim opcjom możesz nie tylko **convert Word to txt**, ale także zachować każde równanie jako czysty znacznik LaTeX. W tym samouczku przeprowadzimy Cię przez cały proces, wyjaśnimy, dlaczego każde ustawienie ma znaczenie, i pokażemy, jak zweryfikować wynik. + +Omówimy: + +* Instalację biblioteki Aspose.Words for .NET +* Ładowanie pliku `.docx` zawierającego równania matematyczne +* Konfigurację `TxtSaveOptions`, aby **how to export math** stało się ciągiem przyjaznym LaTeX‑owi +* Zapis pliku i sprawdzenie wyjścia + +Po zakończeniu będziesz mieć wielokrotnego użytku fragment kodu, który pozwala **save docx as txt**, zachowując każdą formułę jako LaTeX — idealny dla pipeline’ów naukowych, generatorów statycznych stron lub dowolnego przepływu pracy wymagającego czystego tekstu matematycznego. + +--- + +## Wymagania wstępne + +Zanim zanurkujemy, upewnij się, że masz: + +* .NET 6.0 lub nowszy (kod działa również z .NET Framework 4.6+) +* Visual Studio 2022 (lub dowolne IDE, które preferujesz) +* Pakiet NuGet **Aspose.Words for .NET** – zainstaluj go przy pomocy + +```bash +dotnet add package Aspose.Words +``` + +Nie są wymagane żadne dodatkowe konwertery ani zewnętrzne narzędzia; Aspose.Words radzi sobie z ciężką pracą wewnętrznie. + +--- + +## Krok 1: Zainstaluj i odwołaj się do Aspose.Words + +Najpierw dodaj bibliotekę do swojego projektu. Jeśli używasz wiersza poleceń, uruchom powyższą komendę. W Visual Studio możesz także kliknąć prawym przyciskiem **Dependencies → Manage NuGet Packages** i wyszukać *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Używaj najnowszej stabilnej wersji (stan na kwiecień 2026 to 24.10). Nowsze wydania zawierają poprawki błędów związanych z obsługą OfficeMath, więc unikniesz nieoczekiwanych brakujących symboli. + +--- + +## Krok 2: Załaduj dokument źródłowy + +Teraz pobieramy plik `.docx`, który zawiera równania, które chcesz zachować. Klasa `Document` abstrahuje cały plik Word, dając dostęp do tekstu, obrazów i obiektów Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Dlaczego najpierw go ładować? Aspose.Words parsuje plik do modelu obiektowego, co pozwala nam przeglądać lub modyfikować zawartość przed podjęciem decyzji o eksporcie. To właśnie tutaj decyzje **how to export math** zaczynają mieć znaczenie. + +--- + +## Krok 3: Skonfiguruj TxtSaveOptions do eksportu LaTeX + +Serce rozwiązania stanowi klasa `TxtSaveOptions`. Domyślnie zapisywanie do TXT usuwa całkowicie Office Math. Ustawienie `OfficeMathExportMode` na `LaTeX` instruuje bibliotekę, aby przetłumaczyła każde równanie na jego reprezentację LaTeX. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX jest lingua franca publikacji naukowych. Eksportując w ten sposób, zachowujesz semantykę równania zamiast płaskiego obrazu lub zniekształconego ciągu znaków. Jeśli później przekażesz plik TXT do procesora Markdown obsługującego MathJax, równania zostaną wyrenderowane perfekcyjnie. + +--- + +## Krok 4: Zapisz dokument jako zwykły tekst + +Po skonfigurowaniu opcji, ostatni krok to jednowierszowy kod zapisujący plik na dysk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +I to wszystko — twój `.docx` jest teraz plikiem `.txt`, w którym każde równanie pojawia się jako fragment LaTeX, gotowy do dalszego przetwarzania. + +--- + +## Weryfikacja wyniku (Jak poprawnie zapisać txt) + +Otwórz `MathSample.txt` w dowolnym edytorze tekstu. Powinieneś zobaczyć coś w stylu: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Jeśli zauważysz surowe znaki specyficzne dla Worda (np. `?` lub brakujące symbole), sprawdź ponownie, że: + +* Używasz aktualnej wersji Aspose.Words (starsze kompilacje miały błędy w obsłudze OfficeMath). +* Dokument źródłowy faktycznie zawiera obiekty **OfficeMath** — nie starsze obiekty Equation Editor. W przypadku tych drugich może być konieczna ręczna konwersja lub użycie metody `ConvertMathToOfficeMath` przed zapisem. + +--- + +## Typowe warianty i przypadki brzegowe + +| Sytuacja | Co zrobić | +|-----------|------------| +| **Legacy Equation Editor** objects | Wywołaj `doc.ConvertMathToOfficeMath()` przed krokiem 3. | +| **You need plain Unicode math, not LaTeX** | Ustaw `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Large documents (100 + MB)** | Strumieniuj operację zapisu używając `doc.Save(Stream, txtOptions)`, aby uniknąć wysokiego zużycia pamięci. | +| **You want to keep the original file name** | Użyj `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` przy konstruowaniu ścieżki wyjściowej. | + +Te drobne zmiany odpowiadają na pytanie “**how to export math**” w różnych pipeline’ach, zapewniając, że rozwiązanie będzie solidne niezależnie od źródła. + +--- + +## Pełny działający przykład (Wszystkie kroki w jednym miejscu) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Uruchom program, otwórz wygenerowany `.txt`, i zobaczysz równania LaTeX wstawione dokładnie tam, gdzie powinny być. To najprostszy sposób na **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/polish/net/working-with-fonts/_index.md b/words/polish/net/working-with-fonts/_index.md index 5208aef90b..895ec15ca5 100644 --- a/words/polish/net/working-with-fonts/_index.md +++ b/words/polish/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ Niezależnie od tego, czy chcesz formatować tekst za pomocą różnych czcionek | [Otrzymaj powiadomienie ostrzegawcze](./receive-warning-notification/) Dowiedz się, jak otrzymywać powiadomienia ostrzegawcze podczas korzystania z Aspose.Words dla platformy .NET i jak zarządzać wszelkimi problemami lub ostrzeżeniami w dokumentach. | | [Przykład źródła czcionki Steam](./resource-steam-font-source-example/) | Dowiedz się, jak używać źródła czcionek strumienia zasobów do ładowania niestandardowych czcionek do Aspose.Words dla platformy .NET. | | [Uzyskaj zamiennik bez sufiksów](./get-substitution-without-suffixes/) | W tym samouczku dowiesz się, jak uzyskać nadpisania bez sufiksów w dokumencie programu Word za pomocą Aspose.Words dla platformy .NET. | - +| [Podstawianie czcionek Aspose – Wykrywanie brakujących czcionek w dokumentach Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Dowiedz się, jak wykrywać brakujące czcionki w dokumentach Word przy użyciu Aspose.Words dla .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/polish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/polish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..d61f27fc41 --- /dev/null +++ b/words/polish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Przewodnik Aspose dotyczący zamiany czcionek, aby wykrywać brakujące + czcionki podczas ładowania dokumentu Word. Dowiedz się, jak konfigurować ustawienia + czcionek i efektywnie obsługiwać brakujące czcionki. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: pl +og_description: Przewodnik Aspose dotyczący podstawiania czcionek w celu wykrycia + brakujących czcionek podczas ładowania dokumentu Word. Dowiedz się, jak konfigurować + ustawienia czcionek i efektywnie obsługiwać brakujące czcionki. +og_title: Zastępowanie czcionek Aspose – Wykrywanie brakujących czcionek w dokumentach + Word +tags: +- Aspose.Words +- C# +- Font Management +title: Zastępowanie czcionek Aspose – wykrywanie brakujących czcionek w dokumentach + Word +url: /pl/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Wykrywanie brakujących czcionek w dokumentach Word + +Czy zdarzyło Ci się, że plik Word wygląda idealnie na jednym komputerze, a na innym wyświetla dziwne zmiany czcionek? To klasyczny problem **aspose font substitution**, który zazwyczaj oznacza brak niektórych czcionek w systemie docelowym. W tym samouczku pokażemy Ci krok po kroku, jak **wykrywać brakujące czcionki** podczas **ładowania dokumentu Word**, jak **konfigurować ustawienia czcionek** oraz co zrobić, aby **obsługiwać brakujące czcionki** w elegancki sposób. + +Przejdziemy przez kompletny, gotowy do uruchomienia przykład w C#, wyjaśnimy, dlaczego każda linia ma znaczenie, i pokażemy oczekiwany wynik w konsoli. Po zakończeniu będziesz w stanie wykrywać zamiany czcionek w momencie ładowania dokumentu — bez domysłów. + +## Czego się nauczysz + +- Jak włączyć diagnostyczny kolektor ostrzeżeń czcionek w Aspose.Words. +- Dokładny kod potrzebny do **ładowania dokumentu Word** z niestandardowymi **ustawieniami czcionek**. +- Jak iterować po obiektach `WarningInfo`, aby wypisać każdą zamienioną czcionkę. +- Wskazówki, jak tłumić niechciane ostrzeżenia lub dostarczać czcionki zapasowe. +- Gotowy do uruchomienia przykład, który możesz skopiować i wkleić do Visual Studio. + +### Wymagania wstępne + +- .NET 6.0 lub nowszy (API działa tak samo na .NET Framework). +- Aspose.Words for .NET (pakiet NuGet `Aspose.Words`). +- Plik Word, który odwołuje się do czcionki, której nie masz zainstalowanej (np. `MissingFont.docx`). + +Jeśli masz to wszystko, zanurzmy się. + +## Krok 1 – Włączenie diagnostycznego kolektora (Konfiguracja ustawień czcionek) + +Na początek: Aspose.Words rejestruje ostrzeżenia o zamianie czcionek tylko wtedy, gdy mu to zlecisz. Robi się to poprzez utworzenie obiektu `FontSettings` i przypisanie go do instancji `LoadOptions`. Pomyśl o tym jak o włączeniu „świateł debugowania” dla obsługi czcionek. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Dlaczego?** +Bez obiektu `FontSettings` kolektor ostrzeżeń pozostaje cichy i nigdy nie dowiesz się, które czcionki zostały zamienione. Inicjalizując go pustym, pozwalamy Aspose używać domyślnych czcionek systemowych *i* śledzić wszystkie zamiany. + +**Wskazówka:** Jeśli wiesz, że konkretny folder zawiera firmowe czcionki, wskaż go w `FontSettings` za pomocą `SetFontsFolder("path")`. To może zmniejszyć liczbę ostrzeżeń o brakujących czcionkach. + +## Krok 2 – Ładowanie dokumentu z skonfigurowanymi opcjami (Load Word Document) + +Teraz, gdy kolektor jest aktywny, załaduj swój plik `.docx` używając tych samych `LoadOptions`. To moment, w którym Aspose skanuje dokument, wyszukuje wszystkie odwołania do czcionek i decyduje, czy wymagana jest zamiana. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Dlaczego to ma znaczenie?** +Jeśli po prostu wywołałbyś `new Document("MissingFont.docx")`, zastosowane byłyby ustawienia domyślne *i* lista ostrzeżeń pozostałaby pusta. Przekazanie `loadOptions` zapewnia, że diagnostyczny kolektor jest podłączony do procesu ładowania. + +## Krok 3 – Pobieranie i wyświetlanie ostrzeżeń o zamianie czcionek (Wykrywanie brakujących czcionek) + +Po załadowaniu dokumentu do pamięci, Aspose przechowuje wszystkie ostrzeżenia w `document.WarningCallback.Warnings`. Przejdź pętlą po tej kolekcji, przefiltruj elementy typu `WarningType.FontSubstitution` i wypisz opis. Każdy opis informuje, której czcionki brakowało i jaka została użyta zamiast niej. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Oczekiwany wynik w konsoli** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Ten wynik dokładnie informuje, które czcionki brakuje na maszynie uruchamiającej kod. Teraz możesz zdecydować, czy zainstalować brakujące czcionki, osadzić je w dokumencie, czy pozostawić zamianę. + +![Wynik w konsoli pokazujący ostrzeżenia o zamianie czcionek Aspose](/images/aspose-font-substitution-console.png) + +*Tekst alternatywny obrazu:* aspose font substitution – wynik w konsoli wymieniający zamienione czcionki + +## Krok 4 – Opcjonalnie: Dostosowanie zachowania zamiany (Obsługa brakujących czcionek) + +Czasami nie wystarczy wiedzieć *że* doszło do zamiany — chcesz kontrolować *jak* ona nastąpiła. Aspose.Words pozwala zarejestrować własną regułę `IFontSubstitutionRule`. Poniżej szybki przykład, który wymusza, aby każda brakująca czcionka przechodziła na `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Kiedy mógłbyś tego użyć?** +Jeśli generujesz PDF-y dla usługi internetowej i wiesz, że każdy klient potrafi renderować `Tahoma`, wymuszenie zapasowej czcionki zapewnia spójność wizualną bez konieczności dystrybuowania dziesiątek plików czcionek. + +## Pełny działający przykład (wszystkie kroki razem) + +Oto cały program, który możesz wkleić do nowego projektu konsolowego. Kompiluje się bez zmian, pod warunkiem że zainstalowałeś pakiet NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Uruchom program, obserwuj konsolę i zobaczysz wypisane wszystkie zdarzenia brakujących czcionek. Następnie możesz zdecydować, czy zainstalować brakujące czcionki, osadzić je, czy zachować zapasową. + +## Najczęściej zadawane pytania + +**Q: Czy to działa przy konwersji do PDF?** +**A:** Tak. Gdy później wywołasz `doc.Save("output.pdf")`, wszystkie czcionki, które zostały zamienione podczas ładowania, będą osadzone w PDF-ie. Dlatego wczesne wykrycie ostrzeżeń pomaga uniknąć niespodziewanych zmian czcionek w ostatecznym PDF-ie. + +**Q: Co zrobić, jeśli mam wiele dokumentów do przetworzenia?** +Umieść logikę ładowania w bloku try‑catch i ponownie używaj jednej instancji `FontSettings` dla wszystkich dokumentów. To zmniejsza narzut i utrzymuje kolektor ostrzeżeń aktywnym dla każdego pliku. + +**Q: Czy mogę całkowicie wyciszyć ostrzeżenia?** +Możesz ustawić `loadOptions.WarningCallback = null;` przed ładowaniem, ale stracisz możliwość **wykrywania brakujących czcionek** — co zazwyczaj nie jest pożądane. + +## Zakończenie + +Omówiliśmy wszystko, co potrzebne, aby opanować **aspose font substitution**: włączenie diagnostycznego kolektora, ładowanie pliku Word z niestandardowymi **ustawieniami czcionek**, wyodrębnianie listy brakujących czcionek oraz nadpisanie domyślnej reguły zamiany, aby **obsługiwać brakujące czcionki** po swojemu. Dzięki kilku linijkom C# uzyskasz pełną widoczność problemów z czcionkami, które w przeciwnym razie ukrywałyby się za subtelnymi zmianami układu. + +Co dalej? Spróbuj osadzić oryginalne czcionki w dokumencie za pomocą `FontSettings.SetFontsFolder` lub zbadaj `FontSourceBase`, aby ładować czcionki z bazy danych. Możesz także poeksperymentować z kolekcją `Document.BuiltInStyle`, aby zobaczyć, jak zmiany czcionek na poziomie stylu się rozprzestrzeniają. + +Masz więcej pytań dotyczących Aspose.Words lub zarządzania czcionkami? Dodaj komentarz, zapoznaj się z oficjalną dokumentacją Aspose lub uruchom nowy projekt i poeksperymentuj z powyższym kodem. Szczęśliwego kodowania i niech Twoje dokumenty zawsze renderują się dokładnie tak, jak zamierzasz! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/basic-conversions/_index.md b/words/portuguese/net/basic-conversions/_index.md index 52ea0a466d..8b6bfa16ad 100644 --- a/words/portuguese/net/basic-conversions/_index.md +++ b/words/portuguese/net/basic-conversions/_index.md @@ -33,6 +33,8 @@ Conversões Básicas orienta você nas conversões básicas de documentos usando | [Como Exportar LaTeX do Word – Guia Passo a Passo](./how-to-export-latex-from-word-step-by-step-guide/) | Aprenda a exportar conteúdo LaTeX de documentos Word usando Aspose.Words para .NET. Guia passo a passo com exemplos de código. | | [Converter Word para PDF em C# usando Aspose.Words – Guia](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aprenda a converter documentos Word para PDF em C# usando Aspose.Words com este guia passo a passo. | | [Salvar Word como PDF com Aspose.Words – Guia Completo C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aprenda a salvar documentos Word como PDF usando Aspose.Words em C#. Guia completo passo a passo. | +| [Converter Word para PDF em C# – Guia Completo com Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Aprenda a converter documentos Word para PDF em C# usando Aspose.Words com este guia completo passo a passo. | + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/portuguese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..d34c4f165a --- /dev/null +++ b/words/portuguese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,206 @@ +--- +category: general +date: 2026-04-05 +description: Converter Word para PDF em C# usando Aspose.Words. Aprenda como salvar + docx como PDF, exportar PDF acessível e carregar documento Word de forma eficiente. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: pt +og_description: Converta Word para PDF em C# com um guia passo a passo. Descubra como + salvar docx como PDF, exportar PDF acessível e carregar documento Word usando Aspose.Words. +og_title: Converter Word para PDF em C# – Tutorial Completo do Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Converter Word para PDF em C# – Guia Completo com Aspose.Words +url: /pt/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter Word para PDF em C# – Tutorial de Programação Completo + +Já se perguntou como **convert word to pdf** sem lutar com ferramentas de linha de comando complicadas ou serviços de terceiros? Você não está sozinho. Muitos desenvolvedores encontram esse obstáculo quando um cliente pede um PDF acessível direto de um arquivo DOCX. A boa notícia? Com algumas linhas de C# e a poderosa biblioteca Aspose.Words, você pode transformar um documento Word em um PDF compatível com padrões em um instante. + +Neste guia, percorreremos tudo o que você precisa saber: desde os fundamentos de **load word document**, passando pela configuração das opções corretas para **how to export accessible pdf**, e finalmente salvando o resultado para que você possa **save docx as pdf** de forma confiável. Ao final, você terá um trecho pronto‑para‑executar que pode ser inserido em qualquer projeto .NET. + +> **Dica profissional:** Se você estiver visando conformidade PDF/UA‑2 (o padrão de acessibilidade exigido por muitas agências governamentais), o mesmo código funciona sem passos adicionais—basta definir a flag `PdfCompliance` correta. + +--- + +## O que você vai aprender + +- Como **load word document** usando Aspose.Words em C#. +- As configurações exatas necessárias para **how to export accessible pdf** (PDF/UA‑2). +- Um exemplo completo e executável que **save docx as pdf** com uma única chamada de método. +- Armadilhas comuns ao **c# convert docx pdf** e como evitá‑las. +- Maneiras rápidas de verificar se o PDF gerado atende às expectativas de acessibilidade. + +Nenhuma ferramenta externa, nenhum arquivo de configuração obscuro—apenas código puro em C# que você pode compilar hoje. + +--- + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +1. **.NET 6.0** (ou qualquer versão recente do .NET) instalado. Frameworks mais antigos também funcionam, mas a sintaxe abaixo assume o SDK moderno. +2. Uma **licença** para Aspose.Words for .NET. A biblioteca oferece um teste gratuito, mas para produção você precisará de uma chave válida. +3. O pacote **Aspose.Words** NuGet adicionado ao seu projeto: + +```bash +dotnet add package Aspose.Words +``` + +É só isso—nenhum binário adicional, nenhuma interop COM, apenas uma referência limpa via NuGet. + +--- + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +--- + +## Implementação passo a passo + +A seguir, dividimos o processo em blocos lógicos. Cada etapa contém um pequeno trecho de código, uma explicação do **porquê** e uma dica baseada em uso real. + +### ## Convert Word to PDF – Load the Source Document + +A primeira coisa que você precisa fazer é **load word document** na memória. Aspose.Words abstrai o parsing OpenXML, permitindo trabalhar com arquivos DOCX, DOC ou até RTF sem se preocupar com peculiaridades de formato. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Por que isso importa:** +Carregar o arquivo cria um objeto `Document` que representa todo o arquivo Word, incluindo cabeçalhos, rodapés, estilos e metadados ocultos. Se você pular esta etapa ou tentar ler o arquivo como um fluxo bruto, perderá as informações de layout que mais tarde determinam como o PDF ficará. + +> **Nota lateral:** O mesmo construtor `Document` funciona para `.doc` e `.rtf`. Isso significa que você pode **c# convert docx pdf** mesmo quando a origem não é estritamente um DOCX. + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +Agora que o documento está na memória, informamos ao Aspose.Words como queremos que o PDF seja gerado. Para a maioria dos casos, as configurações padrão são suficientes, mas quando você precisa de um **accessible PDF** é necessário habilitar a flag de conformidade PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Por que isso importa:** +`PdfCompliance.PdfUAXmpA2` indica à biblioteca que ela deve incorporar as tags e estruturas necessárias que leitores de tela utilizam. Sem essa flag, você pode obter um PDF visualmente perfeito que falha em uma auditoria de acessibilidade. + +> **Dica:** Se você precisar apenas de um PDF regular, pode remover a linha `Compliance`. As demais opções ainda fornecem uma saída de alta qualidade. + +### ## Convert Word to PDF – Write the File + +Com as opções prontas, o passo final é **save docx as pdf**. Esta única chamada realiza todo o trabalho pesado: conversão de layout, incorporação de fontes e marcação de acessibilidade. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**O que você obtém:** +- Um arquivo PDF em `outputPath` que espelha o layout do Word. +- Se você usou a flag `PdfUAXmpA2`, o PDF será marcado como compatível com PDF/UA‑2. +- Todas as fontes são incorporadas, de modo que o arquivo tenha a mesma aparência em qualquer máquina. + +### ## Verify the Accessible PDF (Optional but Recommended) + +Após a conversão, é uma boa prática verificar se o PDF realmente **how to export accessible pdf** corretamente. Você pode usar ferramentas gratuitas como a “Verificação de Acessibilidade” do Adobe Acrobat Reader ou o validador open‑source `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Se o validador não relatar erros, você converteu **convert word to pdf** com suporte total à acessibilidade. + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| Problema | Por que acontece | Solução | +|----------|------------------|---------| +| Fontes ausentes | O DOCX de origem usa uma fonte personalizada que não está instalada no servidor. | Defina `EmbedFullFonts = true` ou instale a fonte na máquina. | +| Tamanho de arquivo grande | Imagens são incorporadas em resolução total. | Use `ImageCompression = PdfImageCompression.Jpeg` e ajuste `JpegQuality` para um valor menor. | +| Hiperlinks quebrados | Links apontam para caminhos relativos que não existem no cliente. | Garanta que as URLs sejam absolutas ou ajuste a propriedade `HyperlinkTarget`. | +| Tags de acessibilidade ausentes | Flag `Compliance` não foi definida. | Adicione `Compliance = PdfCompliance.PdfUAXmpA2` conforme mostrado acima. | + +Manter esses pontos em mente tornará sua rotina **c# convert docx pdf** robusta e pronta para produção. + +--- + +## Exemplo completo em funcionamento + +Juntando tudo, aqui está um aplicativo console autônomo que você pode compilar e executar agora mesmo. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Resultado esperado:** Após executar o programa, você encontrará `output.pdf` em `C:\Docs`. Abra-o em qualquer visualizador de PDF; o layout deve corresponder ao `input.docx` pixel‑por‑pixel, e uma verificação de acessibilidade confirmará a conformidade PDF/UA‑2. + +--- + +## Conclusão + +Acabamos de percorrer uma solução completa, de ponta a ponta, para **convert word to pdf** usando C# e Aspose.Words. Ao **load word document**, configurar as `PdfSaveOptions` corretas e finalmente **save docx as pdf**, você obtém um PDF de alta qualidade e acessível com código mínimo. Seja construindo um microserviço de geração de documentos, um conversor em lote on‑premise, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-markdownsaveoptions/_index.md b/words/portuguese/net/programming-with-markdownsaveoptions/_index.md index c6638c1efc..ab3aab21ea 100644 --- a/words/portuguese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/portuguese/net/programming-with-markdownsaveoptions/_index.md @@ -41,6 +41,9 @@ Aprenda a converter arquivos DOCX para Markdown em C# com instruções detalhada ### [Salvar docx como markdown – Guia completo em C# com extração de imagens](./save-docx-as-markdown-full-c-guide-with-image-extraction/) Aprenda a converter arquivos DOCX para Markdown em C#, extrair imagens e mantendo a formatação com Aspose.Words. +### [Converter DOCX para Markdown – Extrair Imagens do DOCX com Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Aprenda a converter DOCX para Markdown extraindo imagens usando Aspose.Words. + ### [Como Exportar Markdown do Word – Guia Completo em C#](./how-to-export-markdown-from-word-complete-c-guide/) Aprenda a exportar documentos Word para Markdown usando C# com Aspose.Words, passo a passo e exemplos de código. @@ -50,6 +53,9 @@ Aprenda a exportar documentos DOCX para Markdown usando C# com Aspose.Words, pas ### [Como salvar Markdown de DOCX – Guia passo a passo](./how-to-save-markdown-from-docx-step-by-step-guide/) Aprenda a salvar documentos DOCX como arquivos Markdown passo a passo usando Aspose.Words para .NET. +### [Converter Word para Markdown – Guia Completo com Exportação PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +Aprenda a converter documentos Word para Markdown e exportar PDFs compatíveis com PDF/UA usando Aspose.Words para .NET. + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/portuguese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..2edf49c063 --- /dev/null +++ b/words/portuguese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Aprenda como converter DOCX para Markdown e extrair imagens de DOCX em + C#. Guia passo a passo com código completo e dicas. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: pt +og_description: Converta DOCX para Markdown e extraia imagens de DOCX usando Aspose.Words. + Tutorial completo em C# com código, explicação e dicas de boas práticas. +og_title: Converter DOCX para Markdown – Extrair imagens de DOCX em C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Converter DOCX para Markdown – Extrair imagens do DOCX com Aspose.Words +url: /pt/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter DOCX para Markdown – Extrair Imagens de DOCX em C# + +Já precisou **converter DOCX para Markdown** mas teve dificuldades com as imagens desaparecendo na saída? Você não está sozinho. Em muitos projetos a versão markdown é perfeita para controle de versão ou geradores de sites estáticos, porém as imagens ficam para trás, transformando um documento rico em um arquivo de texto vazio. + +A boa notícia? Com algumas linhas de C# e Aspose.Words você pode **converter DOCX para Markdown** *e* **extrair imagens de DOCX** automaticamente. Este guia acompanha todo o processo, explica por que cada parte é importante e ainda mostra como manter sua pasta de imagens organizada. + +## O que você aprenderá + +- Como carregar um DOCX que contém imagens. +- Como definir um `IResourceSavingCallback` personalizado que decide onde cada imagem será salva. +- Como configurar `MarkdownSaveOptions` para que o markdown gerado faça referência às imagens extraídas corretamente. +- Dicas para lidar com casos extremos, como nomes de imagens duplicados ou formatos que não sejam PNG. +- Um exemplo de código completo, pronto para copiar e colar, que você pode executar hoje. + +### Pré-requisitos + +- .NET 6.0 ou posterior (a API funciona no .NET Core, .NET Framework e .NET 5+). +- Uma licença para **Aspose.Words for .NET** (a versão de avaliação gratuita funciona para testes). +- Familiaridade básica com C# e Visual Studio (ou sua IDE favorita). + +Se você tem isso, vamos mergulhar. + +--- + +## Etapa 1: Configurar o Projeto e Instalar o Aspose.Words + +Primeiro, crie um novo aplicativo console (ou integre em uma solução existente). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Dica profissional:** Use a versão mais recente do NuGet (em abril 2026 é 24.12) para obter as melhorias mais recentes de exportação para markdown. + +--- + +## Etapa 2: Criar um Callback para Salvar Imagens Onde Você Deseja + +Aspose.Words permite interceptar cada recurso (imagens, SVGs, etc.) que é escrito durante a exportação para markdown. Ao implementar `IResourceSavingCallback` você pode: + +1. Escolher uma pasta que fique ao lado do seu arquivo markdown. +2. Gerar um nome de arquivo único (para que você nunca sobrescreva uma imagem existente). +3. Decidir o formato (aqui forçamos PNG para consistência). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Por que um nome baseado em GUID? + +Se o DOCX de origem contém duas imagens com o mesmo nome original, uma simples cópia‑colagem sobrescreveria uma delas. Usar `Guid.NewGuid()` garante unicidade, o que é especialmente útil quando você executa a conversão muitas vezes em um pipeline automatizado. + +--- + +## Etapa 3: Carregar o DOCX e Configurar as Opções de Markdown + +Agora trazemos o documento para a memória e anexamos o callback que acabamos de criar. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### O que o código faz, passo a passo + +| Etapa | Propósito | +|------|-----------| +| **Definir caminhos** | Mantém seu projeto flexível; você pode apontar para qualquer pasta sem recompilar. | +| **Carregar o DOCX** | `Document` analisa o arquivo Word, tornando todos os elementos (parágrafos, tabelas, imagens) acessíveis. | +| **Configurar `MarkdownSaveOptions`** | O `ResourceSavingCallback` é o ponto de extensão que extrai as imagens. Sem ele, o Aspose.Words incorporaria as imagens como strings base64 ou as descartaria totalmente, dependendo das configurações. | +| **Salvar** | `doc.Save` grava o arquivo markdown e dispara o callback para cada imagem. | + +--- + +## Etapa 4: Verificar a Saída – O que Você Deve Ver? + +Depois de executar o programa, abra `DocWithImages.md`. Você notará links de imagem markdown que se parecem com isto: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +E em `C:\Docs\MarkdownResources` você encontrará uma série de arquivos PNG com nomes GUID. Abra qualquer um deles – eles devem ser idênticos às imagens que estavam incorporadas no DOCX original. + +Se você abrir o arquivo markdown em um visualizador que respeita caminhos relativos (por exemplo, pré‑visualização do VS Code, GitHub ou um gerador de sites estáticos), as imagens serão renderizadas exatamente como no Word. + +### Armadilhas Comuns & Como Evitá‑las + +| Sintoma | Causa Provável | Solução | +|---------|----------------|---------| +| Imagens aparecem como links quebrados | O `ResourceFileName` não foi definido, então o markdown aponta para um arquivo inexistente. | Garanta que `args.ResourceFileName = newFileName;` esteja dentro do callback. | +| Arquivos PNG são muito grandes | As imagens originais eram JPEG ou BMP; converter para PNG pode aumentar o tamanho. | Detecte o formato original via `args.ResourceContentType` e preserve‑o: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Imagens duplicadas ainda aparecem | Você usou um nome de arquivo estático em vez de um GUID. | Retorne à lógica de GUID ou adicione um contador por tipo de imagem. | +| Conversão lança `FileNotFoundException` | O caminho do DOCX de origem está errado ou a pasta não tem permissão de leitura. | Verifique o caminho e conceda as permissões de sistema de arquivos adequadas. | + +--- + +## Etapa 5: Ajustes Avançados (Opcional) + +### 5.1 Preservar Formatos Originais das Imagens + +Se você quiser que as imagens de saída mantenham suas extensões originais, modifique o callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Incorporar Imagens como Base64 (Quando Você *Não* Quer Arquivos Separados) + +Às vezes, um markdown de arquivo único é preferível (por exemplo, para envio por e‑mail). Altere a opção: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Mas lembre‑se: **extrair imagens de DOCX** é o objetivo principal na maioria dos fluxos de trabalho de sites estáticos, portanto a abordagem de pasta costuma ser a melhor escolha. + +--- + +## Exemplo Completo Funcional (Pronto para Copiar e Colar) + +A seguir está o programa inteiro em um único arquivo. Basta substituir os caminhos pelos seus e executar. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Execute com `dotnet run`. Quando o console imprimir a linha ✅, abra o arquivo markdown e você deverá ver as imagens renderizadas corretamente. + +--- + +## Conclusão + +Agora você tem uma **solução completa, pronta para produção, para converter DOCX para Markdown e extrair imagens de DOCX** usando Aspose.Words em C#. A palavra‑chave principal aparece ao longo do guia, reforçando a relevância tanto para motores de busca quanto para assistentes de IA. + +Em uma única passagem o código: + +1. Carrega um documento Word. +2. Intercepta cada imagem via `IResourceSavingCallback`. +3. Salva cada imagem em uma pasta previsível com um nome único. +4. Gera markdown que faz referência a essas imagens. + +A partir daqui você pode: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/portuguese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..d3036f6f6d --- /dev/null +++ b/words/portuguese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Converta Word para Markdown rapidamente e também aprenda como salvar + como PDF/UA em C#. Código passo a passo, dicas e tratamento de casos extremos. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: pt +og_description: Converta Word para Markdown e salve como PDF/UA com Aspose.Words. + Aprenda o porquê, o como e dicas de melhores práticas em um guia conciso. +og_title: Converter Word para Markdown – Tutorial Completo de C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Converter Word para Markdown – Guia Completo com Exportação PDF/UA +url: /pt/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter Word para Markdown – Guia Completo com Exportação PDF/UA + +Já se perguntou como **converter Word para Markdown** sem perder equações ou imagens? Você não está sozinho. Muitos desenvolvedores precisam de uma maneira confiável de transformar arquivos `.docx` em Markdown limpo, ainda podendo **salvar como PDF/UA** para PDFs compatíveis com acessibilidade. Neste tutorial, vamos percorrer uma solução completa, pronta‑para‑executar, usando Aspose.Words for .NET, explicar por que cada configuração importa e mostrar como lidar com as partes mais complicadas, como OfficeMath e formas flutuantes. + +Até o final deste guia, você terá um único programa C# que: + +1. Carrega um documento Word com recuperação relaxada (para que arquivos corrompidos não interrompam a execução). +2. Exporta para Markdown, convertendo equações em LaTeX e armazenando imagens via um callback personalizado. +3. Salva o mesmo documento como um arquivo compatível PDF/UA‑2, incorporando formas flutuantes como tags inline. + +Parece muito? Sem problemas—vamos mergulhar. + +## O que você precisará + +- **Aspose.Words for .NET** (última versão, 23.x no momento da escrita). +- Um ambiente de desenvolvimento .NET (Visual Studio 2022, Rider ou a CLI `dotnet`). +- Um arquivo Word de exemplo (`input.docx`) colocado em uma pasta que você possa referenciar. +- Familiaridade básica com a sintaxe C#—nada exótico, apenas alguns `using` statements. + +> **Dica profissional:** Se você estiver usando um gerenciador de pacotes NuGet, adicione a biblioteca com +> `dotnet add package Aspose.Words` ou via a UI NuGet do Visual Studio. + +## Etapa 1 – Carregar o Documento Word com Recuperação Relaxada + +Quando você recebe arquivos Word de fontes externas, eles podem conter pequenas corrupções. Habilitar a recuperação **Relaxed** indica ao Aspose.Words que continue em vez de lançar uma exceção. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Por que isso importa:** +- `RecoveryMode.Relaxed` impede que um único parágrafo malformado aborte toda a conversão. +- Fornecer um objeto `FontSettings` garante que fontes ausentes sejam substituídas de forma elegante, o que é crucial quando você renderiza equações como LaTeX posteriormente. + +## Etapa 2 – Exportar para Markdown (OfficeMath → LaTeX, Imagens via Callback) + +Markdown não possui uma forma nativa de representar equações do Word. Aspose.Words pode traduzir objetos **OfficeMath** para LaTeX, que a maioria dos renderizadores Markdown entende. As imagens, porém, precisam ser salvas em algum lugar; um **callback de salvamento de recursos** personalizado lhe dá controle total sobre a estrutura de pastas e a nomeação. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### O Callback de Salvamento de Recursos + +Abaixo está uma pequena implementação que armazena cada imagem em uma sub‑pasta chamada `images` e nomeia os arquivos como `img001.png`, `img002.png`, etc. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Por que você precisa disso:** +- Sem um callback, Aspose.Words cria uma pasta plana com nomes GUID aleatórios, o que bagunça o controle de versão. +- Ao controlar o esquema de nomes, você mantém o repositório Markdown organizado e reproduzível. + +### Saída Markdown Esperada + +Abra `doc.md` após a execução e você verá: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +As equações aparecem como LaTeX envolvidas em `$$ … $$`, e as imagens referenciam a pasta `images` que você acabou de criar. + +## Etapa 3 – Exportar para PDF/UA‑2 (Pronto para Acessibilidade) + +Se você precisar compartilhar o documento com usuários que dependem de leitores de tela ou outras tecnologias assistivas, a conformidade com **PDF/UA‑2** é o padrão ouro. Aspose.Words pode impor isso com uma única flag, e também pode achatar formas flutuantes em tags inline para que não sejam perdidas durante a conversão. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Por que PDF/UA importa:** +- PDF/UA (Universal Accessibility) garante que o PDF resultante contenha marcação adequada, ordem de leitura lógica e texto alternativo para imagens. +- Definir `ExportFloatingShapesAsInlineTag` assegura que formas como caixas de texto ou balões não sejam omitidas ou deslocadas—uma armadilha comum ao converter layouts complexos. + +### Verificando a Conformidade PDF/UA + +Após a exportação, abra o PDF no Adobe Acrobat Pro e execute **“Accessibility Check”** (Ferramentas → Acessibilidade → Verificação Completa). Se a ferramenta relatar **0 erros**, você teve sucesso. + +## Casos de Borda & Armadilhas Comuns + +| Situação | O que observar | Correção / Recomendação | +|----------------------------------------|--------------------------------------------------|-----------------------------------------------------------| +| O arquivo Word contém **fonts não suportadas** | As fontes podem ser substituídas, quebrando o layout das equações | Forneça um `FontSettings` personalizado com fontes de fallback. | +| Documentos grandes (> 100 MB) | Pressão de memória durante a conversão | Use `LoadOptions` com `LoadFormat.Docx` e faça streaming do arquivo. | +| Imagens são gráficos vetoriais **EMF/WMF** | Elas podem ser rasterizadas inadvertidamente | Converta-as para PNG via `ImageSaveOptions` antes de salvar. | +| PDF/UA falha na validação em **tabelas aninhadas** | A marcação pode ficar ambígua | Habilite `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` para ajudar o motor. | +| Necessidade de **preservar estilos personalizados** | Markdown tem capacidades de estilo limitadas | Exporte um arquivo CSS junto ao Markdown e faça referência a ele. | + +## Exemplo Completo (Todo o Código Junto) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Execute o programa, e você encontrará tanto `doc.md` (com equações LaTeX e links de imagem limpos) quanto `doc.pdf` (totalmente compatível PDF/UA‑2) na pasta `YOUR_DIRECTORY`. + +## Visão Geral Visual + +![exemplo de conversão de word para markdown](https://example.com/placeholder.png "exemplo de conversão de word para markdown – mostra o Word de entrada, saída Markdown e arquivo PDF/UA") + +*Texto alternativo:* **exemplo de conversão de word para markdown** – diagrama do pipeline de conversão de um arquivo Word para Markdown e PDF/UA. + +## Recapitulação & Próximos Passos + +Acabamos de **converter Word para Markdown** mantendo as equações intactas, armazenando imagens em uma pasta organizada, e produzindo um arquivo **salvar como PDF/UA** que passa nas verificações de acessibilidade. Os principais pontos são: + +- Use `LoadOptions.RecoveryMode.Relaxed` para tolerar arquivos Word imperfeitos. +- Defina `OfficeMathExportMode` como `LaTeX` para renderização limpa de equações. +- Implemente um `ResourceSavingCallback` para controlar a saída de imagens. +- Habilite `PdfCompliance.PdfUAXmpA2` e `ExportFloatingShapesAsInlineTag` para um PDF em conformidade com padrões. + +### O que explorar a seguir? + +- **CSS personalizado para Markdown** – gerar uma folha de estilos que reflita seus estilos do Word. +- **Processamento em lote** – percorrer um diretório de arquivos `.docx` para automatizar migrações em larga escala. +- **Recursos avançados de PDF/UA** – adicionar tags personalizadas, definir atributos de idioma ou incorporar descrições de áudio. +- **Integração com CI/CD** – garantir que cada build produza PDFs acessíveis automaticamente. + +Se você encontrar algum problema, verifique novamente se a sua versão do Aspose.Words corresponde à API usada aqui, e lembre‑se de que a própria documentação da biblioteca é uma referência secundária sólida. + +Feliz codificação, e que seus documentos permaneçam tanto bonitos **quanto** acessíveis! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/programming-with-txtsaveoptions/_index.md b/words/portuguese/net/programming-with-txtsaveoptions/_index.md index d9e7d6cb39..f9f748e4a7 100644 --- a/words/portuguese/net/programming-with-txtsaveoptions/_index.md +++ b/words/portuguese/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Graças a estes tutoriais, você poderá explorar ao máximo as funcionalidades | [Adicionar marcas Bidi em um documento do Word](./add-bidi-marks/) | Aprenda a adicionar marcas bidirecionais (Bidi) em documentos do Word usando o Aspose.Words para .NET com este guia. Garanta a direção correta do texto para conteúdo multilíngue. | | [Use o caractere de tabulação por nível para recuo de lista](./use-tab-character-per-level-for-list-indentation/) | Aprenda a criar listas multinível com recuo por tabulação usando o Aspose.Words para .NET. Siga este guia para obter uma formatação precisa de listas em seus documentos. | | [Use caractere de espaço por nível para recuo de lista](./use-space-character-per-level-for-list-indentation/) | Aprenda a criar listas multinível com recuo de caracteres de espaço no Aspose.Words para .NET. Guia passo a passo para formatação precisa de documentos. | - +| [Salvar docx como txt – Exportar equações do Word para LaTeX com C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Aprenda a salvar documentos DOCX como arquivos TXT e exportar equações do Word para LaTeX usando C# com Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/portuguese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..f6aa3ff31d --- /dev/null +++ b/words/portuguese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-04-05 +description: salve docx como txt com Aspose.Words – converta rapidamente Word para + txt e aprenda a exportar equações matemáticas como LaTeX. Código C# simples, sem + necessidade de ferramentas extras. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: pt +og_description: salve docx como txt em C# e veja como exportar matemática para LaTeX. + Siga este guia passo a passo para converter Word em txt com equações intactas. +og_title: salvar docx como txt – Exportar equações do Word para LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Salvar docx como txt – Exportar equações do Word para LaTeX com C# +url: /pt/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# salvar docx como txt – Exportar equações do Word para LaTeX com C# + +Já precisou **salvar docx como txt** mas temia que suas equações desaparecessem ou se transformassem em lixo ilegível? Você não está sozinho. Muitos desenvolvedores se deparam com esse problema ao tentar **converter word para txt** para processamento posterior, especialmente quando o arquivo fonte contém objetos Office Math. + +A boa notícia? Com algumas linhas de C# e as opções corretas, você pode não apenas **converter Word para txt**, mas também manter cada equação como marcação LaTeX limpa. Neste tutorial vamos percorrer todo o processo, explicar por que cada configuração importa e mostrar como verificar o resultado. + +Vamos cobrir: + +* Instalar a biblioteca Aspose.Words for .NET +* Carregar um `.docx` que contém equações matemáticas +* Configurar `TxtSaveOptions` para que **how to export math** se torne uma string compatível com LaTeX +* Salvar o arquivo e conferir a saída + +Ao final, você terá um trecho reutilizável que permite **salvar docx como txt** preservando cada fórmula como LaTeX — perfeito para pipelines científicos, geradores de sites estáticos ou qualquer fluxo de trabalho que precise de matemática em texto puro. + +--- + +## Pré-requisitos + +Antes de mergulharmos, certifique‑se de que você tem: + +* .NET 6.0 ou superior (o código também funciona com .NET Framework 4.6+) +* Visual Studio 2022 (ou qualquer IDE de sua preferência) +* O pacote NuGet **Aspose.Words for .NET** – instale‑o com + +```bash +dotnet add package Aspose.Words +``` + +Nenhum conversor adicional ou ferramenta externa é necessário; o Aspose.Words cuida do trabalho pesado internamente. + +--- + +## Etapa 1: Instalar e referenciar Aspose.Words + +Primeiro, adicione a biblioteca ao seu projeto. Se estiver usando a linha de comando, execute o comando acima. No Visual Studio você também pode clicar com o botão direito em **Dependencies → Manage NuGet Packages** e procurar por *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Dica profissional:** Use a versão estável mais recente (em abril 2026 é a 24.10). Lançamentos mais novos trazem correções de bugs para o tratamento de OfficeMath, evitando símbolos ausentes inesperados. + +--- + +## Etapa 2: Carregar o documento fonte + +Agora carregamos o `.docx` que contém as equações que você deseja manter. A classe `Document` abstrai todo o arquivo Word, dando acesso a texto, imagens e objetos Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Por que carregá‑lo primeiro? O Aspose.Words analisa o arquivo em um modelo de objetos, permitindo inspecionar ou modificar o conteúdo antes de decidir como exportá‑lo. É aqui que as decisões de **how to export math** começam a importar. + +--- + +## Etapa 3: Configurar TxtSaveOptions para exportação LaTeX + +O coração da solução é a classe `TxtSaveOptions`. Por padrão, salvar em TXT remove completamente o Office Math. Definir `OfficeMathExportMode` como `LaTeX` instrui a biblioteca a traduzir cada equação para sua representação LaTeX. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Por que LaTeX?** LaTeX é a lingua franca da publicação científica. Exportando a matemática dessa forma, você preserva a semântica da equação em vez de uma imagem plana ou uma cadeia de caracteres corrompida. Se mais tarde você inserir o TXT em um processador Markdown que suporte MathJax, as equações serão renderizadas perfeitamente. + +--- + +## Etapa 4: Salvar o documento como texto puro + +Com as opções configuradas, o passo final é uma única linha que grava o arquivo no disco. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +É isso — seu `.docx` agora é um arquivo `.txt` onde cada equação aparece como um trecho LaTeX, pronto para consumo posterior. + +--- + +## Verificando a saída (Como salvar txt corretamente) + +Abra `MathSample.txt` em qualquer editor de texto. Você deverá ver algo como: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Se encontrar caracteres específicos do Word (por exemplo, `?` ou símbolos ausentes), verifique: + +* Você está usando uma versão recente do Aspose.Words (versões antigas tinham bugs com OfficeMath). +* O documento fonte realmente contém objetos **OfficeMath** — não objetos legados do Equation Editor. Para estes últimos, pode ser necessário convertê‑los manualmente ou usar o método `ConvertMathToOfficeMath` antes de salvar. + +--- + +## Variações comuns e casos de borda + +| Situação | O que fazer | +|-----------|------------| +| **Objetos do Editor de Equações Legado** | Chame `doc.ConvertMathToOfficeMath()` antes da etapa 3. | +| **Você precisa de matemática Unicode simples, não LaTeX** | Defina `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Documentos grandes (100 + MB)** | Transmita a operação de salvamento usando `doc.Save(Stream, txtOptions)` para evitar alto uso de memória. | +| **Você quer manter o nome original do arquivo** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` ao construir o caminho de saída. | + +Esses ajustes respondem à pergunta “**how to export math**” para diferentes pipelines, garantindo que sua solução seja robusta independentemente da origem. + +--- + +## Exemplo completo em funcionamento (Todas as etapas em um só lugar) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Execute o programa, abra o `.txt` gerado e você verá as equações LaTeX incorporadas exatamente onde deveriam estar. Esta é a maneira mais direta de **converter + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/portuguese/net/working-with-fonts/_index.md b/words/portuguese/net/working-with-fonts/_index.md index 36022e3fdb..3e45c78d25 100644 --- a/words/portuguese/net/working-with-fonts/_index.md +++ b/words/portuguese/net/working-with-fonts/_index.md @@ -27,7 +27,7 @@ Quer você queira formatar texto com fontes diferentes, definir regras de substi | --- | --- | | [Formatação de fonte](./font-formatting/) | Aprenda a formatar fontes em documentos do Word usando o Aspose.Words para .NET com um guia detalhado passo a passo. | | [Obter espaçamento entre linhas de fonte](./get-font-line-spacing/) | Aprenda como obter espaçamento entre linhas de fonte usando o Aspose.Words para .NET com este tutorial passo a passo. Perfeito para desenvolvedores. | -| [Verifique o efeito de texto do DrawingML](./check-drawingml-text-effect/) Aprenda a verificar os efeitos de texto do DrawingML em documentos do Word usando o Aspose.Words para .NET com nosso guia passo a passo detalhado. Aprimore seus documentos com facilidade. | +| [Verifique o efeito de texto do DrawingML](./check-drawingml-text-effect/) Aprenda a verificar os efeitos texto do DrawingML em documentos do Word usando o Aspose.Words para .NET com nosso guia passo a passo detalhado. Aprimore seus documentos com facilidade. | | [Definir formatação de fonte](./set-font-formatting/) | Aprenda a definir a formatação de fontes em documentos do Word usando o Aspose.Words para .NET. Siga nosso guia passo a passo detalhado para aprimorar a automação de seus documentos. | | [Definir marca de ênfase da fonte](./set-font-emphasis-mark/) | Aprenda a definir marcas de ênfase de fonte em documentos do Word usando o Aspose.Words para .NET com este guia passo a passo detalhado. Perfeito para desenvolvedores .NET. | | [Definir pastas de fontes](./set-fonts-folders/) | Aprenda a definir pastas de fontes personalizadas no Aspose.Words para .NET com este guia passo a passo abrangente. Perfeito para desenvolvedores que buscam aprimorar fontes em documentos. | @@ -40,7 +40,7 @@ Quer você queira formatar texto com fontes diferentes, definir regras de substi | [Definir pastas de fontes com prioridade](./set-fonts-folders-with-priority/) | Aprenda a definir pastas de fontes com prioridade em documentos do Word usando o Aspose.Words para .NET. Nosso guia garante que seus documentos sejam renderizados perfeitamente sempre. | | [Definir pasta de fontes True Type](./set-true-type-fonts-folder/) | Aprenda a definir uma pasta de fontes True Type em documentos do Word usando o Aspose.Words para .NET. Siga nosso guia passo a passo detalhado para garantir um gerenciamento consistente de fontes. | | [Especificar fonte padrão ao renderizar](./specify-default-font-when-rendering/) | Aprenda a especificar uma fonte padrão ao renderizar documentos do Word usando o Aspose.Words para .NET. Garanta a consistência da aparência do documento em todas as plataformas. | -| [Configurações de fonte com opções de carregamento](./font-settings-with-load-options/) Aprenda a gerenciar as configurações de fonte com opções de carregamento no Aspose.Words para .NET. Guia passo a passo para desenvolvedores garantirem a consistência da aparência da fonte em documentos do Word. +| [Configurações de fonte com opções de carregamento](./font-settings-with-load-options/) Aprenda a gerenciar as configurações de fonte com opções de carregamento no Aspose.Words para .NET. Guia passo a passo para desenvolvedores garantirem a consistência da aparência da fonte em documentos do Word. | | [Definir pasta de fontes](./set-fonts-folder/) | Aprenda como definir uma pasta de fontes personalizada no Aspose.Words para .NET para garantir que seus documentos do Word sejam renderizados corretamente, sem fontes ausentes. | | [Configurações de fonte Instância padrão](./font-settings-default-instance/) | Neste tutorial, aprenda a configurar as configurações de fonte padrão em um documento do Word com o Aspose.Words para .NET. | | [Obtenha a lista de fontes disponíveis](./get-list-of-available-fonts/) | Descubra como obter uma lista de fontes disponíveis usando o Aspose.Words para .NET neste tutorial passo a passo detalhado. Aprimore suas habilidades de gerenciamento de fontes. | @@ -48,7 +48,7 @@ Quer você queira formatar texto com fontes diferentes, definir regras de substi | [Receber notificação de aviso](./receive-warning-notification/) Aprenda como receber uma notificação de aviso ao usar o Aspose.Words para .NET e gerencie quaisquer problemas ou avisos em seus documentos. | | [Exemplo de fonte de fonte do Resource Steam](./resource-steam-font-source-example/) | Aprenda a usar o Resource Stream Font Source para carregar fontes personalizadas no Aspose.Words para .NET. | | [Obtenha substituição sem sufixos](./get-substitution-without-suffixes/) | Neste tutorial, aprenda como obter substituições sem sufixo em um documento do Word com o Aspose.Words para .NET. | - +| [Substituição de Fonte Aspose – Detectar Fontes Ausentes em Documentos Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Aprenda a detectar fontes ausentes em documentos Word usando Aspose.Words para .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/portuguese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/portuguese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..d01783a1ff --- /dev/null +++ b/words/portuguese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Guia de substituição de fontes da Aspose para detectar fontes ausentes + ao carregar um documento Word. Aprenda a configurar as configurações de fontes e + lidar com fontes ausentes de forma eficiente. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: pt +og_description: Guia de substituição de fontes da Aspose para detectar fontes ausentes + ao carregar um documento Word. Aprenda a configurar as definições de fonte e lidar + com fontes ausentes de forma eficiente. +og_title: Substituição de Fontes Aspose – Detectar Fontes Ausentes em Documentos Word +tags: +- Aspose.Words +- C# +- Font Management +title: Substituição de Fonte Aspose – Detectar Fontes Ausentes em Documentos Word +url: /pt/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Substituição de Fonte Aspose – Detectar Fontes Ausentes em Documentos Word + +Já se deparou com um arquivo Word que parece perfeito em uma máquina, mas apresenta alterações estranhas de fonte em outra? Esse é o clássico problema de **aspose font substitution**, e geralmente significa que algumas fontes estão ausentes no sistema de destino. Neste tutorial, mostraremos, passo a passo, como **detectar fontes ausentes** ao **carregar um documento Word**, como **configurar as definições de fonte**, e o que fazer para **tratar fontes ausentes** de forma elegante. + +Vamos percorrer um exemplo completo e executável em C#, explicar por que cada linha importa e até mostrar a saída do console que você deve esperar. Ao final, você será capaz de identificar substituições de fonte no instante em que um documento é carregado — sem adivinhações. + +## O que Você Vai Aprender + +- Como habilitar o coletor diagnóstico do Aspose.Words para avisos de fonte. +- O código exato necessário para **carregar um documento Word** com **definições de fonte** personalizadas. +- Como iterar sobre objetos `WarningInfo` para listar cada fonte substituída. +- Dicas para suprimir avisos indesejados ou fornecer fontes alternativas. +- Um exemplo pronto‑para‑executar que você pode copiar‑colar no Visual Studio. + +### Pré‑requisitos + +- .NET 6.0 ou superior (a API funciona da mesma forma no .NET Framework). +- Aspose.Words for .NET (pacote NuGet `Aspose.Words`). +- Um arquivo Word que faça referência a uma fonte que você não tenha instalada (por exemplo, `MissingFont.docx`). + +Se você tem tudo isso, vamos mergulhar. + +## Etapa 1 – Habilitar o Coletor Diagnóstico (Configurar Definições de Fonte) + +Primeiro de tudo: o Aspose.Words só registra avisos de substituição de fonte se você o instruir a fazê‑lo. Isso é feito criando um objeto `FontSettings` e atribuindo‑o a uma instância de `LoadOptions`. Pense nisso como ligar as “luzes de depuração” para o tratamento de fontes. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Por quê?** +Sem um objeto `FontSettings` o coletor de avisos permanece silencioso, e você nunca saberá quais fontes foram trocadas. Ao inicializá‑lo vazio, deixamos o Aspose usar as fontes padrão do sistema *e* acompanhar quaisquer substituições. + +> **Dica profissional:** Se você souber que uma pasta específica contém fontes corporativas, aponte `FontSettings` para ela com `SetFontsFolder("caminho")`. Isso pode reduzir o número de avisos de fontes ausentes. + +## Etapa 2 – Carregar o Documento com as Opções Configuradas (Carregar Documento Word) + +Agora que o coletor está ativo, carregue seu arquivo `.docx` usando o mesmo `LoadOptions`. Este é o momento em que o Aspose analisa o documento, procura cada referência de fonte e decide se uma substituição é necessária. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Por que isso importa?** +Se você simplesmente chamar `new Document("MissingFont.docx")`, as configurações padrão seriam aplicadas *e* a lista de avisos ficaria vazia. Passar `loadOptions` garante que o coletor diagnóstico esteja conectado ao pipeline de carregamento. + +## Etapa 3 – Recuperar e Exibir Avisos de Substituição de Fonte (Detectar Fontes Ausentes) + +Depois que o documento estiver na memória, o Aspose armazena quaisquer avisos em `document.WarningCallback.Warnings`. Percorra essa coleção, filtre por `WarningType.FontSubstitution` e imprima a descrição. Cada descrição informa qual fonte estava ausente e qual foi usada em seu lugar. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Saída esperada no console** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Essa saída indica exatamente quais fontes estão ausentes na máquina que executa o código. Agora você pode decidir se instala as fontes faltantes, as incorpora ao documento ou mantém a substituição. + +![Saída do console mostrando avisos de substituição de fonte Aspose](/images/aspose-font-substitution-console.png) + +*Texto alternativo da imagem:* substituição de fonte Aspose – saída do console listando fontes substituídas + +## Etapa 4 – Opcional: Personalizar o Comportamento de Substituição (Tratar Fontes Ausentes) + +Às vezes você não quer apenas saber *que* uma substituição ocorreu — você quer controlar *como* ela acontece. O Aspose.Words permite registrar uma regra personalizada `IFontSubstitutionRule`. A seguir, um exemplo rápido que força qualquer fonte ausente a recair em `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Quando usar isso?** +Se você gera PDFs para um serviço web e sabe que todos os clientes conseguem renderizar `Tahoma`, forçar o fallback garante consistência visual sem precisar distribuir dezenas de arquivos de fonte. + +## Exemplo Completo em Funcionamento (Todas as Etapas Combinadas) + +Aqui está o programa inteiro que você pode colar em um novo projeto de console. Ele compila como‑está, assumindo que o pacote NuGet Aspose.Words foi instalado. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Execute o programa, observe o console e você verá cada evento de fonte ausente impresso. A partir daí, pode decidir se instala as fontes faltantes, as incorpora ou mantém o fallback. + +## Perguntas Frequentes + +**P: Isso funciona com conversão para PDF?** +Sim. Quando você posteriormente chamar `doc.Save("output.pdf")`, quaisquer fontes que foram substituídas durante o carregamento serão as que serão incorporadas ao PDF. Portanto, capturar os avisos antecipadamente ajuda a evitar mudanças inesperadas de fonte no PDF final. + +**P: E se eu tiver muitos documentos para processar?** +Envolva a lógica de carregamento em um bloco try‑catch e reutilize uma única instância de `FontSettings` entre os documentos. Isso reduz a sobrecarga e mantém o coletor de avisos ativo para cada arquivo. + +**P: Posso suprimir os avisos completamente?** +Você pode definir `loadOptions.WarningCallback = null;` antes de carregar, mas perderá a capacidade de **detectar fontes ausentes** — o que geralmente não é o que se deseja. + +## Conclusão + +Cobrimos tudo o que você precisa para dominar a **aspose font substitution**: habilitar o coletor diagnóstico, carregar um arquivo Word com **definições de fonte** personalizadas, extrair a lista de fontes ausentes e até substituir a regra padrão de substituição para **tratar fontes ausentes** da sua maneira. Com apenas algumas linhas de C# você obtém total visibilidade sobre problemas de fonte que, de outra forma, ficariam ocultos por sutis alterações de layout. + +Próximos passos? Experimente incorporar as fontes originais ao documento com `FontSettings.SetFontsFolder` ou explore `FontSourceBase` para carregar fontes a partir de um banco de dados. Você também pode brincar com a coleção `Document.BuiltInStyle` para ver como alterações de fonte em nível de estilo se propagam. + +Tem mais perguntas sobre Aspose.Words ou gerenciamento de fontes? Deixe um comentário, explore a documentação oficial da Aspose ou inicie um novo projeto e experimente o código acima. Boa codificação, e que seus documentos sempre sejam renderizados exatamente como pretendido! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/basic-conversions/_index.md b/words/russian/net/basic-conversions/_index.md index 43375dc72d..8ebebb92b6 100644 --- a/words/russian/net/basic-conversions/_index.md +++ b/words/russian/net/basic-conversions/_index.md @@ -35,6 +35,7 @@ Basic Conversions проведет вас через базовые преобр | [Как экспортировать LaTeX из Word – пошаговое руководство](./how-to-export-latex-from-word-step-by-step-guide/) | Узнайте, как экспортировать документ Word в LaTeX с помощью Aspose.Words для .NET, следуя пошаговому руководству. | | [Конвертировать Word в PDF в C# с Aspose.Words – Руководство](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Узнайте, как конвертировать Word в PDF в C# с помощью Aspose.Words. Пошаговое руководство для разработчиков. | | [Сохранить Word как PDF с Aspose.Words – Полное руководство C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Узнайте, как сохранить документ Word в PDF с помощью Aspose.Words в C#. Подробное руководство с примерами кода. | +| [Конвертировать Word в PDF на C# – Полное руководство с Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Подробное руководство по конвертации документов Word в PDF с использованием Aspose.Words в C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/russian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..c52bba9226 --- /dev/null +++ b/words/russian/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,195 @@ +--- +category: general +date: 2026-04-05 +description: Конвертировать Word в PDF в C# с помощью Aspose.Words. Узнайте, как сохранить + docx как PDF, экспортировать доступный PDF и эффективно загружать документ Word. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: ru +og_description: Конвертировать Word в PDF на C# с пошаговым руководством. Узнайте, + как сохранить docx как PDF, экспортировать доступный PDF и загрузить документ Word + с помощью Aspose.Words. +og_title: Конвертировать Word в PDF на C# – Полный учебник по Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Конвертация Word в PDF на C# – полное руководство с Aspose.Words +url: /ru/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Конвертация Word в PDF на C# – Полный программный учебник + +Ever wondered how to **convert word to pdf** without wrestling with fiddly command‑line tools or third‑party services? You're not the only one. Many developers hit that wall when a client asks for an accessible PDF straight from a DOCX file. The good news? With a few lines of C# and the powerful Aspose.Words library, you can turn a Word document into a standards‑compliant PDF in a snap. + +В этом руководстве мы пройдем всё, что вам нужно знать: от основ **load word document**, через настройку правильных параметров до **how to export accessible pdf**, и, наконец, сохранения результата, чтобы вы могли надёжно **save docx as pdf**. К концу у вас будет готовый к запуску фрагмент кода, который можно вставить в любой проект .NET. + +> **Pro tip:** Если вы нацелены на соответствие PDF/UA‑2 (стандарт доступности, требуемый многими государственными учреждениями), тот же код работает без дополнительных шагов — просто установите правильный флаг `PdfCompliance`. + +## Что вы узнаете + +- Как **load word document** с использованием Aspose.Words в C#. +- Точные настройки, необходимые для **how to export accessible pdf** (PDF/UA‑2). +- Полный, исполняемый пример, который **save docx as pdf** одним вызовом метода. +- Распространённые подводные камни при **c# convert docx pdf** и как их избежать. +- Быстрые способы проверить, что сгенерированный PDF соответствует требованиям доступности. + +Без внешних инструментов, без непонятных файлов конфигурации — только чистый код C#, который вы можете скомпилировать уже сегодня. + +## Требования + +Прежде чем мы погрузимся, убедитесь, что у вас есть: + +1. **.NET 6.0** (или любую более новую версию .NET), установленную. Более старые фреймворки тоже работают, но синтаксис ниже предполагает современный SDK. +2. **license** для Aspose.Words for .NET. Библиотека предлагает бесплатную пробную версию, но для продакшна понадобится действительный ключ. +3. **Aspose.Words** NuGet‑пакет, добавленный в ваш проект: + +```bash +dotnet add package Aspose.Words +``` + +Вот и всё — без дополнительных бинарных файлов, без COM‑interop, только чистая ссылка на NuGet. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## Пошаговая реализация + +Ниже мы разбиваем процесс на логические части. Каждый шаг содержит небольшой фрагмент кода, объяснение **why** его важности и совет, полученный из реального опыта. + +### ## Конвертация Word в PDF – Загрузка исходного документа + +Первое, что вам нужно сделать, — **load word document** в память. Aspose.Words абстрагирует парсинг OpenXML, поэтому вы можете работать с файлами DOCX, DOC или даже RTF, не беспокоясь о нюансах формата. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +Загрузка файла создаёт объект `Document`, представляющий весь файл Word, включая заголовки, колонтитулы, стили и скрытые метаданные. Если пропустить этот шаг или попытаться прочитать файл как обычный поток, вы потеряете информацию о макете, которая позже определяет, как будет выглядеть PDF. + +> **Side note:** Тот же конструктор `Document` работает для `.doc` и `.rtf`. Это значит, что вы можете **c# convert docx pdf** даже если источник не является строго DOCX. + +### ## Сохранить DOCX как PDF – Настройка соответствия PDF/UA‑2 + +Теперь, когда документ находится в памяти, мы указываем Aspose.Words, как должен быть сгенерирован PDF. Для большинства сценариев настройки по умолчанию подходят, но когда нужен **accessible PDF**, необходимо включить флаг соответствия PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +`PdfCompliance.PdfUAXmpA2` указывает библиотеке встраивать необходимые теги и структуры, которые используют скрин‑ридеры. Без этого флага вы можете получить визуально идеальный PDF, который не пройдет проверку доступности. + +> **Tip:** Если вам нужен только обычный PDF, вы можете убрать строку `Compliance`. Остальные параметры всё равно обеспечат вывод высокого качества. + +### ## Конвертация Word в PDF – Запись файла + +С готовыми параметрами последний шаг — **save docx as pdf**. Этот один вызов выполняет всю тяжелую работу: преобразование макета, встраивание шрифтов и добавление тегов доступности. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- PDF‑файл по пути `outputPath`, который точно воспроизводит макет Word. +- Если вы использовали флаг `PdfUAXmpA2`, PDF будет помечен как соответствующий PDF/UA‑2. +- Все шрифты встраиваются, поэтому файл выглядит одинаково на любом компьютере. + +### ## Проверка доступного PDF (необязательно, но рекомендуется) + +После конвертации рекомендуется дважды проверить, что PDF действительно **how to export accessible pdf** правильно. Вы можете использовать бесплатные инструменты, такие как «Проверка доступности» в Adobe Acrobat Reader или открытый валидатор `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Если валидатор не сообщает об ошибках, вы успешно **convert word to pdf** с полной поддержкой доступности. + +### ## Распространённые подводные камни при C# конвертации DOCX в PDF + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| Missing fonts | В исходном DOCX используется пользовательский шрифт, не установленный на сервере. | Установите `EmbedFullFonts = true` или установите шрифт на машину. | +| Large file size | Изображения встраиваются в полном разрешении. | Используйте `ImageCompression = PdfImageCompression.Jpeg` и задайте более низкое значение `JpegQuality`. | +| Broken hyperlinks | Ссылки указывают на относительные пути, которые не существуют у клиента. | Убедитесь, что URL‑адреса абсолютные, либо скорректируйте свойство `HyperlinkTarget`. | +| Accessibility tags missing | Флаг `Compliance` не установлен. | Добавьте `Compliance = PdfCompliance.PdfUAXmpA2`, как показано выше. | + +Учитывая эти моменты, ваш процесс **c# convert docx pdf** станет надёжным и готовым к продакшну. + +## Полный рабочий пример + +Объединив всё вместе, представляем автономное консольное приложение, которое вы можете сразу скомпилировать и запустить. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** После запуска программы вы найдете `output.pdf` в `C:\Docs`. Откройте его в любом PDF‑просмотрщике; макет должен точно соответствовать `input.docx`, а проверка доступности подтвердит соответствие PDF/UA‑2. + +## Заключение + +Мы только что прошли полный сквозной процесс решения, как **convert word to pdf** с помощью C# и Aspose.Words. С помощью **load word document**, настройки правильных `PdfSaveOptions` и, наконец, **save docx as pdf**, вы получаете высококачественный доступный PDF с минимальным количеством кода. Независимо от того, создаёте ли вы микросервис генерации документов, локальный пакетный конвертер, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-markdownsaveoptions/_index.md b/words/russian/net/programming-with-markdownsaveoptions/_index.md index 4be0115f6d..7f910f24b2 100644 --- a/words/russian/net/programming-with-markdownsaveoptions/_index.md +++ b/words/russian/net/programming-with-markdownsaveoptions/_index.md @@ -29,9 +29,11 @@ | [Конвертировать docx в markdown – пошаговое руководство C#](./convert-docx-to-markdown-step-by-step-c-guide/) | Подробное пошаговое руководство по конвертации файлов DOCX в Markdown с использованием C# и Aspose.Words. | | [Сохранить docx как markdown – Полное руководство C# с уравнениями LaTeX](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | Полное руководство по конвертации DOCX в Markdown с поддержкой уравнений LaTeX на C#. | | [Сохранить docx как markdown – Полное руководство C# с извлечением изображений](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Полное руководство по сохранению DOCX в Markdown с извлечением изображений на C# с использованием Aspose.Words. | +| [Конвертировать DOCX в Markdown – извлечение изображений из DOCX с Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Конвертируйте DOCX в Markdown, извлекая изображения, используя Aspose.Words для .NET. | | [Как экспортировать Markdown из Word – Полное руководство C#](./how-to-export-markdown-from-word-complete-c-guide/) | Полное руководство по экспорту Markdown из Word с использованием C# и Aspose.Words. | | [Как сохранить Markdown из DOCX – пошаговое руководство](./how-to-save-markdown-from-docx-step-by-step-guide/) | Подробное руководство по сохранению документа DOCX в формате Markdown с пошаговыми инструкциями на C#. | | [Как экспортировать Markdown из DOCX – Полное руководство](./how-to-export-markdown-from-docx-complete-guide/) | Полное руководство по экспорту Markdown из DOCX с использованием Aspose.Words для .NET. | +| [Конвертировать Word в Markdown – Полное руководство с экспортом PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Полное руководство по конвертации Word в Markdown с последующим экспортом в PDF/UA, используя Aspose.Words для .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/russian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..0b08764117 --- /dev/null +++ b/words/russian/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Узнайте, как конвертировать DOCX в Markdown и извлекать изображения из + DOCX на C#. Пошаговое руководство с полным кодом и советами. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: ru +og_description: Конвертировать DOCX в Markdown и извлекать изображения из DOCX с помощью + Aspose.Words. Полный учебник по C# с кодом, объяснением и советами по лучшим практикам. +og_title: Преобразовать DOCX в Markdown – извлекать изображения из DOCX на C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Конвертировать DOCX в Markdown – извлекать изображения из DOCX с помощью Aspose.Words +url: /ru/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Конвертировать DOCX в Markdown – извлекать изображения из DOCX в C# + +Когда‑нибудь вам нужно было **конвертировать DOCX в Markdown**, но изображения исчезали в результате? Вы не одиноки. Во многих проектах версия в markdown идеальна для систем контроля версий или генераторов статических сайтов, однако картинки остаются позади, превращая богатый документ в пустой текстовый файл. + +Хорошая новость? С несколькими строками C# и Aspose.Words вы можете **конвертировать DOCX в Markdown** *и* **извлекать изображения из DOCX** автоматически. Это руководство проведёт вас через весь процесс, объяснит, почему каждый шаг важен, и даже покажет, как поддерживать порядок в папке с изображениями. + +## Что вы узнаете + +- Как загрузить DOCX, содержащий изображения. +- Как определить пользовательский `IResourceSavingCallback`, который решает, куда сохранять каждое изображение. +- Как настроить `MarkdownSaveOptions`, чтобы сгенерированный markdown корректно ссылался на извлечённые изображения. +- Советы по обработке крайних случаев, таких как дублирующиеся имена изображений или форматы, отличные от PNG. +- Полный готовый к копированию и вставке пример кода, который вы можете запустить сегодня. + +### Предварительные требования + +- .NET 6.0 или новее (API работает на .NET Core, .NET Framework и .NET 5+). +- Лицензия на **Aspose.Words for .NET** (бесплатная пробная версия подходит для тестирования). +- Базовые знания C# и Visual Studio (или вашей любимой IDE). + +Если всё это у вас есть, давайте приступим. + +--- + +## Шаг 1: Настройте проект и установите Aspose.Words + +Сначала создайте новое консольное приложение (или интегрируйте в существующее решение). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Совет:** Используйте последнюю версию NuGet (по состоянию на апрель 2026 это 24.12), чтобы получить новейшие улучшения экспорта markdown. + +--- + +## Шаг 2: Создайте обратный вызов для сохранения изображений туда, где вам нужно + +Aspose.Words позволяет перехватывать каждый ресурс (изображения, SVG и т.д.), который записывается во время экспорта в markdown. Реализуя `IResourceSavingCallback`, вы можете: + +1. Выбрать папку, расположенную рядом с вашим markdown‑файлом. +2. Сгенерировать уникальное имя файла (чтобы никогда не перезаписать существующее изображение). +3. Определить формат (здесь мы принудительно используем PNG для согласованности). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Почему имя основано на GUID? + +Если исходный DOCX содержит два изображения с одинаковым оригинальным именем, простое копирование перезапишет одно из них. Использование `Guid.NewGuid()` гарантирует уникальность, что особенно удобно, когда вы запускаете конвертацию многократно в автоматизированном конвейере. + +--- + +## Шаг 3: Загрузите DOCX и настройте параметры Markdown + +Теперь мы загружаем документ в память и привязываем созданный обратный вызов. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Что делает код, шаг за шагом + +| Шаг | Назначение | +|------|------------| +| **Define paths** | Делает проект гибким; вы можете указывать любую папку без перекомпиляции. | +| **Load the DOCX** | `Document` разбирает Word‑файл, делая доступными все элементы (абзацы, таблицы, изображения). | +| **Configure `MarkdownSaveOptions`** | `ResourceSavingCallback` — это точка, где извлекаются изображения. Без неё Aspose.Words будет встраивать изображения как строки base64 или полностью их опускать, в зависимости от настроек. | +| **Save** | `doc.Save` записывает markdown‑файл и вызывает обратный вызов для каждого изображения. | + +--- + +## Шаг 4: Проверьте результат – что вы должны увидеть? + +После выполнения программы откройте `DocWithImages.md`. Вы увидите ссылки на изображения markdown, выглядящие так: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +А в `C:\Docs\MarkdownResources` вы найдёте серию PNG‑файлов с именами‑GUID. Откройте любой из них — они должны быть идентичны картинкам, встроенным в оригинальный DOCX. + +Если открыть markdown‑файл в просмотрщике, который учитывает относительные пути (например, предварительный просмотр VS Code, GitHub или генератор статических сайтов), изображения отобразятся так же, как в Word. + +### Распространённые ошибки и как их избежать + +| Признак | Возможная причина | Решение | +|---------|-------------------|---------| +| Изображения отображаются как битые ссылки | `ResourceFileName` не был установлен, поэтому markdown указывает на несуществующий файл. | Убедитесь, что внутри обратного вызова есть `args.ResourceFileName = newFileName;`. | +| PNG‑файлы слишком большие | Исходные изображения были JPEG или BMP; конвертация в PNG может увеличить размер. | Определите оригинальный формат через `args.ResourceContentType` и сохраняйте его: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";`. | +| Дублирующиеся изображения всё ещё появляются | Вы использовали статическое имя файла вместо GUID. | Вернитесь к логике GUID или добавьте счётчик для каждого типа изображения. | +| При конвертации возникает `FileNotFoundException` | Неправильный путь к исходному DOCX или папка без прав чтения. | Проверьте путь и предоставьте необходимые права доступа к файловой системе. | + +--- + +## Шаг 5: Расширенные настройки (по желанию) + +### 5.1 Сохранить оригинальные форматы изображений + +Если вы хотите, чтобы выходные изображения сохраняли свои оригинальные расширения, измените обратный вызов: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Встраивание изображений как Base64 (когда вы *не* хотите отдельные файлы) + +Иногда удобнее иметь один markdown‑файл (например, для отправки по электронной почте). Измените параметр: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Но помните: **извлекать изображения из DOCX** — главная цель большинства рабочих процессов со статическими сайтами, поэтому подход с отдельной папкой обычно предпочтительнее. + +--- + +## Полный рабочий пример (готов к копированию и вставке) + +Ниже представлен весь код в одном файле. Просто замените пути на свои и запустите. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Запустите его командой `dotnet run`. Когда консоль выведет строку с ✅, откройте markdown‑файл — изображения должны отобразиться корректно. + +--- + +## Заключение + +Теперь у вас есть **полное, готовое к использованию решение для конвертации DOCX в Markdown и извлечения изображений из DOCX** с помощью Aspose.Words в C#. Основное ключевое слово присутствует по всему руководству, усиливая релевантность как для поисковых систем, так и для AI‑ассистентов. + +За один проход код: + +1. Загружает Word‑документ. +2. Перехватывает каждое изображение через `IResourceSavingCallback`. +3. Сохраняет каждое изображение в предсказуемую папку с уникальным именем. +4. Генерирует markdown, который ссылается на эти изображения. + +Отсюда вы можете: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/russian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..09c495c6eb --- /dev/null +++ b/words/russian/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Быстро преобразуйте Word в Markdown и также узнайте, как сохранять в + PDF/UA на C#. Пошаговый код, советы и обработка крайних случаев. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: ru +og_description: Преобразуйте Word в Markdown и сохраните как PDF/UA с помощью Aspose.Words. + Узнайте, почему это делается, как это сделать, а также лучшие практические советы + в одном лаконичном руководстве. +og_title: Конвертировать Word в Markdown – Полный учебник по C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Преобразование Word в Markdown – Полное руководство с экспортом PDF/UA +url: /ru/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Конвертация Word в Markdown – Полное руководство с экспортом PDF/UA + +Задумывались ли вы когда‑нибудь, как **конвертировать Word в Markdown** без потери уравнений или изображений? Вы не одиноки. Многие разработчики нуждаются в надёжном способе превратить файлы `.docx` в чистый Markdown, при этом сохраняя возможность **сохранить как PDF/UA** для PDF‑документов, соответствующих требованиям доступности. В этом руководстве мы пройдём через полностью готовое к запуску решение с использованием Aspose.Words for .NET, объясним, почему важна каждая настройка, и покажем, как справиться с более сложными частями, такими как OfficeMath и плавающие фигуры. + +К концу этого руководства у вас будет одна программа на C#, которая: +1. Загружает документ Word с включённым режимом relaxed recovery (чтобы повреждённые файлы не прерывали выполнение). +2. Экспортирует его в Markdown, преобразуя уравнения в LaTeX и сохраняет изображения с помощью пользовательского callback. +3. Сохраняет тот же документ как файл, соответствующий PDF/UA‑2, внедряя плавающие фигуры как встроенные теги. + +Звучит сложно? Не переживайте — давайте начнём. + +## Что понадобится + +- **Aspose.Words for .NET** (последняя версия, 23.x на момент написания). +- Среда разработки .NET (Visual Studio 2022, Rider или `dotnet` CLI). +- Пример файла Word (`input.docx`), размещённый в папке, к которой вы можете обратиться. +- Базовое знакомство с синтаксисом C# — ничего экзотического, лишь несколько операторов `using`. + +> **Pro tip:** Если вы используете менеджер пакетов NuGet, добавьте библиотеку с помощью +> `dotnet add package Aspose.Words` или через интерфейс NuGet в Visual Studio. + +## Шаг 1 — Загрузка документа Word с режимом Relaxed Recovery + +Когда вы получаете файлы Word из внешних источников, они могут содержать небольшие повреждения. Включение восстановления **Relaxed** заставляет Aspose.Words продолжать работу вместо выбрасывания исключения. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Почему это важно:** +- `RecoveryMode.Relaxed` предотвращает прерывание всей конвертации из‑за одного некорректного абзаца. +- Предоставление объекта `FontSettings` гарантирует, что любые отсутствующие шрифты будут заменены корректно, что важно при последующей отрисовке уравнений в LaTeX. + +## Шаг 2 — Экспорт в Markdown (OfficeMath → LaTeX, изображения через Callback) + +Markdown не имеет встроенного способа представления уравнений Word. Aspose.Words может преобразовать объекты **OfficeMath** в LaTeX, который понимают большинство рендереров Markdown. Однако изображения необходимо где‑то сохранять; пользовательский **resource‑saving callback** даёт полный контроль над структурой папок и именованием. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback сохранения ресурсов + +Ниже представлена небольшая реализация, которая сохраняет каждое изображение в подпапку `images` и именует файлы как `img001.png`, `img002.png` и т.д. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Зачем это нужно:** +- Без callback Aspose.Words создаёт одну папку с случайными именами GUID, что усложняет работу с системой контроля версий. +- Контролируя схему именования, вы поддерживаете порядок и воспроизводимость репозитория Markdown. + +### Ожидаемый вывод Markdown + +Откройте `doc.md` после выполнения, и вы увидите: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Уравнения отображаются в виде LaTeX, обёрнутого в `$$ … $$`, а изображения ссылаются на папку `images`, которую вы только что создали. + +## Шаг 3 — Экспорт в PDF/UA‑2 (готовый для доступности) + +Если вам нужно поделиться документом с пользователями, использующими скрин‑ридеры или другие вспомогательные технологии, соответствие **PDF/UA‑2** является золотым стандартом. Aspose.Words может обеспечить это одним флагом, а также преобразовать плавающие фигуры в встроенные теги, чтобы они не терялись при конвертации. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Почему важен PDF/UA:** +- PDF/UA (Universal Accessibility) гарантирует, что полученный PDF содержит правильную разметку, логический порядок чтения и альтернативный текст для изображений. +- Установка `ExportFloatingShapesAsInlineTag` гарантирует, что такие фигуры, как текстовые блоки или выноски, не будут пропущены или смещены — частая проблема при конвертации сложных макетов. + +### Проверка соответствия PDF/UA + +После экспорта откройте PDF в Adobe Acrobat Pro и запустите **«Accessibility Check»** (Tools → Accessibility → Full Check). Если инструмент сообщает **0 ошибок**, вы успешно завершили задачу. + +## Пограничные случаи и распространённые подводные камни + +| Ситуация | На что обратить внимание | Исправление / Рекомендация | +|----------------------------------------|------------------------------------------------------------|--------------------------------------------------------------| +| Файл Word содержит **неподдерживаемые шрифты** | Шрифты могут быть заменены, нарушая макет уравнений | Предоставьте пользовательский `FontSettings` с резервными шрифтами. | +| Большие документы (> 100 MB) | Нагрузка на память во время конвертации | Используйте `LoadOptions` с `LoadFormat.Docx` и потоковое чтение файла. | +| Изображения — векторные графики **EMF/WMF** | Они могут быть неожиданно растеризованы | Преобразуйте их в PNG с помощью `ImageSaveOptions` перед сохранением. | +| PDF/UA не проходит проверку на **вложенных таблицах** | Разметка может стать неоднозначной | Включите `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit`, чтобы помочь движку. | +| Необходимо **сохранить пользовательские стили** | Markdown имеет ограниченные возможности стилизации | Экспортируйте CSS‑файл вместе с Markdown и укажите его. | + +## Полный рабочий пример (весь код вместе) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Запустите программу, и вы найдёте как `doc.md` (с уравнениями LaTeX и чистыми ссылками на изображения), так и `doc.pdf` (полностью соответствующий PDF/UA‑2) в папке `YOUR_DIRECTORY`. + +## Визуальный обзор + +![пример конвертации Word в Markdown](https://example.com/placeholder.png "пример конвертации Word в Markdown – показывает входной Word, вывод Markdown и файл PDF/UA") + +*Alt text:* **пример конвертации Word в Markdown** – диаграмма конвейера преобразования из файла Word в Markdown и PDF/UA. + +## Итоги и дальнейшие шаги + +Мы только что **конвертировали Word в Markdown**, сохранив уравнения, разместили изображения в аккуратной папке и создали файл **save as PDF/UA**, который проходит проверки доступности. Ключевые выводы: + +- Используйте `LoadOptions.RecoveryMode.Relaxed`, чтобы терпимо обрабатывать несовершенные файлы Word. +- Установите `OfficeMathExportMode` в `LaTeX` для чистого отображения уравнений. +- Реализуйте `ResourceSavingCallback` для управления выводом изображений. +- Включите `PdfCompliance.PdfUAXmpA2` и `ExportFloatingShapesAsInlineTag` для PDF, соответствующего стандартам. + +### Что изучать дальше? + +- **Custom CSS для Markdown** — сгенерировать таблицу стилей, отражающую стили Word. +- **Пакетная обработка** — пройтись по каталогу файлов `.docx` для автоматизации массовой миграции. +- **Продвинутые возможности PDF/UA** — добавить пользовательские теги, задать атрибуты языка или внедрить аудио‑описания. +- **Интеграция с CI/CD** — гарантировать, что каждый билд автоматически создаёт доступные PDF. + +Если возникнут проблемы, дважды проверьте, что версия Aspose.Words соответствует использованному здесь API, и помните, что собственная документация библиотеки является надёжным вторичным источником. + +Удачной кодировки, и пусть ваши документы остаются одновременно красивыми **и** доступными! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/programming-with-txtsaveoptions/_index.md b/words/russian/net/programming-with-txtsaveoptions/_index.md index 1827608650..34507ae8fa 100644 --- a/words/russian/net/programming-with-txtsaveoptions/_index.md +++ b/words/russian/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ | [Добавить знаки биди в документ Word](./add-bidi-marks/) | Узнайте, как добавлять двунаправленные (Bidi) знаки в документы Word с помощью Aspose.Words для .NET с помощью этого руководства. Обеспечьте правильное направление текста для многоязычного контента. | | [Использовать символ табуляции на уровне для отступа списка](./use-tab-character-per-level-for-list-indentation/) | Узнайте, как создавать многоуровневые списки с табулированными отступами с помощью Aspose.Words для .NET. Следуйте этому руководству для точного форматирования списков в ваших документах. | | [Используйте пробел на каждом уровне для отступа списка](./use-space-character-per-level-for-list-indentation/) | Узнайте, как создавать многоуровневые списки с отступом в виде пробела в Aspose.Words для .NET. Пошаговое руководство по точному форматированию документов. | - +| [Сохранить docx как txt – Экспорт уравнений Word в LaTeX с C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Узнайте, как экспортировать уравнения из документов Word в формат LaTeX при сохранении как txt с помощью C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/russian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..05d62c26e6 --- /dev/null +++ b/words/russian/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Сохраните docx как txt с помощью Aspose.Words — быстро конвертируйте + Word в txt и узнайте, как экспортировать математические уравнения в LaTeX. Простой + код C#, без дополнительных инструментов. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: ru +og_description: Сохраните docx как txt в C# и узнайте, как экспортировать формулы + в LaTeX. Следуйте этому пошаговому руководству, чтобы преобразовать Word в txt с + сохранёнными уравнениями. +og_title: сохранить docx как txt – экспортировать уравнения Word в LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Сохранить docx как txt – экспортировать уравнения Word в LaTeX с помощью C# +url: /ru/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Сохранить docx как txt – экспортировать уравнения Word в LaTeX с C# + +Когда‑нибудь вам нужно было **save docx as txt**, но вы боялись, что ваши уравнения исчезнут или превратятся в нечитаемый мусор? Вы не одиноки. Многие разработчики сталкиваются с этой проблемой, когда пытаются **convert word to txt** для последующей обработки, особенно если исходный файл содержит объекты Office Math. + +Хорошие новости? С несколькими строками C# и правильными параметрами вы можете не только **convert Word to txt**, но и сохранить каждое уравнение в виде чистой разметки LaTeX. В этом руководстве мы пройдем весь процесс, объясним, почему каждое настройка важна, и покажем, как проверить результат. + +Мы рассмотрим: + +* Установку библиотеки Aspose.Words for .NET +* Загрузку `.docx`, содержащего математические уравнения +* Настройку `TxtSaveOptions`, чтобы **how to export math** превратилось в строку, совместимую с LaTeX +* Сохранение файла и проверку вывода + +К концу вы получите переиспользуемый фрагмент кода, который позволяет **save docx as txt**, сохраняя каждую формулу в виде LaTeX — идеально для научных конвейеров, генераторов статических сайтов или любого рабочего процесса, требующего простого текста с математикой. + +--- + +## Prerequisites + +Прежде чем начать, убедитесь, что у вас есть: + +* .NET 6.0 или новее (код также работает с .NET Framework 4.6+) +* Visual Studio 2022 (или любая другая IDE) +* NuGet‑пакет **Aspose.Words for .NET** – установите его с помощью + +```bash +dotnet add package Aspose.Words +``` + +Никакие дополнительные конвертеры или внешние инструменты не требуются; Aspose.Words справляется со всем внутри. + +--- + +## Step 1: Install and reference Aspose.Words + +Сначала добавьте библиотеку в проект. Если вы используете командную строку, выполните приведённую выше команду. В Visual Studio также можно щёлкнуть правой кнопкой **Dependencies → Manage NuGet Packages** и найти *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Используйте последнюю стабильную версию (на апрель 2026 года это 24.10). Более новые релизы содержат исправления ошибок обработки OfficeMath, поэтому вы избежите неожиданного отсутствия символов. + +--- + +## Step 2: Load the source document + +Теперь загрузим `.docx`, содержащий уравнения, которые нужно сохранить. Класс `Document` абстрагирует весь файл Word, предоставляя доступ к тексту, изображениям и объектам Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Почему сначала загружаем? Aspose.Words разбирает файл в объектную модель, позволяя нам инспектировать или изменять содержимое перед тем, как решить, как экспортировать его. Именно здесь начинают играть роль решения **how to export math**. + +--- + +## Step 3: Configure TxtSaveOptions for LaTeX export + +Сердце решения — класс `TxtSaveOptions`. По умолчанию сохранение в TXT полностью удаляет Office Math. Установка `OfficeMathExportMode` в `LaTeX` заставляет библиотеку переводить каждое уравнение в его LaTeX‑представление. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Почему LaTeX?** LaTeX — lingua franca научных публикаций. Экспортируя математику таким образом, вы сохраняете семантику уравнения, а не плоское изображение или искажённую строку. Если позже вы передадите TXT в процессор Markdown, поддерживающий MathJax, уравнения отобразятся идеально. + +--- + +## Step 4: Save the document as plain‑text + +С настроенными параметрами последний шаг — однострочная команда, записывающая файл на диск. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +И всё — ваш `.docx` теперь `.txt`, где каждое уравнение представлено как фрагмент LaTeX, готовый к дальнейшему использованию. + +--- + +## Verifying the output (How to save txt correctly) + +Откройте `MathSample.txt` в любом текстовом редакторе. Вы должны увидеть что‑то вроде: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Если вы заметили необработанные символы Word (например, `?` или отсутствующие знаки), проверьте следующее: + +* Вы используете свежую версию Aspose.Words (в старых сборках были баги с OfficeMath). +* Исходный документ действительно содержит **OfficeMath**‑объекты, а не устаревшие объекты Equation Editor. В последнем случае их может потребоваться конвертировать вручную или вызвать метод `ConvertMathToOfficeMath` перед сохранением. + +--- + +## Common Variations & Edge Cases + +| Ситуация | Что делать | +|-----------|------------| +| **Legacy Equation Editor** objects | Вызовите `doc.ConvertMathToOfficeMath()` перед шагом 3. | +| **You need plain Unicode math, not LaTeX** | Установите `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Large documents (100 + MB)** | Потоково сохраняйте с помощью `doc.Save(Stream, txtOptions)`, чтобы избежать высокого потребления памяти. | +| **You want to keep the original file name** | Используйте `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` при построении пути вывода. | + +Эти настройки отвечают на вопрос “**how to export math**” для разных конвейеров, обеспечивая надёжность решения независимо от исходного файла. + +--- + +## Full Working Example (All steps in one place) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Запустите программу, откройте сгенерированный `.txt`, и вы увидите встроенные LaTeX‑уравнения именно там, где они должны быть. Это самый простой способ **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/russian/net/working-with-fonts/_index.md b/words/russian/net/working-with-fonts/_index.md index 57d561bdc8..da790947a9 100644 --- a/words/russian/net/working-with-fonts/_index.md +++ b/words/russian/net/working-with-fonts/_index.md @@ -48,7 +48,7 @@ | [Получать предупреждающие уведомления](./receive-warning-notification/) Узнайте, как получать предупреждающие уведомления при использовании Aspose.Words для .NET и управлять любыми проблемами или предупреждениями в ваших документах. | | [Пример исходного кода шрифта Steam](./resource-steam-font-source-example/) | Узнайте, как использовать источник шрифтов Resource Stream для загрузки пользовательских шрифтов в Aspose.Words для .NET. | | [Получить замену без суффиксов](./get-substitution-without-suffixes/) | В этом уроке вы узнаете, как получить переопределения без суффиксов в документе Word с помощью Aspose.Words для .NET. | - +| [Подстановка шрифтов Aspose – Обнаружение отсутствующих шрифтов в документах Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Узнайте, как обнаружить отсутствующие шрифты в документах Word с помощью Aspose Font Substitution. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/russian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/russian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..d5bfb94675 --- /dev/null +++ b/words/russian/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Руководство по замене шрифтов Aspose для обнаружения отсутствующих шрифтов + при загрузке документа Word. Узнайте, как настроить параметры шрифтов и эффективно + обрабатывать отсутствующие шрифты. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: ru +og_description: Руководство по замене шрифтов Aspose для обнаружения отсутствующих + шрифтов при загрузке документа Word. Узнайте, как настроить параметры шрифтов и + эффективно обрабатывать недостающие шрифты. +og_title: Подстановка шрифтов Aspose – Обнаружение отсутствующих шрифтов в документах + Word +tags: +- Aspose.Words +- C# +- Font Management +title: Подстановка шрифтов Aspose – обнаружение отсутствующих шрифтов в документах + Word +url: /ru/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Обнаружение отсутствующих шрифтов в документах Word + +Случалось ли вам открывать файл Word, который выглядит идеально на одном компьютере, но показывает странные изменения шрифтов на другом? Это классическая проблема **aspose font substitution**, обычно означающая, что некоторые шрифты отсутствуют в целевой системе. В этом руководстве мы покажем вам шаг за шагом, как **обнаружить отсутствующие шрифты** при **загрузке документа Word**, как **настроить параметры шрифтов**, и что делать, чтобы **корректно обрабатывать отсутствующие шрифты**. + +Мы пройдем через полный, исполняемый пример на C#, объясним, почему каждая строка важна, и даже покажем ожидаемый вывод в консоль. К концу вы сможете обнаруживать замену шрифтов в момент загрузки документа — без догадок. + +## Что вы узнаете + +- Как включить диагностический сборщик Aspose.Words для предупреждений о шрифтах. +- Точный код, необходимый для **загрузки документа Word** с пользовательскими **настройками шрифтов**. +- Как перебрать объекты `WarningInfo`, чтобы вывести список всех замененных шрифтов. +- Советы по подавлению нежелательных предупреждений или предоставлению резервных шрифтов. +- Готовый к запуску пример, который вы можете скопировать и вставить в Visual Studio. + +### Требования + +- .NET 6.0 или новее (API работает одинаково на .NET Framework). +- Aspose.Words for .NET (пакет NuGet `Aspose.Words`). +- Файл Word, который использует шрифт, не установленный у вас (например, `MissingFont.docx`). + +Если у вас есть всё это, давайте приступим. + +## Шаг 1 – Включить диагностический сборщик (Настроить параметры шрифтов) + +Сначала: Aspose.Words записывает предупреждения о замене шрифтов только если вы его об этом попросите. Это делается путем создания объекта `FontSettings` и назначения его экземпляру `LoadOptions`. Считайте это включением «отладочных индикаторов» для обработки шрифтов. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Почему?** +Без объекта `FontSettings` сборщик предупреждений будет молчать, и вы никогда не узнаете, какие шрифты были заменены. Инициализируя его пустым, мы позволяем Aspose использовать шрифты системы по умолчанию *и* отслеживать любые замены. + +> **Совет:** Если вы знаете, что в определенной папке находятся корпоративные шрифты, укажите её в `FontSettings` с помощью `SetFontsFolder("path")`. Это может уменьшить количество предупреждений об отсутствующих шрифтах. + +## Шаг 2 – Загрузить документ с настроенными параметрами (Загрузка документа Word) + +Теперь, когда сборщик активен, загрузите ваш файл `.docx`, используя те же `LoadOptions`. Это момент, когда Aspose сканирует документ, ищет каждое упоминание шрифта и решает, нужна ли замена. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Почему это важно?** +Если вы просто вызовете `new Document("MissingFont.docx")`, применятся настройки по умолчанию *и* список предупреждений останется пустым. Передача `loadOptions` гарантирует, что диагностический сборщик будет подключен к процессу загрузки. + +## Шаг 3 – Получить и отобразить предупреждения о замене шрифтов (Обнаружить отсутствующие шрифты) + +После того как документ загружен в память, Aspose сохраняет любые предупреждения в `document.WarningCallback.Warnings`. Пройдитесь по этой коллекции, отфильтруйте элементы `WarningType.FontSubstitution` и выведите описание. Каждое описание сообщает, какой шрифт был отсутствующим и какой использован вместо него. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Ожидаемый вывод в консоль** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Этот вывод точно показывает, какие шрифты отсутствуют на машине, где выполняется код. Теперь вы можете решить, установить ли отсутствующие шрифты, внедрить их в документ или оставить замену. + +![Вывод консоли, показывающий предупреждения о замене шрифтов Aspose](/images/aspose-font-substitution-console.png) + +*Текст альтернативного изображения:* aspose font substitution – вывод консоли со списком замененных шрифтов + +## Шаг 4 – Необязательно: Настроить поведение замены (Обработка отсутствующих шрифтов) + +Иногда вам нужно не только знать, *что* произошла замена, но и контролировать, *как* она происходит. Aspose.Words позволяет зарегистрировать пользовательское `IFontSubstitutionRule`. Ниже быстрый пример, который заставляет любой отсутствующий шрифт использовать `Tahoma` в качестве резервного. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Когда это может понадобиться?** +Если вы генерируете PDF для веб‑сервиса и знаете, что каждый клиент может отобразить `Tahoma`, принудительное использование резервного шрифта гарантирует визуальную согласованность без необходимости распространять десятки файлов шрифтов. + +## Полный рабочий пример (Все шаги вместе) + +Вот полный код программы, который вы можете вставить в новый консольный проект. Он компилируется без изменений, при условии, что вы установили пакет NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Запустите программу, наблюдайте за консолью, и вы увидите вывод каждого события отсутствующего шрифта. После этого вы сможете решить, установить ли отсутствующие шрифты, внедрить их или оставить резервный. + +## Часто задаваемые вопросы + +**В: Работает ли это при конвертации в PDF?** +Да. Когда вы позже вызываете `doc.Save("output.pdf")`, любые шрифты, заменённые во время загрузки, будут встроены в PDF. Поэтому раннее обнаружение предупреждений помогает избежать неожиданных изменений шрифтов в конечном PDF. + +**В: Что делать, если нужно обработать много документов?** +Оберните логику загрузки в блок try‑catch и переиспользуйте один экземпляр `FontSettings` для всех документов. Это уменьшает накладные расходы и сохраняет активным сборщик предупреждений для каждого файла. + +**В: Можно ли полностью подавлять предупреждения?** +Вы можете установить `loadOptions.WarningCallback = null;` перед загрузкой, но тогда потеряете возможность **обнаруживать отсутствующие шрифты** — что обычно не желаемо. + +## Заключение + +Мы рассмотрели всё, что нужно знать, чтобы освоить **aspose font substitution**: включение диагностического сборщика, загрузка файла Word с пользовательскими **настройками шрифтов**, извлечение списка отсутствующих шрифтов и даже переопределение правила замены по‑умолчанию, чтобы **обрабатывать отсутствующие шрифты** по‑своему. Всего несколькими строками C# вы получаете полную видимость проблем со шрифтами, которые иначе скрывались бы за тонкими изменениями макета. + +Следующие шаги? Попробуйте внедрить оригинальные шрифты в документ с помощью `FontSettings.SetFontsFolder` или изучить `FontSourceBase` для загрузки шрифтов из базы данных. Вы также можете поэкспериментировать с коллекцией `Document.BuiltInStyle`, чтобы увидеть, как изменения шрифтов на уровне стилей распространяются. + +Есть дополнительные вопросы по Aspose.Words или управлению шрифтами? Оставьте комментарий, изучите официальную документацию Aspose или создайте новый проект и поиграйте с приведённым выше кодом. Приятного кодинга, и пусть ваши документы всегда отображаются точно так, как задумано! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/basic-conversions/_index.md b/words/spanish/net/basic-conversions/_index.md index 0145e04557..2f7125fd81 100644 --- a/words/spanish/net/basic-conversions/_index.md +++ b/words/spanish/net/basic-conversions/_index.md @@ -34,7 +34,8 @@ Conversiones Básicas te guía a través de las conversiones básicas de documen | [Guardar PDF en formato Word (Docx)](./pdf-to-docx/) Aprenda a convertir un PDF a un documento de Word (Docx) con Aspose.Words para .NET con esta guía detallada paso a paso. Ideal para desarrolladores. | [Cómo exportar LaTeX desde Word – Guía paso a paso](./how-to-export-latex-from-word-step-by-step-guide/) Aprenda a exportar contenido LaTeX desde Word usando Aspose.Words para .NET con esta guía paso a paso. | [Convertir Word a PDF en C# usando Aspose.Words – Guía](./convert-word-to-pdf-in-c-using-aspose-words-guide/) Aprenda a convertir documentos Word a PDF en C# con Aspose.Words. Guía paso a paso con ejemplos de código. -| [Guardar Word como PDF con Aspose.Words – Guía completa en C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) Aprenda a guardar documentos Word como PDF usando Aspose.Words en C#. Guía paso a paso con ejemplos de código. | +| [Guardar Word como PDF con Aspose.Words – Guía completa en C#](./save-word-as-pdf-with-aspose-words-complete-c-guide/) Aprenda a guardar documentos Word como PDF usando Aspose.Words en C#. Guía paso a paso con ejemplos de código. +| [Convertir Word a PDF en C# – Guía completa con Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) Aprenda a convertir documentos Word a PDF en C# usando Aspose.Words con esta guía paso a paso y ejemplos de código. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/spanish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..0b9ee07923 --- /dev/null +++ b/words/spanish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,195 @@ +--- +category: general +date: 2026-04-05 +description: Convertir Word a PDF en C# usando Aspose.Words. Aprende cómo guardar + docx como PDF, exportar PDF accesible y cargar documentos Word de manera eficiente. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: es +og_description: Convierte Word a PDF en C# con una guía paso a paso. Descubre cómo + guardar docx como PDF, exportar PDF accesible y cargar documentos de Word usando + Aspose.Words. +og_title: Convertir Word a PDF en C# – Tutorial completo de Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Convertir Word a PDF en C# – Guía completa con Aspose.Words +url: /es/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir Word a PDF en C# – Tutorial de Programación Completo + +¿Alguna vez te has preguntado cómo **convertir word a pdf** sin luchar con engorrosas herramientas de línea de comandos o servicios de terceros? No eres el único. Muchos desarrolladores se topan con ese obstáculo cuando un cliente solicita un PDF accesible directamente desde un archivo DOCX. ¿La buena noticia? Con unas pocas líneas de C# y la poderosa biblioteca Aspose.Words, puedes convertir un documento Word en un PDF que cumple con los estándares en un abrir y cerrar de ojos. + +En esta guía repasaremos todo lo que necesitas saber: desde los conceptos básicos de **load word document**, pasando por la configuración de las opciones correctas para **how to export accessible pdf**, y finalmente guardando el resultado para que puedas **save docx as pdf** de forma fiable. Al final tendrás un fragmento listo para ejecutar que podrás insertar en cualquier proyecto .NET. + +> **Consejo profesional:** Si estás apuntando a la conformidad PDF/UA‑2 (el estándar de accesibilidad que muchas agencias gubernamentales requieren), el mismo código funciona sin pasos adicionales—simplemente establece la bandera `PdfCompliance` adecuada. + +## Lo que aprenderás + +- Cómo **load word document** usando Aspose.Words en C#. +- Los ajustes exactos necesarios para **how to export accessible pdf** (PDF/UA‑2). +- Un ejemplo completo y ejecutable que **save docx as pdf** con una sola llamada al método. +- Problemas comunes cuando **c# convert docx pdf** y cómo evitarlos. +- Formas rápidas de verificar que el PDF generado cumpla con las expectativas de accesibilidad. + +Sin herramientas externas, sin archivos de configuración oscuros—solo código puro de C# que puedes compilar hoy. + +## Requisitos previos + +Antes de sumergirnos, asegúrate de tener: + +1. **.NET 6.0** (o cualquier versión reciente de .NET) instalado. Los frameworks más antiguos también funcionan, pero la sintaxis a continuación asume el SDK moderno. +2. Una **license** para Aspose.Words for .NET. La biblioteca ofrece una prueba gratuita, pero para producción necesitarás una clave válida. +3. El paquete NuGet **Aspose.Words** añadido a tu proyecto: + +```bash +dotnet add package Aspose.Words +``` + +Eso es todo—sin binarios adicionales, sin interop COM, solo una referencia NuGet limpia. + +![convertir word a pdf usando Aspose.Words en C#](image-placeholder.png "convertir word a pdf usando Aspose.Words en C#") + +## Implementación paso a paso + +A continuación dividimos el proceso en bloques lógicos. Cada paso contiene un pequeño fragmento de código, una explicación de **por qué** es importante y un consejo basado en el uso real. + +### ## Convertir Word a PDF – Cargar el documento fuente + +Lo primero que debes hacer es **load word document** en memoria. Aspose.Words abstrae el análisis de OpenXML, por lo que puedes trabajar con archivos DOCX, DOC o incluso RTF sin preocuparte por las particularidades del formato. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Por qué es importante:** +Cargar el archivo crea un objeto `Document` que representa todo el archivo Word, incluidos encabezados, pies de página, estilos y metadatos ocultos. Si omites este paso o intentas leer el archivo como un flujo bruto, perderás la información de diseño que luego determina cómo se ve el PDF. + +> **Nota al margen:** El mismo constructor `Document` funciona para `.doc` y `.rtf`. Eso significa que puedes **c# convert docx pdf** incluso cuando la fuente no es estrictamente un DOCX. + +### ## Guardar DOCX como PDF – Configurar la conformidad PDF/UA‑2 + +Ahora que el documento está en memoria, indicamos a Aspose.Words cómo queremos que se genere el PDF. Para la mayoría de los casos, la configuración predeterminada es suficiente, pero cuando necesitas un **accessible PDF** debes habilitar la bandera de conformidad PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Por qué es importante:** +`PdfCompliance.PdfUAXmpA2` indica a la biblioteca que incruste las etiquetas y estructuras necesarias que los lectores de pantalla utilizan. Sin esta bandera, podrías obtener un PDF con aspecto perfecto que falla en una auditoría de accesibilidad. + +> **Consejo:** Si solo necesitas un PDF normal, puedes omitir la línea `Compliance`. El resto de las opciones aún te brinda una salida de alta calidad. + +### ## Convertir Word a PDF – Escribir el archivo + +Con las opciones listas, el paso final es **save docx as pdf**. Esta única llamada realiza todo el trabajo pesado: conversión de diseño, incrustación de fuentes y etiquetado de accesibilidad. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Lo que obtienes:** +- Un archivo PDF en `outputPath` que replica el diseño de Word. +- Si usaste la bandera `PdfUAXmpA2`, el PDF estará marcado como compatible con PDF/UA‑2. +- Todas las fuentes están incrustadas, por lo que el archivo se ve idéntico en cualquier máquina. + +### ## Verificar el PDF accesible (Opcional pero recomendado) + +Después de la conversión, es una buena idea verificar que el PDF realmente **how to export accessible pdf** correctamente. Puedes usar herramientas gratuitas como la “Comprobación de accesibilidad” de Adobe Acrobat Reader o el validador de código abierto `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Si el validador no reporta errores, has **convert word to pdf** con soporte completo de accesibilidad. + +### ## Problemas comunes al C# convertir DOCX a PDF + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| Fuentes faltantes | El DOCX fuente usa una fuente personalizada que no está instalada en el servidor. | Establece `EmbedFullFonts = true` o instala la fuente en la máquina. | +| Tamaño de archivo grande | Las imágenes se incrustan a resolución completa. | Usa `ImageCompression = PdfImageCompression.Jpeg` y establece `JpegQuality` a un valor más bajo. | +| Hipervínculos rotos | Los enlaces apuntan a rutas relativas que no existen en el cliente. | Asegúrate de que las URLs sean absolutas o ajusta la propiedad `HyperlinkTarget`. | +| Etiquetas de accesibilidad faltantes | Bandera `Compliance` no establecida. | Añade `Compliance = PdfCompliance.PdfUAXmpA2` como se mostró arriba. | + +Tener esto en cuenta hará que tu rutina **c# convert docx pdf** sea robusta y lista para producción. + +## Ejemplo completo y funcional + +Juntando todo, aquí tienes una aplicación de consola autónoma que puedes compilar y ejecutar ahora mismo. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Resultado esperado:** Después de ejecutar el programa, encontrarás `output.pdf` en `C:\Docs`. Ábrelo en cualquier visor de PDF; el diseño debe coincidir con `input.docx` píxel por píxel, y una comprobación de accesibilidad confirmará la conformidad PDF/UA‑2. + +## Conclusión + +Acabamos de repasar una solución completa, de extremo a extremo, para **convert word to pdf** usando C# y Aspose.Words. Mediante **load word document**, configurando las `PdfSaveOptions` correctas y finalmente **save docx as pdf**, obtienes un PDF de alta calidad y accesible con código mínimo. Ya sea que estés construyendo un microservicio de generación de documentos, un convertidor por lotes local, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-markdownsaveoptions/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/_index.md index bc76e03596..0b4083008d 100644 --- a/words/spanish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/spanish/net/programming-with-markdownsaveoptions/_index.md @@ -28,11 +28,13 @@ Procesamiento de textos con MarkdownSaveOptions es un recurso detallado que te g | [Cómo usar Markdown: Convertir DOCX a Markdown con ecuaciones LaTeX](./how-to-use-markdown-convert-docx-to-markdown-with-latex-equa/) Aprenda a convertir documentos DOCX a Markdown conservando ecuaciones LaTeX usando Aspose.Words para .NET. | | [Guardar docx como markdown – Guía completa en C# con ecuaciones LaTeX](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) Aprenda a guardar documentos DOCX como Markdown conservando ecuaciones LaTeX usando Aspose.Words para .NET. | | [Guardar docx como markdown – Guía completa en C# con extracción de imágenes](./save-docx-as-markdown-full-c-guide-with-image-extraction/) Aprenda a guardar documentos DOCX como Markdown y extraer imágenes usando Aspose.Words para .NET. | +| [Convertir DOCX a Markdown – Extraer imágenes del DOCX con Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) Aprenda a convertir documentos DOCX a Markdown y extraer todas las imágenes usando Aspose.Words para .NET. | | [Cómo exportar Markdown desde Word – Guía completa en C#](./how-to-export-markdown-from-word-complete-c-guide/) Aprenda a exportar contenido de Word a formato Markdown con una guía completa en C# usando Aspose.Words. | ### [Crear PDF accesible y convertir Word a Markdown – Guía completa en C#](./create-accessible-pdf-and-convert-word-to-markdown-full-c-gu/) Aprenda a generar PDFs accesibles y convertir documentos Word a Markdown usando C# y Aspose.Words para .NET. ### [Cómo guardar Markdown desde DOCX – Guía paso a paso](./how-to-save-markdown-from-docx-step-by-step-guide/) Aprenda a guardar documentos DOCX como archivos Markdown paso a paso con Aspose.Words para .NET. ### [Cómo exportar Markdown desde DOCX – Guía completa](./how-to-export-markdown-from-docx-complete-guide/) Aprenda a exportar contenido de archivos DOCX a formato Markdown con una guía completa usando Aspose.Words para .NET. +### [Convertir Word a Markdown – Guía completa con exportación PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) Aprenda a convertir documentos Word a Markdown y exportar PDFs accesibles PDF/UA usando Aspose.Words para .NET. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..aa62cda87b --- /dev/null +++ b/words/spanish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Aprende cómo convertir DOCX a Markdown y extraer imágenes de DOCX en + C#. Guía paso a paso con código completo y consejos. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: es +og_description: Convertir DOCX a Markdown y extraer imágenes de DOCX usando Aspose.Words. + Tutorial completo de C# con código, explicación y consejos de buenas prácticas. +og_title: Convertir DOCX a Markdown – Extraer imágenes de DOCX en C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Convertir DOCX a Markdown – Extraer imágenes de DOCX con Aspose.Words +url: /es/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir DOCX a Markdown – Extraer imágenes de DOCX en C# + +¿Alguna vez necesitaste **convertir DOCX a Markdown** pero tuviste problemas con que las imágenes desaparecieran en el resultado? No eres el único. En muchos proyectos la versión markdown es perfecta para el control de versiones o generadores de sitios estáticos, sin embargo las imágenes se quedan atrás, convirtiendo un documento rico en un archivo de texto vacío. + +¿La buena noticia? Con unas pocas líneas de C# y Aspose.Words puedes **convertir DOCX a Markdown** *y* **extraer imágenes de DOCX** automáticamente. Esta guía te lleva a través de todo el proceso, explica por qué cada parte es importante, y hasta te muestra cómo mantener ordenada tu carpeta de imágenes. + +## Lo que aprenderás + +- Cómo cargar un DOCX que contiene imágenes. +- Cómo definir un `IResourceSavingCallback` personalizado que decide dónde se guarda cada imagen. +- Cómo configurar `MarkdownSaveOptions` para que el markdown generado haga referencia a las imágenes extraídas correctamente. +- Consejos para manejar casos límite como nombres de imágenes duplicados o formatos que no sean PNG. +- Un ejemplo de código completo, listo para copiar y pegar, que puedes ejecutar hoy. + +### Requisitos previos + +- .NET 6.0 o posterior (la API funciona en .NET Core, .NET Framework y .NET 5+). +- Una licencia para **Aspose.Words for .NET** (la prueba gratuita sirve para pruebas). +- Familiaridad básica con C# y Visual Studio (o tu IDE favorito). + +Si tienes eso, vamos a sumergirnos. + +--- + +## Paso 1: Configurar el proyecto e instalar Aspose.Words + +Primero, crea una nueva aplicación de consola (o intégrala en una solución existente). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Consejo profesional:** Usa la última versión de NuGet (a partir de abril 2026 es la 24.12) para obtener las mejoras más recientes en la exportación a markdown. + +--- + +## Paso 2: Crear una devolución de llamada para guardar imágenes donde desees + +Aspose.Words te permite interceptar cada recurso (imágenes, SVG, etc.) que se escribe durante la exportación a markdown. Al implementar `IResourceSavingCallback` puedes: + +1. Elegir una carpeta que esté junto a tu archivo markdown. +2. Generar un nombre de archivo único (para que nunca sobrescribas una imagen existente). +3. Decidir el formato (aquí forzamos PNG por consistencia). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### ¿Por qué un nombre basado en GUID? + +Si el DOCX de origen contiene dos imágenes con el mismo nombre original, una simple copia‑pega sobrescribiría una de ellas. Usar `Guid.NewGuid()` garantiza unicidad, lo cual es especialmente útil cuando ejecutas la conversión muchas veces en una canalización automatizada. + +--- + +## Paso 3: Cargar el DOCX y conectar las opciones de Markdown + +Ahora cargamos el documento en memoria y adjuntamos la devolución de llamada que acabamos de crear. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Qué hace el código, paso a paso + +| Paso | Propósito | +|------|-----------| +| **Definir rutas** | Mantiene tu proyecto flexible; puedes apuntar a cualquier carpeta sin recompilar. | +| **Cargar el DOCX** | `Document` analiza el archivo Word, haciendo accesibles todos los elementos (párrafos, tablas, imágenes). | +| **Configurar `MarkdownSaveOptions`** | El `ResourceSavingCallback` es el gancho que extrae las imágenes. Sin él, Aspose.Words incrustaría las imágenes como cadenas base64 o las eliminaría por completo, según la configuración. | +| **Guardar** | `doc.Save` escribe el archivo markdown y dispara la devolución de llamada para cada imagen. | + +--- + +## Paso 4: Verificar la salida – ¿Qué deberías ver? + +Después de ejecutar el programa, abre `DocWithImages.md`. Notarás enlaces de imagen markdown que se ven así: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Y en `C:\Docs\MarkdownResources` encontrarás una serie de archivos PNG con nombres GUID. Abre cualquiera de ellos – deberían ser idénticos a las imágenes que estaban incrustadas en el DOCX original. + +Si abres el archivo markdown en un visor que respete rutas relativas (p.ej., la vista previa de VS Code, GitHub o un generador de sitios estáticos), las imágenes se renderizarán tal como lo hacían en Word. + +### Errores comunes y cómo evitarlos + +| Síntoma | Causa probable | Solución | +|---------|----------------|----------| +| Las imágenes aparecen como enlaces rotos | No se estableció `ResourceFileName`, por lo que el markdown apunta a un archivo inexistente. | Asegúrate de `args.ResourceFileName = newFileName;` dentro de la devolución de llamada. | +| Los archivos PNG son enormes | Las imágenes originales eran JPEG o BMP; convertir a PNG puede aumentar el tamaño. | Detecta el formato original mediante `args.ResourceContentType` y consérvalo: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Aún aparecen imágenes duplicadas | Usaste un nombre de archivo estático en lugar de un GUID. | Vuelve a la lógica de GUID o agrega un contador por tipo de imagen. | +| La conversión lanza `FileNotFoundException` | La ruta del DOCX de origen es incorrecta o la carpeta carece de permiso de lectura. | Verifica la ruta y otorga los permisos de sistema de archivos adecuados. | + +--- + +## Paso 5: Ajustes avanzados (Opcional) + +### 5.1 Conservar los formatos originales de imagen + +Si deseas que las imágenes de salida mantengan sus extensiones originales, modifica la devolución de llamada: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Incrustar imágenes como Base64 (cuando *no* deseas archivos separados) + +A veces un markdown de un solo archivo es preferible (p.ej., para enviar por correo electrónico). Cambia la opción: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Pero recuerda: **extraer imágenes de DOCX** es el objetivo principal para la mayoría de los flujos de trabajo de sitios estáticos, por lo que el enfoque de carpeta suele ser la mejor opción. + +--- + +## Ejemplo completo funcional (listo para copiar‑pegar) + +Abajo está todo el programa en un solo archivo. Solo reemplaza las rutas con las tuyas y ejecuta. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Ejecútalo con `dotnet run`. Cuando la consola imprima la línea ✅, abre el archivo markdown y deberías ver las imágenes renderizadas correctamente. + +--- + +## Conclusión + +Ahora tienes una **solución completa y lista para producción para convertir DOCX a Markdown y extraer imágenes de DOCX** usando Aspose.Words en C#. La palabra clave principal aparece a lo largo de la guía, reforzando la relevancia tanto para los motores de búsqueda como para los asistentes de IA. + +En una sola pasada el código: + +1. Carga un documento Word. +2. Intercepta cada imagen mediante `IResourceSavingCallback`. +3. Guarda cada imagen en una carpeta predecible con un nombre único. +4. Genera markdown que hace referencia a esas imágenes. + +Desde aquí puedes: + +- Conectar + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/spanish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..9be74d36a0 --- /dev/null +++ b/words/spanish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: Convierte Word a Markdown rápidamente y también aprende cómo guardar + como PDF/UA en C#. Código paso a paso, consejos y manejo de casos límite. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: es +og_description: Convierte Word a Markdown y guárdalo como PDF/UA con Aspose.Words. + Aprende el porqué, el cómo y consejos de mejores prácticas en una guía concisa. +og_title: Convertir Word a Markdown – Tutorial completo de C# +tags: +- Aspose.Words +- C# +- Document Conversion +title: Convertir Word a Markdown – Guía completa con exportación PDF/UA +url: /es/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir Word a Markdown – Guía completa con exportación PDF/UA + +¿Alguna vez te has preguntado cómo **convertir Word a Markdown** sin perder ecuaciones o imágenes? No eres el único. Muchos desarrolladores necesitan una forma fiable de transformar archivos `.docx` en Markdown limpio mientras aún pueden **guardar como PDF/UA** para PDFs compatibles con accesibilidad. En este tutorial recorreremos una solución completa, lista para ejecutar, usando Aspose.Words para .NET, explicaremos por qué cada configuración es importante y te mostraremos cómo manejar las partes más complicadas como OfficeMath y formas flotantes. + +Al final de esta guía tendrás un único programa en C# que: + +1. Carga un documento Word con recuperación relajada (para que los archivos corruptos no interrumpan la ejecución). +2. Lo exporta a Markdown, convirtiendo ecuaciones a LaTeX y almacenando imágenes mediante una devolución de llamada personalizada. +3. Guarda el mismo documento como un archivo compatible con PDF/UA‑2, incrustando formas flotantes como etiquetas en línea. + +¿Suena mucho? No hay problema—¡vamos a sumergirnos! + +## Lo que necesitarás + +- **Aspose.Words for .NET** (última versión, 23.x al momento de escribir). +- Un entorno de desarrollo .NET (Visual Studio 2022, Rider, o la CLI `dotnet`). +- Un archivo Word de ejemplo (`input.docx`) colocado en una carpeta a la que puedas hacer referencia. +- Familiaridad básica con la sintaxis de C#—nada exótico, solo unas cuantas sentencias `using`. + +> **Consejo profesional:** Si estás usando un gestor de paquetes NuGet, agrega la biblioteca con +> `dotnet add package Aspose.Words` o mediante la UI de NuGet de Visual Studio. + +## Paso 1 – Cargar el documento Word con recuperación relajada + +Cuando recibes archivos Word de fuentes externas pueden contener pequeñas corrupciones. Habilitar la recuperación **Relaxed** indica a Aspose.Words que continúe en lugar de lanzar una excepción. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Por qué es importante:** +- `RecoveryMode.Relaxed` evita que un solo párrafo malformado aborta toda la conversión. +- Proveer un objeto `FontSettings` asegura que cualquier fuente faltante sea sustituida de forma elegante, lo cual es crucial cuando luego renderizas ecuaciones como LaTeX. + +## Paso 2 – Exportar a Markdown (OfficeMath → LaTeX, Imágenes mediante Callback) + +Markdown no tiene una forma nativa de representar ecuaciones de Word. Aspose.Words puede traducir objetos **OfficeMath** a LaTeX, que la mayoría de los renderizadores de Markdown entienden. Las imágenes, sin embargo, deben guardarse en algún lugar; una **devolución de llamada de guardado de recursos** personalizada te brinda control total sobre la estructura de carpetas y los nombres. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### La devolución de llamada de guardado de recursos + +A continuación hay una pequeña implementación que almacena cada imagen en una subcarpeta llamada `images` y nombra los archivos `img001.png`, `img002.png`, etc. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Por qué necesitas esto:** +- Sin una devolución de llamada, Aspose.Words crea una carpeta plana con nombres GUID aleatorios, lo que complica el control de versiones. +- Al controlar el esquema de nombres mantienes el repositorio Markdown ordenado y reproducible. + +### Salida Markdown esperada + +Abre `doc.md` después de la ejecución y verás: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Las ecuaciones aparecen como LaTeX envueltas en `$$ … $$`, y las imágenes hacen referencia a la carpeta `images` que acabas de crear. + +## Paso 3 – Exportar a PDF/UA‑2 (Listo para accesibilidad) + +Si necesitas compartir el documento con usuarios que dependen de lectores de pantalla u otras tecnologías de asistencia, el cumplimiento de **PDF/UA‑2** es el estándar de oro. Aspose.Words puede imponer esto con una sola bandera, y también puede aplanar formas flotantes en etiquetas en línea para que no se pierdan durante la conversión. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Por qué PDF/UA es importante:** +- PDF/UA (Accesibilidad Universal) garantiza que el PDF resultante contenga etiquetado adecuado, orden lógico de lectura y texto alternativo para imágenes. +- Configurar `ExportFloatingShapesAsInlineTag` asegura que formas como cuadros de texto o llamadas de atención no se omitan o desplacen—una trampa común al convertir diseños complejos. + +### Verificando el cumplimiento de PDF/UA + +Después de la exportación, abre el PDF en Adobe Acrobat Pro y ejecuta **“Accessibility Check”** (Herramientas → Accesibilidad → Comprobación completa). Si la herramienta informa **0 errores**, lo has conseguido. + +## Casos límite y errores comunes + +| Situación | Qué observar | Solución / Recomendación | +|----------------------------------------|------------------------------------------------|------------------------------------------------------------| +| El archivo Word contiene **fuentes no compatibles** | Las fuentes pueden ser sustituidas, rompiendo el diseño de las ecuaciones | Proporciona un `FontSettings` personalizado con fuentes de respaldo. | +| Documentos grandes (> 100 MB) | Presión de memoria durante la conversión | Usa `LoadOptions` con `LoadFormat.Docx` y transmite el archivo. | +| Las imágenes son gráficos vectoriales **EMF/WMF** | Pueden rasterizarse de forma no intencional | Conviértelos a PNG mediante `ImageSaveOptions` antes de guardarlos. | +| PDF/UA falla la validación en **tablas anidadas** | El etiquetado puede volverse ambiguo | Activa `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` para ayudar al motor. | +| Necesitas **preservar estilos personalizados** | Markdown tiene capacidades de estilo limitadas | Exporta un archivo CSS junto al Markdown y haz referencia a él. | + +## Ejemplo completo (Todo el código junto) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Ejecuta el programa, y encontrarás tanto `doc.md` (con ecuaciones LaTeX y enlaces de imágenes limpios) como `doc.pdf` (totalmente compatible con PDF/UA‑2) ubicados en `YOUR_DIRECTORY`. + +## Visión general visual + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Texto alternativo:* **convert word to markdown example** – diagrama del flujo de conversión de un archivo Word a Markdown y PDF/UA. + +## Recapitulación y próximos pasos + +Acabamos de **convertir Word a Markdown** manteniendo las ecuaciones intactas, almacenar imágenes en una carpeta ordenada y producir un archivo **guardar como PDF/UA** que supera las verificaciones de accesibilidad. Los puntos clave son: + +- Usa `LoadOptions.RecoveryMode.Relaxed` para tolerar archivos Word imperfectos. +- Configura `OfficeMathExportMode` a `LaTeX` para una representación limpia de ecuaciones. +- Implementa un `ResourceSavingCallback` para controlar la salida de imágenes. +- Activa `PdfCompliance.PdfUAXmpA2` y `ExportFloatingShapesAsInlineTag` para un PDF conforme a los estándares. + +### ¿Qué explorar a continuación? + +- **CSS personalizado para Markdown** – genera una hoja de estilo que refleje los estilos de tu Word. +- **Procesamiento por lotes** – recorre un directorio de archivos `.docx` para automatizar migraciones masivas. +- **Funciones avanzadas de PDF/UA** – agrega etiquetas personalizadas, establece atributos de idioma o incrusta descripciones de audio. +- **Integración con CI/CD** – garantiza que cada compilación produzca PDFs accesibles automáticamente. + +Si encuentras un problema, verifica que la versión de Aspose.Words coincida con la API usada aquí, y recuerda que la documentación de la biblioteca es una referencia secundaria sólida. + +¡Feliz codificación, y que tus documentos permanezcan tanto hermosos **como** accesibles! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/programming-with-txtsaveoptions/_index.md b/words/spanish/net/programming-with-txtsaveoptions/_index.md index 8013c307cf..a0283410a5 100644 --- a/words/spanish/net/programming-with-txtsaveoptions/_index.md +++ b/words/spanish/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Gracias a estos tutoriales, podrá aprovechar al máximo las funcionalidades de | [Agregar marcas bidireccionales en un documento de Word](./add-bidi-marks/) Aprenda a agregar marcas bidireccionales (Bidi) en documentos de Word con Aspose.Words para .NET con esta guía. Asegúrese de que la dirección del texto sea correcta para contenido multilingüe. | [Usar carácter de tabulación por nivel para sangría de lista](./use-tab-character-per-level-for-list-indentation/) Aprenda a crear listas multinivel con sangría de tabulación usando Aspose.Words para .NET. Siga esta guía para un formato de lista preciso en sus documentos. | [Utilice el carácter de espacio por nivel para la sangría de la lista](./use-space-character-per-level-for-list-indentation/) Aprenda a crear listas multinivel con sangría de espacios en Aspose.Words para .NET. Guía paso a paso para un formato preciso de documentos. - +| [Guardar docx como txt – Exportar ecuaciones de Word a LaTeX con C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) Aprenda a exportar ecuaciones de Word a formato LaTeX al guardar documentos DOCX como archivos TXT usando C# y Aspose.Words. {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/spanish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..be5e9bac38 --- /dev/null +++ b/words/spanish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-04-05 +description: Guardar docx como txt con Aspose.Words – convierte rápidamente Word a + txt y aprende cómo exportar ecuaciones matemáticas como LaTeX. Código C# simple, + sin herramientas adicionales. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: es +og_description: Guarda docx como txt en C# y descubre cómo exportar matemáticas a + LaTeX. Sigue esta guía paso a paso para convertir Word a txt con ecuaciones intactas. +og_title: guardar docx como txt – Exportar ecuaciones de Word a LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: guardar docx como txt – Exportar ecuaciones de Word a LaTeX con C# +url: /es/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# guardar docx como txt – Exportar ecuaciones de Word a LaTeX con C# + +¿Alguna vez necesitaste **guardar docx como txt** pero temías que tus ecuaciones desaparecieran o se convirtieran en un galimatías ilegible? No eres el único. Muchos desarrolladores se topan con ese obstáculo cuando intentan **convertir word a txt** para procesamiento posterior, sobre todo cuando el archivo fuente contiene objetos Office Math. + +¿La buena noticia? Con unas pocas líneas de C# y las opciones correctas, puedes no solo **convertir Word a txt**, sino también mantener cada ecuación como marcado LaTeX limpio. En este tutorial recorreremos todo el proceso, explicaremos por qué cada configuración es importante y te mostraremos cómo verificar el resultado. + +Cubriremos: + +* Instalar la biblioteca Aspose.Words for .NET +* Cargar un `.docx` que contiene ecuaciones matemáticas +* Configurar `TxtSaveOptions` para que **cómo exportar matemáticas** se convierta en una cadena compatible con LaTeX +* Guardar el archivo y comprobar la salida + +Al final, tendrás un fragmento reutilizable que te permite **guardar docx como txt** preservando cada fórmula como LaTeX—perfecto para pipelines científicos, generadores de sitios estáticos o cualquier flujo de trabajo que necesite matemáticas en texto plano. + +--- + +## Requisitos previos + +Antes de sumergirnos, asegúrate de contar con: + +* .NET 6.0 o posterior (el código también funciona con .NET Framework 4.6+) +* Visual Studio 2022 (o cualquier IDE que prefieras) +* El paquete NuGet **Aspose.Words for .NET** – instálalo con + +```bash +dotnet add package Aspose.Words +``` + +No se requieren convertidores adicionales ni herramientas externas; Aspose.Words se encarga del trabajo pesado internamente. + +--- + +## Paso 1: Instalar y referenciar Aspose.Words + +Primero, agrega la biblioteca a tu proyecto. Si usas la línea de comandos, ejecuta el comando anterior. En Visual Studio también puedes hacer clic derecho en **Dependencies → Manage NuGet Packages** y buscar *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Consejo profesional:** Usa la versión estable más reciente (a partir de abril 2026 es la 24.10). Las versiones más nuevas incluyen correcciones de errores para el manejo de OfficeMath, por lo que evitarás símbolos ausentes inesperados. + +--- + +## Paso 2: Cargar el documento fuente + +Ahora cargamos el `.docx` que contiene las ecuaciones que deseas conservar. La clase `Document` abstrae todo el archivo Word, dándote acceso a texto, imágenes y objetos Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +¿Por qué cargarlo primero? Aspose.Words analiza el archivo y lo convierte en un modelo de objetos, lo que nos permite inspeccionar o modificar el contenido antes de decidir cómo exportarlo. Aquí es donde las decisiones sobre **cómo exportar matemáticas** comienzan a importar. + +--- + +## Paso 3: Configurar TxtSaveOptions para exportar a LaTeX + +El corazón de la solución es la clase `TxtSaveOptions`. Por defecto, al guardar en TXT se eliminan por completo los objetos Office Math. Establecer `OfficeMathExportMode` a `LaTeX` indica a la biblioteca que traduzca cada ecuación a su representación LaTeX. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**¿Por qué LaTeX?** LaTeX es la lingua franca de la publicación científica. Al exportar la matemática de esta forma, mantienes la semántica de la ecuación en lugar de una imagen plana o una cadena corrupta. Si más adelante alimentas el TXT a un procesador Markdown que soporte MathJax, las ecuaciones se renderizarán perfectamente. + +--- + +## Paso 4: Guardar el documento como texto plano + +Con las opciones configuradas, el paso final es una única línea que escribe el archivo en disco. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Eso es todo—tu `.docx` ahora es un archivo `.txt` donde cada ecuación aparece como un fragmento LaTeX, listo para su consumo posterior. + +--- + +## Verificando la salida (Cómo guardar txt correctamente) + +Abre `MathSample.txt` en cualquier editor de texto. Deberías ver algo como: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Si encuentras caracteres específicos de Word sin procesar (p. ej., `?` o símbolos faltantes), verifica que: + +* Estés usando una versión reciente de Aspose.Words (las versiones antiguas tenían errores con OfficeMath). +* El documento fuente realmente contenga objetos **OfficeMath**, no objetos heredados del Editor de Ecuaciones. Para estos últimos, quizá necesites convertirlos manualmente o usar el método `ConvertMathToOfficeMath` antes de guardar. + +--- + +## Variaciones comunes y casos límite + +| Situación | Qué hacer | +|-----------|-----------| +| **Objetos del Editor de Ecuaciones heredados** | Llama a `doc.ConvertMathToOfficeMath()` antes del paso 3. | +| **Necesitas matemáticas Unicode simples, no LaTeX** | Establece `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Documentos muy grandes (100 + MB)** | Usa la operación de guardado en streaming con `doc.Save(Stream, txtOptions)` para evitar un alto consumo de memoria. | +| **Quieres conservar el nombre original del archivo** | Usa `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` al construir la ruta de salida. | + +Estos ajustes responden a la pregunta “**cómo exportar matemáticas**” para diferentes pipelines, asegurando que tu solución sea robusta sin importar la fuente. + +--- + +## Ejemplo completo (Todos los pasos en un solo lugar) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Ejecuta el programa, abre el `.txt` generado y verás las ecuaciones LaTeX incrustadas justo donde correspondían. Esta es la forma más directa de **convertir + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/spanish/net/working-with-fonts/_index.md b/words/spanish/net/working-with-fonts/_index.md index 7e48c7dc00..963e1a1e26 100644 --- a/words/spanish/net/working-with-fonts/_index.md +++ b/words/spanish/net/working-with-fonts/_index.md @@ -39,7 +39,7 @@ Ya sea que desee formatear texto con diferentes fuentes, establecer reglas de su | [Establecer carpetas de fuentes del sistema y carpetas personalizadas](./set-fonts-folders-system-and-custom-folder/) Aprenda a configurar carpetas de fuentes personalizadas y del sistema en documentos de Word usando Aspose.Words para .NET, garantizando que sus documentos se muestren correctamente en diferentes entornos. | | [Establecer carpetas de fuentes con prioridad](./set-fonts-folders-with-priority/) Aprenda a configurar carpetas de fuentes con prioridad en documentos de Word con Aspose.Words para .NET. Nuestra guía garantiza que sus documentos se visualicen perfectamente en todo momento. | [Establecer carpeta de fuentes True Type](./set-true-type-fonts-folder/) Aprenda a configurar una carpeta de fuentes True Type en documentos de Word con Aspose.Words para .NET. Siga nuestra guía detallada paso a paso para garantizar una gestión de fuentes consistente. -| [Especificar la fuente predeterminada al renderizar](./specify-default-font-when-rendering/) Aprenda a especificar una fuente predeterminada al renderizar documentos de Word con Aspose.Words para .NET. Asegúrese de que la apariencia de los documentos sea uniforme en todas las plataformas. +| [Especificar la fuente predeterminada al renderizar](./specify-default-font-when-rendering/) Aprende a especificar una fuente predeterminada al renderizar documentos de Word con Aspose.Words para .NET. Asegúrese de que la apariencia de los documentos sea uniforme en todas las plataformas. | [Configuración de fuente con opciones de carga](./font-settings-with-load-options/) Aprenda a administrar la configuración de fuentes con las opciones de carga en Aspose.Words para .NET. Guía paso a paso para desarrolladores que garantiza una apariencia uniforme de las fuentes en documentos de Word. | [Establecer carpeta de fuentes](./set-fonts-folder/) | Aprenda a configurar una carpeta de fuentes personalizadas en Aspose.Words para .NET para garantizar que sus documentos de Word se representen correctamente sin fuentes faltantes. | | [Configuración de fuente Instancia predeterminada](./font-settings-default-instance/) | En este tutorial, aprenda a configurar la configuración de fuente predeterminada en un documento de Word con Aspose.Words para .NET. @@ -48,7 +48,7 @@ Ya sea que desee formatear texto con diferentes fuentes, establecer reglas de su | [Recibir notificación de advertencia](./receive-warning-notification/) Aprenda cómo recibir una notificación de advertencia al usar Aspose.Words para .NET y administrar cualquier problema o advertencia en sus documentos. | | [Ejemplo de fuente de recurso de Steam](./resource-steam-font-source-example/) | Aprenda a utilizar la fuente de flujo de recursos para cargar fuentes personalizadas en Aspose.Words para .NET. | | [Obtener sustitución sin sufijos](./get-substitution-without-suffixes/) | En este tutorial, aprenda cómo obtener anulaciones sin sufijos en un documento de Word con Aspose.Words para .NET. - +| [Sustitución de fuentes Aspose – Detectar fuentes faltantes en documentos de Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Aprenda a detectar fuentes faltantes en documentos de Word con Aspose.Words para .NET mediante la sustitución de fuentes. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/spanish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/spanish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..a0cdacef9f --- /dev/null +++ b/words/spanish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,216 @@ +--- +category: general +date: 2026-04-05 +description: Guía de sustitución de fuentes de Aspose para detectar fuentes faltantes + al cargar un documento de Word. Aprende a configurar la configuración de fuentes + y a manejar las fuentes faltantes de manera eficiente. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: es +og_description: Guía de sustitución de fuentes de Aspose para detectar fuentes faltantes + al cargar un documento de Word. Aprende a configurar la configuración de fuentes + y a manejar las fuentes faltantes de manera eficiente. +og_title: Sustitución de fuentes Aspose – Detectar fuentes faltantes en documentos + Word +tags: +- Aspose.Words +- C# +- Font Management +title: Sustitución de fuentes Aspose – Detectar fuentes faltantes en documentos Word +url: /es/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Sustitución de fuentes Aspose – Detectar fuentes faltantes en documentos Word + +¿Alguna vez te has encontrado con un archivo Word que se ve perfecto en una máquina pero muestra extraños cambios de fuente en otra? Ese es el clásico problema de **aspose font substitution**, y normalmente significa que faltan algunas fuentes en el sistema de destino. En este tutorial te mostraremos, paso a paso, cómo **detectar fuentes faltantes** al **cargar un documento Word**, cómo **configurar la configuración de fuentes**, y qué hacer para **manejar fuentes faltantes** de forma elegante. + +Recorreremos un ejemplo completo y ejecutable en C#, explicaremos por qué cada línea es importante e incluso te mostraremos la salida de consola que deberías obtener. Al final podrás detectar sustituciones de fuentes en el momento en que se carga un documento, sin necesidad de adivinar. + +## Lo que aprenderás + +- Cómo habilitar el recopilador diagnóstico de Aspose.Words para advertencias de fuentes. +- El código exacto necesario para **cargar un documento Word** con **configuración de fuentes** personalizada. +- Cómo iterar sobre objetos `WarningInfo` para enumerar cada fuente sustituida. +- Consejos para suprimir advertencias no deseadas o proporcionar fuentes de respaldo. +- Un ejemplo listo para ejecutar que puedes copiar y pegar en Visual Studio. + +### Requisitos previos + +- .NET 6.0 o posterior (la API funciona igual en .NET Framework). +- Aspose.Words para .NET (paquete NuGet `Aspose.Words`). +- Un archivo Word que haga referencia a una fuente que no tienes instalada (p. ej., `MissingFont.docx`). + +Si tienes todo eso, vamos a sumergirnos. + +## Paso 1 – Habilitar el recopilador diagnóstico (Configurar la configuración de fuentes) + +Primero lo primero: Aspose.Words solo registra advertencias de sustitución de fuentes si se lo indicas. Esto se hace creando un objeto `FontSettings` y asignándolo a una instancia de `LoadOptions`. Piensa en esto como encender las “luces de depuración” para el manejo de fuentes. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**¿Por qué?** +Sin un objeto `FontSettings` el recopilador de advertencias permanece silencioso, y nunca sabrás qué fuentes fueron sustituidas. Al inicializarlo vacío permitimos que Aspose use las fuentes predeterminadas del sistema *y* haga un seguimiento de cualquier sustitución. + +> **Consejo profesional:** Si sabes que una carpeta específica contiene fuentes corporativas, indica esa carpeta a `FontSettings` con `SetFontsFolder("ruta")`. Eso puede reducir la cantidad de advertencias de fuentes faltantes. + +## Paso 2 – Cargar el documento con las opciones configuradas (Cargar documento Word) + +Ahora que el recopilador está activo, carga tu archivo `.docx` usando el mismo `LoadOptions`. Este es el momento en que Aspose escanea el documento, busca cada referencia de fuente y decide si se necesita una sustitución. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**¿Por qué es importante?** +Si simplemente llamas a `new Document("MissingFont.docx")`, se aplicarían los ajustes predeterminados *y* la lista de advertencias permanecería vacía. Pasar `loadOptions` garantiza que el recopilador diagnóstico esté conectado al proceso de carga. + +## Paso 3 – Recuperar y mostrar advertencias de sustitución de fuentes (Detectar fuentes faltantes) + +Después de que el documento está en memoria, Aspose almacena cualquier advertencia en `document.WarningCallback.Warnings`. Recorre esa colección, filtra por `WarningType.FontSubstitution` y muestra la descripción. Cada descripción te indica qué fuente faltaba y cuál se utilizó en su lugar. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Salida esperada de la consola** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +![Salida de consola que muestra advertencias de sustitución de fuentes Aspose](/images/aspose-font-substitution-console.png) + +*Texto alternativo de la imagen:* sustitución de fuentes Aspose – salida de consola que enumera las fuentes sustituidas + +## Paso 4 – Opcional: Personalizar el comportamiento de sustitución (Manejar fuentes faltantes) + +A veces no solo quieres saber *que* ocurrió una sustitución, sino controlar *cómo* ocurre. Aspose.Words te permite registrar una regla personalizada `IFontSubstitutionRule`. A continuación hay un ejemplo rápido que fuerza a cualquier fuente faltante a usar `Tahoma` como respaldo. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**¿Cuándo usarías esto?** +Si estás generando PDFs para un servicio web y sabes que todos los clientes pueden renderizar `Tahoma`, forzar el respaldo garantiza consistencia visual sin tener que distribuir decenas de archivos de fuentes. + +## Ejemplo completo funcional (Todos los pasos combinados) + +Aquí tienes el programa completo que puedes pegar en un nuevo proyecto de consola. Compila tal cual, asumiendo que has instalado el paquete NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Ejecuta el programa, observa la consola y verás cada evento de fuente faltante impreso. A partir de ahí puedes decidir si instalar las fuentes faltantes, incrustarlas o mantener el respaldo. + +## Preguntas frecuentes + +**P: ¿Esto funciona con la conversión a PDF?** +Sí. Cuando luego llames a `doc.Save("output.pdf")`, cualquier fuente que haya sido sustituida durante la carga será la que se incruste en el PDF. Por lo tanto, capturar las advertencias temprano te ayuda a evitar cambios de fuente inesperados en el PDF final. + +**P: ¿Qué pasa si tengo muchos documentos para procesar?** +Envuelve la lógica de carga en un bloque try‑catch y reutiliza una única instancia de `FontSettings` para varios documentos. Eso reduce la sobrecarga y mantiene activo el recopilador de advertencias para cada archivo. + +**P: ¿Puedo suprimir completamente las advertencias?** +Puedes establecer `loadOptions.WarningCallback = null;` antes de cargar, pero perderás la capacidad de **detectar fuentes faltantes**, lo cual usualmente no es lo que deseas. + +## Conclusión + +Hemos cubierto todo lo que necesitas para dominar la **aspose font substitution**: habilitar el recopilador diagnóstico, cargar un archivo Word con **configuración de fuentes** personalizada, extraer la lista de fuentes faltantes e incluso sobrescribir la regla de sustitución predeterminada para **manejar fuentes faltantes** a tu manera. Con solo unas pocas líneas de C# obtienes una visibilidad completa de los problemas de fuentes que de otro modo estarían ocultos tras sutiles cambios de diseño. + +¿Próximos pasos? Intenta incrustar las fuentes originales en el documento con `FontSettings.SetFontsFolder` o explora `FontSourceBase` para cargar fuentes desde una base de datos. También podrías experimentar con la colección `Document.BuiltInStyle` para ver cómo se propagan los cambios de fuente a nivel de estilo. + +¿Tienes más preguntas sobre Aspose.Words o la gestión de fuentes? Deja un comentario, explora la documentación oficial de Aspose o crea un nuevo proyecto y juega con el código anterior. ¡Feliz codificación, y que tus documentos siempre se rendericen exactamente como deseas! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/basic-conversions/_index.md b/words/swedish/net/basic-conversions/_index.md index 3ae482bcd8..e2e9ab3280 100644 --- a/words/swedish/net/basic-conversions/_index.md +++ b/words/swedish/net/basic-conversions/_index.md @@ -34,6 +34,7 @@ Grundläggande konverteringar guidar dig genom grundläggande dokumentkonverteri | [Spara PDF till Word-format (Docx)](./pdf-to-docx/) | Lär dig hur du konverterar en PDF till ett Word-dokument (Docx) med Aspose.Words för .NET i den här detaljerade steg-för-steg-guiden. Perfekt för utvecklare. | | [Exportera LaTeX från Word – steg‑för‑steg‑guide](./how-to-export-latex-from-word-step-by-step-guide/) | Lär dig hur du exporterar LaTeX från ett Word-dokument med Aspose.Words för .NET i en tydlig steg‑för‑steg‑guide. | | [Konvertera Word till PDF i C# med Aspose.Words – Guide](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Lär dig hur du konverterar Word-dokument till PDF i C# med Aspose.Words. Steg‑för‑steg‑guide med kodexempel. | +| [Konvertera Word till PDF i C# – Fullständig guide med Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Lär dig hur du konverterar Word-dokument till PDF i C# med Aspose.Words i en komplett steg‑för‑steg‑guide. | | [Spara Word som PDF med Aspose.Words – Komplett C#-guide](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Lär dig hur du sparar Word-dokument som PDF med Aspose.Words i C#. Steg‑för‑steg‑guide med kodexempel. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/swedish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..1e1e5f0847 --- /dev/null +++ b/words/swedish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,195 @@ +--- +category: general +date: 2026-04-05 +description: Konvertera Word till PDF i C# med Aspose.Words. Lär dig hur du sparar + docx som PDF, exporterar en tillgänglig PDF och laddar Word‑dokument effektivt. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: sv +og_description: Konvertera Word till PDF i C# med en steg‑för‑steg‑guide. Upptäck + hur du sparar docx som PDF, exporterar tillgänglig PDF och laddar Word‑dokument + med Aspose.Words. +og_title: Konvertera Word till PDF i C# – Komplett Aspose.Words-handledning +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Konvertera Word till PDF i C# – Fullständig guide med Aspose.Words +url: /sv/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera Word till PDF i C# – Komplett programmeringshandledning + +Har du någonsin undrat hur man **konvertera word till pdf** utan att kämpa med krångliga kommandoradsverktyg eller tredjepartstjänster? Du är inte ensam. Många utvecklare stöter på detta när en kund begär en tillgänglig PDF direkt från en DOCX‑fil. Den goda nyheten? Med några rader C# och det kraftfulla Aspose.Words‑biblioteket kan du förvandla ett Word‑dokument till en standard‑kompatibel PDF på ett ögonblick. + +I den här guiden går vi igenom allt du behöver veta: från grunderna för **load word document**, genom att konfigurera rätt alternativ till **how to export accessible pdf**, och slutligen spara resultatet så att du kan **save docx as pdf** på ett pålitligt sätt. I slutet har du ett färdigt kodexempel som du kan lägga in i vilket .NET‑projekt som helst. + +> **Proffstips:** Om du siktar på PDF/UA‑2‑kompatibilitet (tillgänglighetsstandarden som många myndigheter kräver), fungerar samma kod utan några extra steg – bara sätt rätt `PdfCompliance`‑flagga. + +## Vad du kommer att lära dig + +- Hur man **load word document** med Aspose.Words i C#. +- De exakta inställningarna som behövs för att **how to export accessible pdf** (PDF/UA‑2). +- Ett komplett, körbart exempel som **save docx as pdf** med ett metodanrop. +- Vanliga fallgropar när du **c# convert docx pdf** och hur du undviker dem. +- Snabba sätt att verifiera att den genererade PDF‑filen uppfyller tillgänglighetskraven. + +Inga externa verktyg, inga kryptiska konfigurationsfiler – bara ren C#‑kod som du kan kompilera idag. + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +1. **.NET 6.0** (eller någon nyare .NET‑version) installerad. Äldre ramverk fungerar också, men syntaxen nedan förutsätter det moderna SDK‑et. +2. En **license** för Aspose.Words for .NET. Biblioteket erbjuder en gratis provperiod, men för produktion behöver du en giltig nyckel. +3. **Aspose.Words**‑NuGet‑paketet tillagt i ditt projekt: + +```bash +dotnet add package Aspose.Words +``` + +Det är allt – inga extra binärer, ingen COM‑interop, bara en ren NuGet‑referens. + +![konvertera word till pdf med Aspose.Words i C#](image-placeholder.png "konvertera word till pdf med Aspose.Words i C#") + +## Steg‑för‑steg‑implementering + +Nedan delar vi upp processen i logiska delar. Varje steg innehåller ett litet kodexempel, en förklaring till **varför** det är viktigt, och ett tips från verklig användning. + +### ## Konvertera Word till PDF – Ladda källdokumentet + +Det första du behöver göra är att **load word document** i minnet. Aspose.Words abstraherar bort OpenXML‑parsing, så du kan arbeta med DOCX-, DOC- eller till och med RTF‑filer utan att oroa dig för format‑egenskaper. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Varför detta är viktigt:** +Att ladda filen skapar ett `Document`‑objekt som representerar hela Word‑filen, inklusive sidhuvuden, sidfötter, stilar och dold metadata. Om du hoppar över detta steg eller försöker läsa filen som en råström, förlorar du layout‑informationen som senare avgör hur PDF‑filen ser ut. + +> **Sidnotering:** Samma `Document`‑konstruktor fungerar för `.doc` och `.rtf`. Det betyder att du kan **c# convert docx pdf** även när källan inte strikt är en DOCX. + +### ## Spara DOCX som PDF – Konfigurera PDF/UA‑2‑kompatibilitet + +Nu när dokumentet är i minnet, talar vi om för Aspose.Words hur vi vill att PDF‑filen ska genereras. För de flesta användningsfall är standardinställningarna tillräckliga, men när du behöver en **accessible PDF** måste du aktivera PDF/UA‑2‑kompatibilitetsflaggan. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Varför detta är viktigt:** +`PdfCompliance.PdfUAXmpA2` instruerar biblioteket att bädda in de nödvändiga taggarna och strukturerna som skärmläsare förlitar sig på. Utan denna flagga kan du få en PDF som ser perfekt ut men som misslyckas i en tillgänglighetsgranskning. + +> **Tips:** Om du bara behöver en vanlig PDF kan du ta bort `Compliance`‑raden. Resten av alternativen ger fortfarande ett högkvalitativt resultat. + +### ## Konvertera Word till PDF – Skriv filen + +Med alternativen klara är sista steget att **save docx as pdf**. Detta enda anrop sköter allt tungt arbete: layoutkonvertering, teckensnittsinbäddning och tillgänglighetstaggar. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Vad du får:** +- En PDF‑fil på `outputPath` som speglar Word‑layouten. +- Om du använde `PdfUAXmpA2`‑flaggan kommer PDF‑filen att vara markerad som PDF/UA‑2‑kompatibel. +- Alla teckensnitt är inbäddade, så filen ser identisk ut på vilken maskin som helst. + +### ## Verifiera den tillgängliga PDF‑filen (Valfritt men rekommenderat) + +Efter konverteringen är det en bra idé att dubbelkolla att PDF‑filen verkligen **how to export accessible pdf** korrekt. Du kan använda gratisverktyg som Adobe Acrobat Readers “Accessibility Check” eller den öppna källkods‑validatorn `pdfcpu`. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Om validatorn rapporterar inga fel har du lyckats **convert word to pdf** med fullt stöd för tillgänglighet. + +### ## Vanliga fallgropar när du C# konverterar DOCX till PDF + +| Problem | Varför det händer | Lösning | +|-------|----------------|-----| +| Missing fonts | Käll‑DOCX använder ett anpassat teckensnitt som inte är installerat på servern. | Sätt `EmbedFullFonts = true` eller installera teckensnittet på maskinen. | +| Large file size | Bilder är inbäddade i full upplösning. | Använd `ImageCompression = PdfImageCompression.Jpeg` och sätt `JpegQuality` till ett lägre värde. | +| Broken hyperlinks | Länkar pekar på relativa sökvägar som inte finns på klienten. | Säkerställ att URL:er är absoluta eller justera `HyperlinkTarget`‑egenskapen. | +| Accessibility tags missing | `Compliance`‑flaggan är inte satt. | Lägg till `Compliance = PdfCompliance.PdfUAXmpA2` som visas ovan. | + +Att ha dessa i åtanke gör att din **c# convert docx pdf**‑rutin blir robust och produktionsklar. + +## Fullt fungerande exempel + +När allt sätts ihop, här är en fristående konsolapp som du kan kompilera och köra direkt. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Förväntat resultat:** Efter att programmet har körts hittar du `output.pdf` i `C:\Docs`. Öppna den i någon PDF‑visare; layouten bör matcha `input.docx` pixel‑för‑pixel, och en tillgänglighetskontroll kommer att bekräfta PDF/UA‑2‑kompatibilitet. + +## Slutsats + +Vi har just gått igenom en komplett, helhetslösning för hur man **convert word to pdf** med C# och Aspose.Words. Genom att **load word document**, konfigurera rätt `PdfSaveOptions` och slutligen **save docx as pdf**, får du en högkvalitativ, tillgänglig PDF med minimal kod. Oavsett om du bygger en dokument‑genererings‑mikrotjänst, en lokalt installerad batch‑konverterare, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-markdownsaveoptions/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/_index.md index ccb402999a..151b3f564c 100644 --- a/words/swedish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/swedish/net/programming-with-markdownsaveoptions/_index.md @@ -39,7 +39,7 @@ Lär dig konvertera DOCX-filer till Markdown med en detaljerad steg‑för‑ste Lär dig spara DOCX-filer som Markdown med en komplett C#-guide som inkluderar LaTeX‑ekvationer. ### [Spara docx som markdown – Fullständig C#-guide med bildextraktion](./save-docx-as-markdown-full-c-guide-with-image-extraction/) -Lär dig spara DOCX-filer som Markdown och extrahera bilder med en komplett C#-guide. +Lär dig spara DOCX som Markdown och extrahera bilder med en komplett C#-guide. ### [Hur man exporterar Markdown från Word – Fullständig C#-guide](./how-to-export-markdown-from-word-complete-c-guide/) Lär dig exportera Word-dokument till Markdown med en komplett C#‑guide som täcker alla steg. @@ -50,6 +50,11 @@ Lär dig spara DOCX som Markdown med en detaljerad steg‑för‑steg‑guide i ### [Hur man exporterar Markdown från DOCX – Fullständig guide](./how-to-export-markdown-from-docx-complete-guide/) Lär dig exportera Markdown från DOCX-filer med en komplett guide i C#. +### [Konvertera DOCX till Markdown – Extrahera bilder från DOCX med Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) +Lär dig hur du extraherar bilder från DOCX när du konverterar till Markdown med Aspose.Words för .NET. + +### [Konvertera Word till Markdown – Fullständig guide med PDF/UA-export](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..33dd24f997 --- /dev/null +++ b/words/swedish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: Lär dig hur du konverterar DOCX till Markdown och extraherar bilder från + DOCX i C#. Steg‑för‑steg‑guide med fullständig kod och tips. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: sv +og_description: Konvertera DOCX till Markdown och extrahera bilder från DOCX med Aspose.Words. + Komplett C#‑handledning med kod, förklaring och bästa‑praxis‑tips. +og_title: Konvertera DOCX till Markdown – Extrahera bilder från DOCX i C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Konvertera DOCX till Markdown – Extrahera bilder från DOCX med Aspose.Words +url: /sv/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera DOCX till Markdown – Extrahera bilder från DOCX i C# + +Har du någonsin behövt **konvertera DOCX till Markdown** men kämpat med att bilderna försvinner i resultatet? Du är inte ensam. I många projekt är markdown‑versionen perfekt för versionskontroll eller statiska webbplatsgeneratorer, men bilderna blir kvar, vilket förvandlar ett rikt dokument till en karg textfil. + +Den goda nyheten? Med några rader C# och Aspose.Words kan du **konvertera DOCX till Markdown** *och* **extrahera bilder från DOCX** automatiskt. Den här guiden går igenom hela processen, förklarar varför varje del är viktig och visar även hur du håller din bildmapp organiserad. + +## Vad du kommer att lära dig + +- Hur du laddar ett DOCX som innehåller bilder. +- Hur du definierar en anpassad `IResourceSavingCallback` som bestämmer var varje bild sparas. +- Hur du konfigurerar `MarkdownSaveOptions` så att den genererade markdown‑filen refererar till de extraherade bilderna korrekt. +- Tips för att hantera kantfall som duplicerade bildnamn eller format som inte är PNG. +- Ett komplett, kopiera‑och‑klistra‑klart kodexempel som du kan köra idag. + +### Förutsättningar + +- .NET 6.0 eller senare (API‑et fungerar på .NET Core, .NET Framework och .NET 5+). +- En licens för **Aspose.Words for .NET** (gratis provversion fungerar för testning). +- Grundläggande kunskap om C# och Visual Studio (eller din favorit‑IDE). + +Om du har dem, låt oss dyka ner. + +--- + +## Steg 1: Ställ in projektet och installera Aspose.Words + +First, create a new console app (or integrate into an existing solution). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro tip:** Use the latest NuGet version (as of April 2026 it’s 24.12) to get the newest markdown export improvements. + +--- + +## Steg 2: Skapa en callback för att spara bilder där du vill ha dem + +Aspose.Words lets you intercept every resource (images, SVGs, etc.) that gets written during the markdown export. By implementing `IResourceSavingCallback` you can: + +1. Choose a folder that lives next to your markdown file. +2. Generate a unique filename (so you never overwrite an existing image). +3. Decide the format (here we force PNG for consistency). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Varför ett GUID‑baserat namn? + +If the source DOCX contains two pictures with the same original name, a simple copy‑paste would overwrite one of them. Using `Guid.NewGuid()` guarantees uniqueness, which is especially handy when you run the conversion many times in an automated pipeline. + +--- + +## Steg 3: Ladda DOCX‑filen och anslut Markdown‑alternativen + +Now we bring the document into memory and attach the callback we just built. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Vad koden gör, steg för steg + +| Steg | Syfte | +|------|-------| +| **Define paths** | Keeps your project flexible; you can point to any folder without recompiling. | +| **Load the DOCX** | `Document` parses the Word file, making all elements (paragraphs, tables, pictures) accessible. | +| **Configure `MarkdownSaveOptions`** | The `ResourceSavingCallback` is the hook that extracts images. Without it, Aspose.Words would embed the images as base64 strings or drop them entirely, depending on settings. | +| **Save** | `doc.Save` writes the markdown file and triggers the callback for each image. | + +--- + +## Steg 4: Verifiera resultatet – Vad bör du se? + +After running the program, open `DocWithImages.md`. You’ll notice markdown image links that look like this: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +And in `C:\Docs\MarkdownResources` you’ll find a series of PNG files with GUID names. Open any of them – they should be identical to the pictures that were embedded in the original DOCX. + +If you open the markdown file in a viewer that respects relative paths (e.g., VS Code preview, GitHub, or a static‑site generator), the images will render just as they did in Word. + +### Vanliga fallgropar & hur du undviker dem + +| Symptom | Trolig orsak | Lösning | +|---------|--------------|---------| +| Images appear as broken links | The `ResourceFileName` wasn’t set, so the markdown points to a non‑existent file. | Ensure `args.ResourceFileName = newFileName;` inside the callback. | +| PNG files are huge | Original images were JPEG or BMP; converting to PNG can increase size. | Detect the original format via `args.ResourceContentType` and preserve it: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Duplicate images still appear | You used a static filename instead of a GUID. | Switch back to GUID logic or add a counter per image type. | +| Conversion throws `FileNotFoundException` | The source DOCX path is wrong or the folder lacks read permission. | Verify the path and grant appropriate file‑system rights. | + +--- + +## Steg 5: Avancerade justeringar (valfritt) + +### 5.1 Bevara originala bildformat + +If you want the output images to keep their original extensions, modify the callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Bädda in bilder som Base64 (när du *inte* vill ha separata filer) + +Sometimes a single‑file markdown is preferable (e.g., for sending via email). Change the option: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +But remember: **extract images from DOCX** is the primary goal for most static‑site workflows, so the folder approach is usually the better choice. + +--- + +## Fullt fungerande exempel (Kopiera‑klistra‑klart) + +Below is the entire program in one file. Just replace the paths with your own and run. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Run it with `dotnet run`. When the console prints the ✅ line, open the markdown file and you should see the images rendered correctly. + +--- + +## Slutsats + +You now have a **complete, production‑ready solution to convert DOCX to Markdown and extract images from DOCX** using Aspose.Words in C#. The primary keyword appears throughout the guide, reinforcing relevance for both search engines and AI assistants. + +In a single pass the code: + +1. Loads a Word document. +2. Intercepts every image via `IResourceSavingCallback`. +3. Saves each image to a predictable folder with a unique name. +4. Generates markdown that references those images. + +From here you can: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/swedish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..9948261449 --- /dev/null +++ b/words/swedish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-04-05 +description: Konvertera Word till Markdown snabbt och lär dig även hur du sparar som + PDF/UA i C#. Steg‑för‑steg‑kod, tips och hantering av speciella fall. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: sv +og_description: Konvertera Word till Markdown och spara som PDF/UA med Aspose.Words. + Lär dig varför, hur och bästa praxis‑tips i en kortfattad guide. +og_title: Konvertera Word till Markdown – Komplett C#‑handledning +tags: +- Aspose.Words +- C# +- Document Conversion +title: Konvertera Word till Markdown – Fullständig guide med PDF/UA‑export +url: /sv/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera Word till Markdown – Fullständig guide med PDF/UA‑export + +Har du någonsin undrat hur man **konverterar Word till Markdown** utan att förlora ekvationer eller bilder? Du är inte ensam. Många utvecklare behöver ett pålitligt sätt att omvandla `.docx`‑filer till ren Markdown samtidigt som de kan **spara som PDF/UA** för tillgänglighets‑kompatibla PDF‑filer. I den här handledningen går vi igenom en komplett, färdig‑körbar lösning med Aspose.Words för .NET, förklarar varför varje inställning är viktig och visar hur du hanterar de knepigare delarna som OfficeMath och flytande former. + +1. Laddar ett Word‑dokument med avslappnad återhämtning (så att korrupta filer inte avbryter körningen). +2. Exporterar det till Markdown, omvandlar ekvationer till LaTeX och sparar bilder via en anpassad callback. +3. Sparar samma dokument som en PDF/UA‑2‑kompatibel fil, där flytande former bäddas in som inline‑taggar. + +Låter som mycket? Ingen fara—låt oss dyka ner. + +## Vad du behöver + +- **Aspose.Words for .NET** (senaste versionen, 23.x vid skrivande). +- En .NET‑utvecklingsmiljö (Visual Studio 2022, Rider eller `dotnet`‑CLI). +- En exempel‑Word‑fil (`input.docx`) placerad i en mapp du kan referera till. +- Grundläggande kunskap om C#‑syntax—inget exotiskt, bara några `using`‑satser. + +> **Proffstips:** Om du använder en NuGet‑pakethanterare, lägg till biblioteket med +> `dotnet add package Aspose.Words` eller via Visual Studio NuGet‑UI. + +## Steg 1 – Ladda Word‑dokumentet med avslappnad återhämtning + +När du får Word‑filer från externa källor kan de innehålla mindre korruption. Att aktivera **Relaxed**‑återhämtning instruerar Aspose.Words att fortsätta istället för att kasta ett undantag. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Varför detta är viktigt:** +- `RecoveryMode.Relaxed` förhindrar att ett enda felaktigt stycke avbryter hela konverteringen. +- Att tillhandahålla ett `FontSettings`‑objekt säkerställer att eventuella saknade teckensnitt ersätts på ett smidigt sätt, vilket är avgörande när du senare renderar ekvationer som LaTeX. + +## Steg 2 – Exportera till Markdown (OfficeMath → LaTeX, bilder via callback) + +Markdown har inget inbyggt sätt att representera Word‑ekvationer. Aspose.Words kan översätta **OfficeMath**‑objekt till LaTeX, vilket de flesta Markdown‑renderare förstår. Bilder däremot måste sparas någonstans; en anpassad **resource‑saving callback** ger dig full kontroll över mappstrukturen och namngivningen. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Resurs‑sparande callbacken + +Nedan är en liten implementation som lagrar varje bild i en undermapp som heter `images` och namnger filerna `img001.png`, `img002.png` osv. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Varför du behöver detta:** +- Utan en callback skapar Aspose.Words en platt mapp med slumpmässiga GUID‑namn, vilket gör versionskontrollen rörig. +- Genom att kontrollera namngivningsschemat håller du Markdown‑arkivet prydligt och reproducerbart. + +### Förväntad Markdown‑output + +Öppna `doc.md` efter körningen så ser du: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Ekvationer visas som LaTeX omslutna av `$$ … $$`, och bilder refererar till `images`‑mappen du just skapade. + +## Steg 3 – Exportera till PDF/UA‑2 (tillgänglighets‑klar) + +Om du behöver dela dokumentet med användare som förlitar sig på skärmläsare eller annan hjälpmedelsteknik, är **PDF/UA‑2**‑kompatibilitet guldstandarden. Aspose.Words kan verkställa detta med en enda flagga, och den kan också platta till flytande former till inline‑taggar så att de inte går förlorade under konverteringen. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Varför PDF/UA är viktigt:** +- PDF/UA (Universal Accessibility) garanterar att den resulterande PDF‑filen innehåller korrekt taggning, logisk läsordning och alternativ text för bilder. +- Inställningen `ExportFloatingShapesAsInlineTag` säkerställer att former som textrutor eller anmärkningar inte utelämnas eller placeras fel – ett vanligt fallgropp vid konvertering av komplexa layouter. + +### Verifiera PDF/UA‑kompatibilitet + +Efter exporten, öppna PDF‑filen i Adobe Acrobat Pro och kör **“Accessibility Check”** (Verktyg → Tillgänglighet → Full kontroll). Om verktyget rapporterar **0 fel**, har du lyckats. + +## Kantfall & vanliga fallgropar + +| Situation | Vad att hålla utkik efter | Åtgärd / Rekommendation | +|----------------------------------------|------------------------------------------------------|----------------------------------------------------------| +| Word‑fil innehåller **unsupported fonts** | Teckensnitt kan ersättas, vilket förstör ekvationslayouten | Tillhandahåll ett anpassat `FontSettings` med reservteckensnitt. | +| Stora dokument (> 100 MB) | Minnesbelastning under konverteringen | Använd `LoadOptions` med `LoadFormat.Docx` och strömfilen. | +| Bilder är **EMF/WMF** vektorgrafik | De kan rasteriseras oavsiktligt | Konvertera dem till PNG via `ImageSaveOptions` innan sparning. | +| PDF/UA misslyckas med validering på **nested tables** | Taggning kan bli tvetydig | Aktivera `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` för att hjälpa motorn. | +| Behöver **preserve custom styles** | Markdown har begränsade stilmöjligheter | Exportera en CSS‑fil tillsammans med Markdown och referera den. | + +## Fullt fungerande exempel (All kod tillsammans) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Kör programmet, så hittar du både `doc.md` (med LaTeX‑ekvationer och rena bildlänkar) och `doc.pdf` (fullt PDF/UA‑2‑kompatibel) i `YOUR_DIRECTORY`. + +## Visuell översikt + +![konvertera word till markdown exempel](https://example.com/placeholder.png "konvertera word till markdown exempel – visar input Word, Markdown‑output och PDF/UA‑fil") + +*Alt‑text:* **konvertera word till markdown exempel** – diagram över konverteringspipeline från en Word‑fil till Markdown och PDF/UA. + +## Sammanfattning & nästa steg + +Vi har just **konverterat Word till Markdown** samtidigt som ekvationerna behålls intakta, lagrat bilder i en prydlig mapp och skapat en **spara som PDF/UA**‑fil som klarar tillgänglighetskontroller. De viktigaste slutsatserna är: + +- Använd `LoadOptions.RecoveryMode.Relaxed` för att tolerera ofullständiga Word‑filer. +- Ställ in `OfficeMathExportMode` till `LaTeX` för ren ekvationsrendering. +- Implementera en `ResourceSavingCallback` för att kontrollera bildutdata. +- Aktivera `PdfCompliance.PdfUAXmpA2` och `ExportFloatingShapesAsInlineTag` för en standard‑kompatibel PDF. + +### Vad du kan utforska härnäst? + +- **Anpassad CSS för Markdown** – generera ett stilblad som speglar dina Word‑stilar. +- **Batch‑behandling** – loopa över en katalog med `.docx`‑filer för att automatisera stora migrationer. +- **Avancerade PDF/UA‑funktioner** – lägg till anpassade taggar, sätt språk‑attribut eller bädda in ljudbeskrivningar. +- **Integration med CI/CD** – säkerställ att varje byggnad producerar tillgängliga PDF‑filer automatiskt. + +Om du stöter på problem, dubbelkolla att din Aspose.Words‑version matchar det API som används här, och kom ihåg att bibliotekets egna dokumentation är en bra sekundär referens. + +Lycka till med kodningen, och må dina dokument förbli både vackra **och** tillgängliga! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/programming-with-txtsaveoptions/_index.md b/words/swedish/net/programming-with-txtsaveoptions/_index.md index b83d0feb0b..707c94414b 100644 --- a/words/swedish/net/programming-with-txtsaveoptions/_index.md +++ b/words/swedish/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Tack vare dessa handledningar kommer du att kunna utnyttja funktionerna i Aspose | [Lägg till Bidi-markeringar i Word-dokument](./add-bidi-marks/) | Lär dig hur du lägger till dubbelriktade (Bidi) tecken i Word-dokument med Aspose.Words för .NET med den här guiden. Säkerställ korrekt textriktning för flerspråkigt innehåll. | | [Använd tabbtecken per nivå för listindrag](./use-tab-character-per-level-for-list-indentation/) | Lär dig hur du skapar listor i flera nivåer med tabbindrag med Aspose.Words för .NET. Följ den här guiden för exakt listformatering i dina dokument. | | [Använd mellanslagstecken per nivå för listindrag](./use-space-character-per-level-for-list-indentation/) | Lär dig hur du skapar listor med flera nivåer med mellanslag i Aspose.Words för .NET. Steg-för-steg-guide för exakt dokumentformatering. | - +| [Spara docx som txt – Exportera Word-ekvationer till LaTeX med C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Lär dig hur du sparar DOCX som TXT och konverterar Word-ekvationer till LaTeX med C# i Aspose.Words för .NET. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/swedish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/swedish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..28f2817c65 --- /dev/null +++ b/words/swedish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-04-05 +description: Spara docx som txt med Aspose.Words – konvertera snabbt Word till txt + och lär dig hur du exporterar matematiska ekvationer som LaTeX. Enkel C#‑kod, inga + extra verktyg behövs. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: sv +og_description: Spara docx som txt i C# och se hur du exporterar matematik till LaTeX. + Följ den här steg‑för‑steg‑guiden för att konvertera Word till txt med ekvationer + intakta. +og_title: spara docx som txt – Exportera Word‑ekvationer till LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: spara docx som txt – exportera Word‑ekvationer till LaTeX med C# +url: /sv/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# spara docx som txt – Exportera Word-ekvationer till LaTeX med C# + +Har du någonsin behövt **save docx as txt** men oroat dig för att dina ekvationer skulle försvinna eller bli oläslig nonsens? Du är inte ensam. Många utvecklare stöter på detta när de försöker **convert word to txt** för efterföljande bearbetning, särskilt när källfilen innehåller Office Math-objekt. + +Den goda nyheten? Med några rader C# och rätt alternativ kan du inte bara **convert Word to txt** utan också behålla varje ekvation som ren LaTeX-markup. I den här handledningen går vi igenom hela processen, förklarar varför varje inställning är viktig och visar hur du verifierar resultatet. + +Vi kommer att gå igenom: + +* Installera Aspose.Words för .NET-biblioteket +* Ladda en `.docx` som innehåller matematiska ekvationer +* Konfigurera `TxtSaveOptions` så att **how to export math** blir en LaTeX‑vänlig sträng +* Spara filen och kontrollera resultatet + +När du är klar har du ett återanvändbart kodsnutt som låter dig **save docx as txt** samtidigt som du bevarar varje formel som LaTeX—perfekt för vetenskapliga pipelines, statiska webbplatsgeneratorer eller vilket arbetsflöde som helst som behöver ren‑text-matematik. + +--- + +## Förutsättningar + +Innan vi dyker ner, se till att du har: + +* .NET 6.0 eller senare (koden fungerar även med .NET Framework 4.6+) +* Visual Studio 2022 (eller någon IDE du föredrar) +* NuGet‑paketet **Aspose.Words for .NET** – installera det med + +```bash +dotnet add package Aspose.Words +``` + +Inga ytterligare konverterare eller externa verktyg krävs; Aspose.Words hanterar det tunga arbetet internt. + +--- + +## Steg 1: Installera och referera Aspose.Words + +Först, lägg till biblioteket i ditt projekt. Om du använder kommandoraden kör kommandot ovan. I Visual Studio kan du också högerklicka på **Dependencies → Manage NuGet Packages** och söka efter *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Använd den senaste stabila versionen (i april 2026 är den 24.10). Nyare releaser innehåller buggfixar för OfficeMath‑hantering, så du undviker oväntade saknade symboler. + +--- + +## Steg 2: Ladda källdokumentet + +Nu hämtar vi `.docx`‑filen som innehåller de ekvationer du vill behålla. Klassen `Document` abstraherar hela Word‑filen och ger dig åtkomst till text, bilder och Office Math‑objekt. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Varför ladda den först? Aspose.Words parsar filen till en objektmodell, vilket låter oss inspektera eller ändra innehållet innan vi bestämmer hur vi ska exportera det. Det är här beslut om **how to export math** börjar bli viktiga. + +## Steg 3: Konfigurera TxtSaveOptions för LaTeX‑export + +Kärnan i lösningen är klassen `TxtSaveOptions`. Som standard tar sparning till TXT bort Office Math helt. Genom att sätta `OfficeMathExportMode` till `LaTeX` instruerar du biblioteket att översätta varje ekvation till dess LaTeX‑representation. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Varför LaTeX?** LaTeX är det gemensamma språket för vetenskaplig publicering. Genom att exportera matematik på detta sätt behåller du ekvationens semantik istället för en platt bild eller en förvrängd sträng. Om du senare matar in TXT‑filen i en Markdown‑processor som stödjer MathJax kommer ekvationerna att renderas perfekt. + +## Steg 4: Spara dokumentet som ren text + +Med alternativen konfigurerade är sista steget en enradare som skriver filen till disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Klart—din `.docx` är nu en `.txt`‑fil där varje ekvation visas som ett LaTeX‑snutt, redo för vidare bearbetning. + +## Verifiera utskriften (Hur man sparar txt korrekt) + +Öppna `MathSample.txt` i någon textredigerare. Du bör se något i stil med: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Om du ser råa Word‑specifika tecken (t.ex. `?` eller saknade symboler), dubbelkolla att: + +* Du använder en aktuell version av Aspose.Words (äldre byggen hade buggar med OfficeMath). +* Källdokumentet innehåller faktiskt **OfficeMath**‑objekt—not legacy Equation Editor‑objekt. För de senare kan du behöva konvertera dem manuellt eller använda metoden `ConvertMathToOfficeMath` innan du sparar. + +## Vanliga variationer & kantfall + +| Situation | Vad man ska göra | +|-----------|-------------------| +| **Legacy Equation Editor** objects | Anropa `doc.ConvertMathToOfficeMath()` före steg 3. | +| **You need plain Unicode math, not LaTeX** | Sätt `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Ununicode`. | +| **Large documents (100 + MB)** | Strömma sparoperationen med `doc.Save(Stream, txtOptions)` för att undvika hög minnesanvändning. | +| **You want to keep the original file name** | Använd `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` när du konstruerar utdata‑sökvägen. | + +Dessa justeringar svarar på frågan “**how to export math**” för olika pipelines, vilket säkerställer att din lösning är robust oavsett källa. + +## Fullt fungerande exempel (Alla steg på ett ställe) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Kör programmet, öppna den genererade `.txt`‑filen, och du kommer att se LaTeX‑ekvationerna inbäddade precis där de hörde hemma. Detta är det mest enkla sättet att **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/swedish/net/working-with-fonts/_index.md b/words/swedish/net/working-with-fonts/_index.md index 6377059a27..c512a576f0 100644 --- a/words/swedish/net/working-with-fonts/_index.md +++ b/words/swedish/net/working-with-fonts/_index.md @@ -40,11 +40,12 @@ Oavsett om du vill formatera text med olika teckensnitt, ange regler för tecken | [Prioriteringsinställningar för teckensnittsmappar](./set-fonts-folders-with-priority/) | Lär dig hur du prioriterar teckensnittsmappar i Word-dokument med Aspose.Words för .NET. Vår guide säkerställer att dina dokument renderas perfekt varje gång. | | [Ställ in mappen True Type-teckensnitt](./set-true-type-fonts-folder/) | Lär dig hur du ställer in en True Type Fonts-mapp i Word-dokument med Aspose.Words för .NET. Följ vår detaljerade steg-för-steg-guide för att säkerställa konsekvent typsnittshantering. | | [Ange standardteckensnitt vid rendering](./specify-default-font-when-rendering/) | Lär dig hur du anger ett standardteckensnitt när du renderar Word-dokument med Aspose.Words för .NET. Säkerställ ett enhetligt dokumentutseende över olika plattformar. | -| [Teckensnittsinställningar med laddningsalternativ](./font-settings-with-load-options/) Lär dig hur du hanterar teckensnittsinställningar med laddningsalternativ i Aspose.Words för .NET. Steg-för-steg-guide för utvecklare för att säkerställa ett enhetligt teckensnittsutseende i Word-dokument. +| [Teckensnittsinställningar med laddningsalternativ](./font-settings-with-load-options/) Lär dig hur du hanterar teckensnittsinställningar med laddningsalternativ i Aspose.Words för .NET. Steg-för-steg-guide för utvecklare för att säkerställa ett enhetligt teckensnittsutseende i Word-dokument. | | [Ange teckensnittsmapp](./set-fonts-folder/) | Lär dig hur du ställer in en mapp för anpassade teckensnitt i Aspose.Words för .NET för att säkerställa att dina Word-dokument återges korrekt utan att teckensnitt saknas. | | [Standardinstans för teckensnittsinställningar](./font-settings-default-instance/) | I den här handledningen lär du dig hur du konfigurerar standardinställningar för teckensnitt i ett Word-dokument med Aspose.Words för .NET. | | [Hämta lista över tillgängliga teckensnitt](./get-list-of-available-fonts/) | Upptäck hur du får en lista över tillgängliga teckensnitt med Aspose.Words för .NET i den här detaljerade steg-för-steg-handledningen. Öka dina kunskaper i teckensnittshantering. | | [Få aviseringar om teckensnitt](./receive-notifications-of-fonts/) | Lär dig hur du får meddelanden om saknade eller utbytta teckensnitt när du använder Aspose.Words för .NET. | +| [Aspose teckensnittsersättning – Upptäck saknade teckensnitt i Word-dokument](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Lär dig hur du upptäcker saknade teckensnitt i Word-dokument med Aspose.Words för .NET. | | [Få varningsmeddelande](./receive-warning-notification/) Lär dig hur du får en varningsmeddelande när du använder Aspose.Words för .NET och hanterar eventuella problem eller varningar i dina dokument. | | [Exempel på teckensnittskälla för resurs Steam](./resource-steam-font-source-example/) | Lär dig hur du använder teckensnittskällan Resource Stream för att läsa in anpassade teckensnitt i Aspose.Words för .NET. | | [Hämta substitution utan suffix](./get-substitution-without-suffixes/) | I den här handledningen lär du dig hur du får suffixlösa åsidosättningar i ett Word-dokument med Aspose.Words för .NET. | diff --git a/words/swedish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/swedish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..5ae28f7d60 --- /dev/null +++ b/words/swedish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Aspose guide för teckensnittssubstitution för att upptäcka saknade teckensnitt + vid inläsning av ett Word‑dokument. Lär dig att konfigurera teckensnittsinställningar + och hantera saknade teckensnitt effektivt. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: sv +og_description: Aspose guide för teckensnittssubstitution för att upptäcka saknade + teckensnitt när du laddar ett Word-dokument. Lär dig att konfigurera teckensnittinställningar + och hantera saknade teckensnitt effektivt. +og_title: Aspose teckensnittssubstitution – Detektera saknade teckensnitt i Word‑dokument +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose teckensnittssubstitution – Upptäck saknade teckensnitt i Word-dokument +url: /sv/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Upptäck saknade teckensnitt i Word-dokument + +Har du någonsin stött på en Word‑fil som ser perfekt ut på en maskin men visar märkliga teckensnittsförändringar på en annan? Det är det klassiska **aspose font substitution**‑problemet, och det betyder vanligtvis att vissa teckensnitt saknas på målsystemet. I den här handledningen visar vi dig, steg‑för‑steg, hur du **upptäcker saknade teckensnitt** när du **läser in ett Word‑dokument**, hur du **konfigurerar teckensnittsinställningar**, och vad du ska göra för att **hantera saknade teckensnitt** på ett smidigt sätt. + +Vi går igenom ett komplett, körbart C#‑exempel, förklarar varför varje rad är viktig och visar även konsolutdata du kan förvänta dig. När du är klar kan du identifiera teckensnittssubstitutioner i samma ögonblick som ett dokument läses in – utan gissningar. + +## What You’ll Learn + +- Hur du aktiverar Aspose.Words diagnostiksamlaren för teckensnittsvarningar. +- Den exakta koden som behövs för att **ladda ett Word‑dokument** med anpassade **teckensnittsinställningar**. +- Hur du itererar över `WarningInfo`‑objekt för att lista varje ersatt teckensnitt. +- Tips för att undertrycka oönskade varningar eller tillhandahålla reservteckensnitt. +- Ett färdigt exempel du kan kopiera‑klistra in i Visual Studio. + +### Prerequisites + +- .NET 6.0 eller senare (API‑et fungerar likadant på .NET Framework). +- Aspose.Words for .NET (NuGet‑paket `Aspose.Words`). +- En Word‑fil som refererar till ett teckensnitt du inte har installerat (t.ex. `MissingFont.docx`). + +Om du har detta, låt oss dyka ner. + +## Step 1 – Enable the Diagnostic Collector (Configure Font Settings) + +First things first: Aspose.Words only records font substitution warnings if you tell it to. That’s done by creating a `FontSettings` object and assigning it to a `LoadOptions` instance. Think of this as turning on the “debug lights” for font handling. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Why?** +Utan ett `FontSettings`‑objekt förblir varningssamlaren tyst, och du får aldrig veta vilka teckensnitt som byttes ut. Genom att initiera det tomt låter vi Aspose använda standard‑systemteckensnitten *och* hålla reda på eventuella substitutioner. + +> **Pro tip:** Om du vet att en specifik mapp innehåller företagets teckensnitt, peka `FontSettings` dit med `SetFontsFolder("path")`. Det kan minska antalet varningar om saknade teckensnitt. + +## Step 2 – Load the Document with the Configured Options (Load Word Document) + +Now that the collector is active, load your `.docx` file using the same `LoadOptions`. This is the moment where Aspose scans the document, looks for every font reference, and decides whether a substitution is needed. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Why does this matter?** +Om du bara anropar `new Document("MissingFont.docx")` skulle standardinställningarna tillämpas *och* varningslistan förbli tom. Att skicka med `loadOptions` garanterar att diagnostiksamlaren är kopplad till laddningsprocessen. + +## Step 3 – Retrieve and Display Font Substitution Warnings (Detect Missing Fonts) + +After the document is in memory, Aspose stores any warnings in `document.WarningCallback.Warnings`. Loop through that collection, filter for `WarningType.FontSubstitution`, and print the description. Each description tells you which font was missing and which one was used instead. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Expected console output** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +That output tells you exactly which fonts are missing on the machine running the code. You can now decide whether to install the missing fonts, embed them in the document, or keep the substitution. + +![Console output showing aspose font substitution warnings](/images/aspose-font-substitution-console.png) + +*Image alt text:* aspose font substitution – console output listing substituted fonts + +## Step 4 – Optional: Customize the Substitution Behavior (Handle Missing Fonts) + +Sometimes you don’t just want to know *that* a substitution happened—you want to control *how* it happens. Aspose.Words lets you register a custom `IFontSubstitutionRule`. Below is a quick example that forces any missing font to fall back to `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**When would you use this?** +Om du genererar PDF‑filer för en webbtjänst och vet att alla klienter kan rendera `Tahoma`, garanterar en tvingad reservteckensnitt visuell konsistens utan att behöva distribuera dussintals teckensnittsfiler. + +## Full Working Example (All Steps Combined) + +Here’s the entire program you can paste into a new console project. It compiles as‑is, assuming you’ve installed the Aspose.Words NuGet package. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Run the program, watch the console, and you’ll see every missing‑font event printed out. From there you can decide whether to install the missing fonts, embed them, or keep the fallback. + +## Frequently Asked Questions + +**Q: Does this work with PDF conversion?** +Ja. När du senare anropar `doc.Save("output.pdf")` kommer alla teckensnitt som ersattes under inläsning att vara de som bäddas in i PDF‑filen. Så att fånga varningarna tidigt hjälper dig att undvika oväntade teckensnittsförändringar i den slutgiltiga PDF‑filen. + +**Q: What if I have many documents to process?** +Packa in laddningslogiken i ett try‑catch‑block och återanvänd ett enda `FontSettings`‑objekt för flera dokument. Det minskar overhead och håller varningssamlaren aktiv för varje fil. + +**Q: Can I suppress the warnings entirely?** +Du kan sätta `loadOptions.WarningCallback = null;` innan du laddar, men du förlorar möjligheten att **upptäcka saknade teckensnitt** – vilket vanligtvis inte är önskvärt. + +## Conclusion + +Vi har gått igenom allt du behöver för att bemästra **aspose font substitution**: aktivera diagnostiksamlaren, ladda ett Word‑dokument med anpassade **teckensnittsinställningar**, extrahera listan över saknade teckensnitt, och till och med åsidosätta standardregeln för att **hantera saknade teckensnitt** på ditt eget sätt. Med bara några rader C# får du full insyn i teckensnittsproblem som annars gömmer sig bakom subtila layoutförändringar. + +Nästa steg? Prova att bädda in de ursprungliga teckensnitten i dokumentet med `FontSettings.SetFontsFolder` eller utforska `FontSourceBase` för att ladda teckensnitt från en databas. Du kan också experimentera med `Document.BuiltInStyle`‑samlingen för att se hur stil‑nivå teckensnittsförändringar sprider sig. + +Har du fler frågor om Aspose.Words eller teckensnittshantering? Lämna en kommentar, utforska den officiella Aspose‑dokumentationen, eller starta ett nytt projekt och lek med koden ovan. Lycka till med kodningen, och må dina dokument alltid renderas exakt som avsett! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/basic-conversions/_index.md b/words/thai/net/basic-conversions/_index.md index a0128bb8eb..f33c0733ed 100644 --- a/words/thai/net/basic-conversions/_index.md +++ b/words/thai/net/basic-conversions/_index.md @@ -25,6 +25,7 @@ Basic Conversions จะแนะนำคุณเกี่ยวกับก | [แปลง Docx เป็น Rtf](./docx-to-rtf/) | เรียนรู้วิธีแปลง DOCX เป็น RTF โดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือทีละขั้นตอนของเรา การแปลงที่ง่ายดายเพื่อการประมวลผลเอกสารที่ราบรื่น - | [แปลงไฟล์ Word เป็น PDF](./docx-to-pdf/) เรียนรู้วิธีการแปลงไฟล์ Word เป็น PDF ได้อย่างง่ายดายโดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือของเรา เหมาะสำหรับนักพัฒนาที่ต้องการการแปลงเอกสารที่รวดเร็วและเชื่อถือได้ - - [แปลง Word เป็น PDF ใน C# ด้วย Aspose.Words – คู่มือ](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | เรียนรู้วิธีแปลงไฟล์ Word เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - +- [แปลง Word เป็น PDF ใน C# – คู่มือเต็มกับ Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | เรียนรู้วิธีแปลงไฟล์ Word เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - - [บันทึก Word เป็น PDF ด้วย Aspose.Words – คู่มือ C# ฉบับสมบูรณ์](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | เรียนรู้วิธีบันทึกไฟล์ Word เป็น PDF ด้วย C# และ Aspose.Words อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน - | [แปลง Docx เป็นไบต์](./docx-to-byte/) | เรียนรู้วิธีการแปลง Docx เป็นอาร์เรย์ไบต์ใน .NET โดยใช้ Aspose.Words เพื่อการประมวลผลเอกสารอย่างมีประสิทธิภาพ มีคู่มือทีละขั้นตอนรวมอยู่ด้วย - | [แปลง Docx เป็น Epub](./docx-to-epub/) | แปลง DOCX เป็น EPUB ได้อย่างง่ายดายด้วย Aspose.Words สำหรับ .NET ทำตามบทช่วยสอนของเราเพื่อบูรณาการกับแอปพลิเคชัน .NET ของคุณได้อย่างราบรื่น - diff --git a/words/thai/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/thai/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..1a8ae36def --- /dev/null +++ b/words/thai/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,192 @@ +--- +category: general +date: 2026-04-05 +description: แปลง Word เป็น PDF ด้วย C# โดยใช้ Aspose.Words. เรียนรู้วิธีบันทึกไฟล์ + docx เป็น PDF, ส่งออก PDF ที่เข้าถึงได้, และโหลดเอกสาร Word อย่างมีประสิทธิภาพ. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: th +og_description: แปลง Word เป็น PDF ใน C# ด้วยคู่มือขั้นตอนโดยละเอียด ค้นหาวิธีบันทึกไฟล์ + docx เป็น PDF ส่งออก PDF ที่เข้าถึงได้ และโหลดเอกสาร Word ด้วย Aspose.Words +og_title: แปลง Word เป็น PDF ด้วย C# – คู่มือ Aspose.Words ครบถ้วน +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: แปลงไฟล์ Word เป็น PDF ด้วย C# – คู่มือเต็มกับ Aspose.Words +url: /th/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง Word เป็น PDF ด้วย C# – คู่มือการเขียนโปรแกรมฉบับสมบูรณ์ + +เคยสงสัยไหมว่า **convert word to pdf** อย่างไรโดยไม่ต้องต่อสู้กับเครื่องมือบรรทัดคำสั่งที่ซับซ้อนหรือบริการของบุคคลที่สาม? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจออุปสรรคนี้เมื่อลูกค้าต้องการ PDF ที่เข้าถึงได้โดยตรงจากไฟล์ DOCX ข่าวดีคือ? ด้วยไม่กี่บรรทัดของ C# และไลบรารี Aspose.Words ที่ทรงพลัง คุณสามารถแปลงเอกสาร Word ให้เป็น PDF ที่เป็นไปตามมาตรฐานได้ในพริบตา + +ในคู่มือนี้เราจะพาคุณผ่านทุกอย่างที่ต้องรู้: ตั้งแต่พื้นฐานการ **load word document**, การกำหนดค่าตัวเลือกที่ถูกต้องเพื่อ **how to export accessible pdf**, และสุดท้ายการบันทึกผลลัพธ์เพื่อให้คุณสามารถ **save docx as pdf** ได้อย่างมั่นใจ เมื่อจบคุณจะมีโค้ดสแนปช็อตที่พร้อมรันและสามารถนำไปใส่ในโปรเจกต์ .NET ใดก็ได้ + +> **Pro tip:** หากคุณกำลังมุ่งเป้าไปที่การปฏิบัติตามมาตรฐาน PDF/UA‑2 (มาตรฐานการเข้าถึงที่หลายหน่วยงานรัฐบาลกำหนด), โค้ดเดียวกันทำงานได้โดยไม่ต้องทำขั้นตอนเพิ่มเติม—เพียงตั้งค่า `PdfCompliance` ให้ถูกต้อง + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธี **load word document** ด้วย Aspose.Words ใน C# +- การตั้งค่าที่จำเป็นเพื่อ **how to export accessible pdf** (PDF/UA‑2) อย่างแม่นยำ +- ตัวอย่างเต็มที่สามารถรันได้ซึ่ง **save docx as pdf** ด้วยการเรียกเมธอดเดียว +- ปัญหาที่พบบ่อยเมื่อคุณ **c# convert docx pdf** และวิธีหลีกเลี่ยง +- วิธีตรวจสอบอย่างรวดเร็วว่า PDF ที่สร้างขึ้นตรงตามความคาดหวังด้านการเข้าถึงหรือไม่ + +ไม่มีเครื่องมือภายนอก, ไม่มีไฟล์กำหนดค่าที่ซับซ้อน—เพียงโค้ด C# แท้ ๆ ที่คุณสามารถคอมไพล์ได้วันนี้ + +## ข้อกำหนดเบื้องต้น + +1. **.NET 6.0** (หรือเวอร์ชัน .NET ล่าสุดใดก็ได้) ที่ติดตั้งไว้แล้ว เฟรมเวิร์กเก่าก็ทำงานได้เช่นกัน แต่ไวยากรณ์ด้านล่างสมมติว่าใช้ SDK รุ่นใหม่ +2. **license** สำหรับ Aspose.Words for .NET ไลบรารีนี้มีรุ่นทดลองฟรี แต่สำหรับการใช้งานจริงคุณจะต้องมีคีย์ที่ถูกต้อง +3. **Aspose.Words** NuGet package ที่เพิ่มเข้าไปในโปรเจกต์ของคุณ + +```bash +dotnet add package Aspose.Words +``` + +เท่านี้—ไม่มีไบนารีเพิ่มเติม, ไม่มี COM interop, เพียงอ้างอิง NuGet ที่สะอาดตา + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## การดำเนินการแบบขั้นตอน + +ด้านล่างเราจะแบ่งกระบวนการเป็นส่วนย่อย ๆ แต่ละขั้นมีโค้ดสแนปช็อตสั้น ๆ คำอธิบายว่า **why** มันสำคัญ และเคล็ดลับจากการใช้งานจริง + +### ## แปลง Word เป็น PDF – โหลดเอกสารต้นฉบับ + +สิ่งแรกที่คุณต้องทำคือ **load word document** เข้าไปในหน่วยความจำ Aspose.Words จะจัดการการแยกวิเคราะห์ OpenXML ให้คุณทำงานกับไฟล์ DOCX, DOC หรือแม้แต่ RTF ได้โดยไม่ต้องกังวลเรื่องความแปลกของฟอร์แมต + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Why this matters:** +การโหลดไฟล์จะสร้างอ็อบเจ็กต์ `Document` ที่แทนเอกสาร Word ทั้งหมด รวมถึงส่วนหัว, ส่วนท้าย, สไตล์, และเมตาดาต้าแบบซ่อน หากข้ามขั้นตอนนี้หรือพยายามอ่านไฟล์เป็นสตรีมดิบ คุณจะสูญเสียข้อมูลการจัดวางที่ต่อมาจะกำหนดลักษณะของ PDF + +> **Side note:** ตัวสร้าง `Document` เดียวกันทำงานได้กับ `.doc` และ `.rtf` นั่นหมายความว่าคุณสามารถ **c# convert docx pdf** แม้แหล่งที่มาจะไม่ใช่ DOCX อย่างเคร่งครัด + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +เมื่อเอกสารอยู่ในหน่วยความจำแล้ว เราจะบอก Aspose.Words ว่าต้องการให้สร้าง PDF อย่างไร สำหรับกรณีใช้งานส่วนใหญ่ค่าตั้งต้นก็พอใช้ได้ แต่เมื่อคุณต้องการ **accessible PDF** คุณต้องเปิดใช้งานฟลัก PDF/UA‑2 compliance + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Why this matters:** +`PdfCompliance.PdfUAXmpA2` บอกไลบรารีให้ฝังแท็กและโครงสร้างที่โปรแกรมอ่านหน้าจอ (screen readers) พึ่งพา หากไม่มีฟลักนี้ คุณอาจได้ PDF ที่ดูสวยงามแต่ไม่ผ่านการตรวจสอบการเข้าถึง + +> **Tip:** หากคุณต้องการ PDF ธรรมดาเท่านั้น สามารถลบบรรทัด `Compliance` ได้ ตัวเลือกอื่น ๆ ยังคงให้ผลลัพธ์คุณภาพสูง + +### ## แปลง Word เป็น PDF – เขียนไฟล์ + +เมื่อกำหนดตัวเลือกเรียบร้อย ขั้นตอนสุดท้ายคือ **save docx as pdf** การเรียกครั้งเดียวนี้ทำหน้าที่ทั้งหมด: การแปลงการจัดวาง, การฝังฟอนต์, และการใส่แท็กการเข้าถึง + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**What you get:** +- ไฟล์ PDF ที่อยู่ที่ `outputPath` ซึ่งสะท้อนการจัดวางของ Word อย่างแม่นยำ +- หากคุณใช้ฟลัก `PdfUAXmpA2` PDF จะถูกระบุว่าเป็น PDF/UA‑2 compliant +- ฟอนต์ทั้งหมดถูกฝังไว้ ทำให้ไฟล์ดูเหมือนเดิมบนเครื่องใดก็ได้ + +### ## Verify the Accessible PDF (Optional but Recommended) + +หลังจากแปลงแล้ว ควรตรวจสอบอีกครั้งว่า PDF จริง ๆ แล้ว **how to export accessible pdf** อย่างถูกต้องหรือไม่ คุณสามารถใช้เครื่องมือฟรีเช่น “Accessibility Check” ของ Adobe Acrobat Reader หรือตัวตรวจสอบ `pdfcpu` แบบโอเพนซอร์ส + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +หากตัวตรวจสอบไม่รายงานข้อผิดพลาด คุณได้ทำ **convert word to pdf** พร้อมการสนับสนุนการเข้าถึงเต็มรูปแบบสำเร็จแล้ว + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| Missing fonts | ไฟล์ DOCX ต้นฉบับใช้ฟอนต์ที่กำหนดเองซึ่งไม่ได้ติดตั้งบนเซิร์ฟเวอร์ | ตั้งค่า `EmbedFullFonts = true` หรือทำการติดตั้งฟอนต์บนเครื่อง | +| Large file size | รูปภาพถูกฝังในความละเอียดเต็ม | ใช้ `ImageCompression = PdfImageCompression.Jpeg` และกำหนด `JpegQuality` ให้ค่าต่ำลง | +| Broken hyperlinks | ลิงก์ชี้ไปยังเส้นทางสัมพันธ์ที่ไม่มีอยู่บนเครื่องลูกค้า | ตรวจสอบให้ URL เป็นแบบเต็มหรือปรับคุณสมบัติ `HyperlinkTarget` | +| Accessibility tags missing | ไม่ได้ตั้งค่าฟลัก `Compliance` | เพิ่ม `Compliance = PdfCompliance.PdfUAXmpA2` ตามที่แสดงด้านบน | + +การคำนึงถึงสิ่งเหล่านี้จะทำให้กระบวนการ **c# convert docx pdf** ของคุณแข็งแรงและพร้อมใช้งานในสภาพแวดล้อมการผลิต + +## Full Working Example + +รวมทุกอย่างเข้าด้วยกัน นี่คือแอปคอนโซลแบบอิสระที่คุณสามารถคอมไพล์และรันได้ทันที + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Expected result:** หลังจากรันโปรแกรม คุณจะพบ `output.pdf` อยู่ใน `C:\Docs` เปิดไฟล์ด้วยโปรแกรมอ่าน PDF ใดก็ได้; การจัดวางควรตรงกับ `input.docx` พิกเซลต่อพิกเซล และการตรวจสอบการเข้าถึงจะยืนยันว่าเป็น PDF/UA‑2 compliant + +## Conclusion + +เราได้อธิบายวิธีแก้ปัญหาแบบครบวงจรสำหรับการ **convert word to pdf** ด้วย C# และ Aspose.Words โดย **load word document**, กำหนด `PdfSaveOptions` ที่เหมาะสม, และสุดท้าย **save docx as pdf** คุณจะได้ PDF คุณภาพสูงที่เข้าถึงได้ด้วยโค้ดเพียงเล็กน้อย ไม่ว่าคุณจะสร้างบริการสร้างเอกสารแบบไมโครเซอร์วิส หรือเครื่องแปลงแบบแบตช์บนเครื่องเซิร์ฟเวอร์ + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-markdownsaveoptions/_index.md b/words/thai/net/programming-with-markdownsaveoptions/_index.md index 57c58415e0..4d69c7a588 100644 --- a/words/thai/net/programming-with-markdownsaveoptions/_index.md +++ b/words/thai/net/programming-with-markdownsaveoptions/_index.md @@ -37,13 +37,18 @@ ### [บันทึก docx เป็น markdown – คู่มือเต็ม C# พร้อมการสกัดรูปภาพ](./save-docx-as-markdown-full-c-guide-with-image-extraction/) ### [วิธีส่งออก Markdown จาก Word – คู่มือเต็ม C#](./how-to-export-markdown-from-word-complete-c-guide/) -เรียนรู้ขั้นตอนการส่งออกไฟล์ Word เป็น Markdown อย่างครบถ้วนด้วย C# +เรียนรู้ขั้นตอนการส่งออกไฟล์ Word เป็น Markdown อย่างครบถ้วนด้วย C+ ### [วิธีบันทึก Markdown จาก DOCX – คู่มือขั้นตอนโดยขั้นตอน](./how-to-save-markdown-from-docx-step-by-step-guide/) ### [วิธีส่งออก Markdown จาก DOCX – คู่มือเต็ม C#](./how-to-export-markdown-from-docx-complete-guide/) เรียนรู้วิธีส่งออก Markdown จากไฟล์ DOCX ด้วย Aspose.Words สำหรับ .NET อย่างละเอียดด้วยขั้นตอนที่ชัดเจน +### [แปลง DOCX เป็น Markdown – สกัดรูปภาพจาก DOCX ด้วย Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) + +### [แปลง Word เป็น Markdown – คู่มือเต็มพร้อมการส่งออก PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) +แปลงไฟล์ Word เป็น Markdown พร้อมการส่งออก PDF/UA อย่างละเอียด + {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/thai/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..fa52b9f898 --- /dev/null +++ b/words/thai/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-04-05 +description: เรียนรู้วิธีแปลง DOCX เป็น Markdown และดึงรูปภาพจาก DOCX ด้วย C# คู่มือทีละขั้นตอนพร้อมโค้ดเต็มและเคล็ดลับ +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: th +og_description: แปลง DOCX เป็น Markdown และดึงรูปภาพจาก DOCX ด้วย Aspose.Words. บทเรียน + C# ครบถ้วนพร้อมโค้ด คำอธิบาย และเคล็ดลับการปฏิบัติที่ดีที่สุด. +og_title: แปลง DOCX เป็น Markdown – ดึงรูปภาพจาก DOCX ด้วย C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: แปลง DOCX เป็น Markdown – ดึงรูปภาพจาก DOCX ด้วย Aspose.Words +url: /th/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง DOCX เป็น Markdown – ดึงรูปภาพจาก DOCX ด้วย C# + +เคยต้องการ **แปลง DOCX เป็น Markdown** แต่พบปัญหารูปภาพหายไปในผลลัพธ์หรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการเวอร์ชัน markdown เหมาะอย่างยิ่งสำหรับการควบคุมเวอร์ชันหรือ static‑site generators แต่รูปภาพกลับถูกละทิ้ง ทำให้เอกสารที่เต็มไปด้วยเนื้อหากลายเป็นไฟล์ข้อความเปล่าเปลี่ยว + +ข่าวดีคือ? ด้วยไม่กี่บรรทัดของ C# และ Aspose.Words คุณสามารถ **แปลง DOCX เป็น Markdown** *และ* **ดึงรูปภาพจาก DOCX** อัตโนมัติ คู่มือนี้จะพาคุณผ่านกระบวนการทั้งหมด อธิบายว่าทำไมแต่ละส่วนจึงสำคัญ และแม้กระทั่งแสดงวิธีจัดระเบียบโฟลเดอร์รูปภาพของคุณให้เป็นระเบียบ + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีโหลดไฟล์ DOCX ที่มีรูปภาพ +- วิธีกำหนด `IResourceSavingCallback` แบบกำหนดเองเพื่อกำหนดตำแหน่งที่แต่ละรูปภาพจะถูกบันทึก +- วิธีตั้งค่า `MarkdownSaveOptions` เพื่อให้ markdown ที่สร้างอ้างอิงรูปภาพที่ดึงออกมาอย่างถูกต้อง +- เคล็ดลับการจัดการกรณีขอบเช่นชื่อรูปภาพซ้ำหรือรูปแบบที่ไม่ใช่ PNG +- ตัวอย่างโค้ดที่สมบูรณ์พร้อมคัดลอก‑วางที่คุณสามารถรันได้ทันที + +### ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (API ทำงานบน .NET Core, .NET Framework, และ .NET 5+) +- ไลเซนส์สำหรับ **Aspose.Words for .NET** (รุ่นทดลองฟรีใช้สำหรับการทดสอบ) +- ความคุ้นเคยพื้นฐานกับ C# และ Visual Studio (หรือ IDE ที่คุณชื่นชอบ) + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปเริ่มกันเลย. + +--- + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และติดตั้ง Aspose.Words + +ขั้นแรก สร้างแอปคอนโซลใหม่ (หรือรวมเข้ากับโซลูชันที่มีอยู่แล้ว) + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **เคล็ดลับระดับมืออาชีพ:** ใช้เวอร์ชัน NuGet ล่าสุด (ณ เมษายน 2026 คือ 24.12) เพื่อรับการปรับปรุงการส่งออก markdown ที่ใหม่ที่สุด + +--- + +## ขั้นตอนที่ 2: สร้าง Callback เพื่อบันทึกรูปภาพในตำแหน่งที่คุณต้องการ + +Aspose.Words ให้คุณดักจับทุกทรัพยากร (รูปภาพ, SVG, ฯลฯ) ที่ถูกเขียนระหว่างการส่งออก markdown โดยการทำ `IResourceSavingCallback` คุณสามารถ: + +1. เลือกโฟลเดอร์ที่อยู่ข้างไฟล์ markdown ของคุณ +2. สร้างชื่อไฟล์ที่ไม่ซ้ำกัน (เพื่อไม่ให้เขียนทับรูปภาพที่มีอยู่) +3. กำหนดรูปแบบ (ที่นี่เราบังคับใช้ PNG เพื่อความสอดคล้อง) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### ทำไมต้องใช้ชื่อแบบ GUID? + +หาก DOCX ต้นฉบับมีรูปภาพสองภาพที่มีชื่อเดิมเดียวกัน การคัดลอก‑วางอย่างง่ายจะทำให้ไฟล์หนึ่งถูกเขียนทับ การใช้ `Guid.NewGuid()` รับประกันความไม่ซ้ำกัน ซึ่งเป็นประโยชน์อย่างยิ่งเมื่อคุณทำการแปลงหลายครั้งใน pipeline อัตโนมัติ + +--- + +## ขั้นตอนที่ 3: โหลด DOCX และตั้งค่า Markdown Options + +ตอนนี้เรานำเอกสารเข้าสู่หน่วยความจำและเชื่อมต่อ callback ที่เราสร้างไว้ + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### สิ่งที่โค้ดทำ ทีละขั้นตอน + +| Step | Purpose | +|------|---------| +| **กำหนดเส้นทาง** | ทำให้โปรเจกต์ของคุณยืดหยุ่น; คุณสามารถชี้ไปยังโฟลเดอร์ใดก็ได้โดยไม่ต้องคอมไพล์ใหม่. | +| **โหลด DOCX** | `Document` วิเคราะห์ไฟล์ Word ทำให้ทุกองค์ประกอบ (ย่อหน้า, ตาราง, รูปภาพ) สามารถเข้าถึงได้. | +| **ตั้งค่า `MarkdownSaveOptions`** | `ResourceSavingCallback` เป็นจุดเชื่อมที่ดึงรูปภาพออก หากไม่มี Aspose.Words จะฝังรูปภาพเป็นสตริง base64 หรือทิ้งรูปภาพทั้งหมด ขึ้นอยู่กับการตั้งค่า. | +| **บันทึก** | `doc.Save` เขียนไฟล์ markdown และเรียก callback สำหรับแต่ละรูปภาพ. | + +--- + +## ขั้นตอนที่ 4: ตรวจสอบผลลัพธ์ – คุณควรเห็นอะไร + +หลังจากรันโปรแกรมแล้ว เปิดไฟล์ `DocWithImages.md` คุณจะสังเกตเห็นลิงก์รูปภาพใน markdown ที่มีลักษณะดังนี้: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +และใน `C:\Docs\MarkdownResources` คุณจะพบไฟล์ PNG จำนวนหลายไฟล์ที่มีชื่อเป็น GUID เปิดไฟล์ใดก็ได้ – ควรจะเหมือนกับรูปภาพที่ฝังอยู่ใน DOCX ต้นฉบับ + +หากคุณเปิดไฟล์ markdown ในโปรแกรมดูที่รองรับเส้นทางสัมพันธ์ (เช่น ตัวอย่างใน VS Code, GitHub, หรือ static‑site generator) รูปภาพจะปรากฏเช่นเดียวกับใน Word + +### ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| Symptom | Likely Cause | Fix | +|---------|--------------|-----| +| รูปภาพแสดงเป็นลิงก์เสีย | `ResourceFileName` ไม่ได้ตั้งค่า ทำให้ markdown ชี้ไปยังไฟล์ที่ไม่มีอยู่ | ตรวจสอบให้แน่ใจว่าได้ตั้งค่า `args.ResourceFileName = newFileName;` ภายใน callback | +| ไฟล์ PNG มีขนาดใหญ่ | รูปภาพต้นฉบับเป็น JPEG หรือ BMP; การแปลงเป็น PNG อาจทำให้ขนาดเพิ่มขึ้น | ตรวจจับรูปแบบต้นฉบับผ่าน `args.ResourceContentType` และเก็บไว้: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| รูปภาพซ้ำยังคงปรากฏ | คุณใช้ชื่อไฟล์คงที่แทน GUID | กลับไปใช้ตรรกะ GUID หรือเพิ่มตัวนับต่อประเภทรูปภาพ | +| การแปลงโยน `FileNotFoundException` | เส้นทาง DOCX ต้นทางผิดหรือโฟลเดอร์ไม่มีสิทธิ์อ่าน | ตรวจสอบเส้นทางและให้สิทธิ์ระบบไฟล์ที่เหมาะสม | + +--- + +## ขั้นตอนที่ 5: การปรับแต่งขั้นสูง (ทางเลือก) + +### 5.1 รักษารูปแบบรูปภาพต้นฉบับ + +หากคุณต้องการให้รูปภาพผลลัพธ์คงนามสกุลเดิม ให้แก้ไข callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 ฝังรูปภาพเป็น Base64 (เมื่อคุณ *ไม่ต้องการ* ไฟล์แยก) + +บางครั้ง markdown แบบไฟล์เดียวอาจเหมาะกว่า (เช่น ส่งทางอีเมล) ให้เปลี่ยนตัวเลือก: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +แต่จำไว้ว่า: **ดึงรูปภาพจาก DOCX** เป็นเป้าหมายหลักสำหรับ workflow ของ static‑site ส่วนใหญ่ ดังนั้นวิธีใช้โฟลเดอร์จึงเป็นตัวเลือกที่ดีกว่า + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (พร้อมคัดลอก‑วาง) + +ด้านล่างเป็นโปรแกรมทั้งหมดในไฟล์เดียว เพียงเปลี่ยนเส้นทางให้เป็นของคุณเองแล้วรัน + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +รันด้วยคำสั่ง `dotnet run`. เมื่อคอนโซลพิมพ์บรรทัด ✅ ให้เปิดไฟล์ markdown แล้วคุณควรเห็นรูปภาพแสดงผลอย่างถูกต้อง + +--- + +## สรุป + +ตอนนี้คุณมี **โซลูชันที่ครบถ้วนและพร้อมใช้งานในระดับผลิตภัณฑ์เพื่อแปลง DOCX เป็น Markdown และดึงรูปภาพจาก DOCX** ด้วย Aspose.Words ใน C# คำหลักหลักปรากฏตลอดคู่มือ เพื่อเสริมความเกี่ยวข้องทั้งสำหรับเครื่องมือค้นหาและผู้ช่วย AI + +ในขั้นตอนเดียว โค้ดทำ: + +1. โหลดเอกสาร Word +2. ดักจับรูปภาพทุกภาพผ่าน `IResourceSavingCallback` +3. บันทึกรูปภาพแต่ละไฟล์ลงในโฟลเดอร์ที่คาดเดาได้ด้วยชื่อที่ไม่ซ้ำ +4. สร้าง markdown ที่อ้างอิงรูปภาพเหล่านั้น + +จากนี้คุณสามารถ: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/thai/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..f5e24eee57 --- /dev/null +++ b/words/thai/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-04-05 +description: แปลง Word เป็น Markdown อย่างรวดเร็วและเรียนรู้วิธีบันทึกเป็น PDF/UA + ด้วย C# โค้ดแบบขั้นตอน‑ต่อ​ขั้นตอน เคล็ดลับและการจัดการกรณีขอบ +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: th +og_description: แปลง Word เป็น Markdown และบันทึกเป็น PDF/UA ด้วย Aspose.Words เรียนรู้เหตุผล + วิธีการ และเคล็ดลับการปฏิบัติที่ดีที่สุดในคู่มือสั้น ๆ หนึ่งเล่ม +og_title: แปลง Word เป็น Markdown – คอร์สสอน C# อย่างสมบูรณ์ +tags: +- Aspose.Words +- C# +- Document Conversion +title: แปลง Word เป็น Markdown – คู่มือเต็มพร้อมการส่งออก PDF/UA +url: /th/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง Word เป็น Markdown – คู่มือเต็มพร้อมการส่งออก PDF/UA + +เคยสงสัยไหมว่าจะ **แปลง Word เป็น Markdown** อย่างไรโดยไม่สูญเสียสมการหรือรูปภาพ? คุณไม่ได้เป็นคนเดียว นักพัฒนาจำนวนมากต้องการวิธีที่เชื่อถือได้ในการแปลงไฟล์ `.docx` ให้เป็น Markdown ที่สะอาดพร้อมทั้ง **บันทึกเป็น PDF/UA** สำหรับไฟล์ PDF ที่เป็นไปตามมาตรฐานการเข้าถึง ในบทแนะนำนี้เราจะเดินผ่านโซลูชันที่พร้อมรันโดยใช้ Aspose.Words for .NET อธิบายว่าทำไมแต่ละการตั้งค่าถึงสำคัญ และแสดงวิธีจัดการกับส่วนที่ซับซ้อนเช่น OfficeMath และรูปแบบลอยตัว + +เมื่อจบคู่มือนี้คุณจะมีโปรแกรม C# เดียวที่: + +1. โหลดเอกสาร Word ด้วยการกู้คืนแบบผ่อนคลาย (เพื่อให้ไฟล์ที่เสียหายไม่ทำให้การทำงานหยุด) +2. ส่งออกเป็น Markdown โดยแปลงสมการเป็น LaTeX และบันทึกรูปภาพผ่าน callback ที่กำหนดเอง +3. บันทึกเอกสารเดียวกันเป็นไฟล์ PDF/UA‑2 ที่สอดคล้องกับมาตรฐาน โดยฝังรูปแบบลอยตัวเป็นแท็กอินไลน์ + +ฟังดูเยอะ? ไม่ต้องกังวล—มาเริ่มกันเลย + +## สิ่งที่คุณต้องมี + +- **Aspose.Words for .NET** (เวอร์ชันล่าสุด, 23.x ณ เวลาที่เขียน) +- สภาพแวดล้อมการพัฒนา .NET (Visual Studio 2022, Rider, หรือ `dotnet` CLI) +- ไฟล์ Word ตัวอย่าง (`input.docx`) ที่วางไว้ในโฟลเดอร์ที่คุณอ้างอิงได้ +- ความคุ้นเคยพื้นฐานกับไวยากรณ์ C#—ไม่มีอะไรซับซ้อน เพียงไม่กี่บรรทัด `using` + +> **Pro tip:** หากคุณใช้ NuGet package manager ให้เพิ่มไลบรารีด้วย +> `dotnet add package Aspose.Words` หรือผ่าน Visual Studio NuGet UI + +## ขั้นตอน 1 – โหลดเอกสาร Word ด้วยการกู้คืนแบบผ่อนคลาย + +เมื่อคุณได้รับไฟล์ Word จากแหล่งภายนอกอาจมีการเสียหายเล็กน้อย การเปิดใช้งานการกู้คืน **Relaxed** จะบอก Aspose.Words ให้ดำเนินการต่อแทนที่จะโยนข้อยกเว้น + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**ทำไมจึงสำคัญ:** +- `RecoveryMode.Relaxed` ป้องกันย่อหน้าที่ผิดรูปแบบเดียวจากการทำให้การแปลงทั้งหมดหยุดลง +- การให้ `FontSettings` จะทำให้ฟอนต์ที่หายไปถูกแทนที่อย่างราบรื่น ซึ่งสำคัญเมื่อคุณต้องเรนเดอร์สมการเป็น LaTeX ต่อไป + +## ขั้นตอน 2 – ส่งออกเป็น Markdown (OfficeMath → LaTeX, รูปภาพผ่าน Callback) + +Markdown ไม่มีวิธีเนทีฟในการแสดงสมการของ Word Aspose.Words สามารถแปลอ็อบเจ็กต์ **OfficeMath** เป็น LaTeX ซึ่งเรนเดอร์เดอร์ Markdown ส่วนใหญ่เข้าใจได้ รูปภาพต้องบันทึกไว้ที่ไหนสักแห่ง; **callback การบันทึกทรัพยากร** ที่กำหนดเองจะให้คุณควบคุมโครงสร้างโฟลเดอร์และการตั้งชื่อได้เต็มที่ + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback การบันทึกทรัพยากร + +ด้านล่างเป็นการทำงานขนาดเล็กที่เก็บรูปภาพทุกไฟล์ในโฟลเดอร์ย่อยชื่อ `images` และตั้งชื่อไฟล์เป็น `img001.png`, `img002.png` เป็นต้น + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**ทำไมคุณต้องใช้:** +- หากไม่มี callback, Aspose.Words จะสร้างโฟลเดอร์แบนที่มีชื่อ GUID สุ่ม ซึ่งทำให้การควบคุมเวอร์ชันยุ่งยาก +- การควบคุมสกีมการตั้งชื่อทำให้ที่เก็บ Markdown ของคุณเป็นระเบียบและทำซ้ำได้ง่าย + +### ผลลัพธ์ Markdown ที่คาดหวัง + +เปิด `doc.md` หลังจากรันแล้วคุณจะเห็น: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +สมการจะแสดงเป็น LaTeX ที่ล้อมด้วย `$$ … $$` และรูปภาพอ้างอิงโฟลเดอร์ `images` ที่คุณสร้างไว้ + +## ขั้นตอน 3 – ส่งออกเป็น PDF/UA‑2 (พร้อมการเข้าถึง) + +หากคุณต้องการแชร์เอกสารกับผู้ใช้ที่พึ่งพา screen reader หรือเทคโนโลยีช่วยเหลืออื่น **PDF/UA‑2** เป็นมาตรฐานทองคำ Aspose.Words สามารถบังคับใช้ได้ด้วยเพียงแฟล็กเดียว และยังสามารถทำให้รูปแบบลอยตัวแปลงเป็นแท็กอินไลน์เพื่อไม่ให้หายไประหว่างการแปลง + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**ทำไม PDF/UA ถึงสำคัญ:** +- PDF/UA (Universal Accessibility) รับประกันว่า PDF ที่ได้มีการแท็กที่เหมาะสม, ลำดับการอ่านที่เป็นตรรกะ, และข้อความแทนสำหรับรูปภาพ +- การตั้งค่า `ExportFloatingShapesAsInlineTag` ทำให้รูปแบบเช่น text box หรือ callout ไม่ถูกละเลยหรือวางผิดตำแหน่ง—ข้อผิดพลาดที่พบบ่อยเมื่อต้องแปลงเลย์เอาต์ที่ซับซ้อน + +### การตรวจสอบความสอดคล้องกับ PDF/UA + +หลังการส่งออก, เปิด PDF ด้วย Adobe Acrobat Pro แล้วรัน **“Accessibility Check”** (Tools → Accessibility → Full Check) หากเครื่องมือรายงาน **0 errors** คุณทำสำเร็จแล้ว + +## กรณีขอบและข้อผิดพลาดทั่วไป + +| สถานการณ์ | สิ่งที่ต้องระวัง | วิธีแก้ / คำแนะนำ | +|-----------|----------------|-------------------| +| ไฟล์ Word มี **ฟอนต์ที่ไม่รองรับ** | ฟอนต์อาจถูกแทนที่ ทำให้รูปแบบสมการเสีย | จัดหา `FontSettings` ที่กำหนดฟอนต์สำรอง | +| เอกสารขนาดใหญ่ (> 100 MB) | ความกดดันของหน่วยความจำระหว่างการแปลง | ใช้ `LoadOptions` กับ `LoadFormat.Docx` แล้วสตรีมไฟล์ | +| รูปภาพเป็นกราฟิกเวกเตอร์ **EMF/WMF** | อาจถูกแปลงเป็น raster โดยไม่ตั้งใจ | แปลงเป็น PNG ผ่าน `ImageSaveOptions` ก่อนบันทึก | +| การตรวจสอบ PDF/UA ล้มเหลวบน **ตารางซ้อนกัน** | การแท็กอาจคลุมเครือ | เปิด `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` เพื่อช่วยเอนจิน | +| ต้อง **รักษาสไตล์ที่กำหนดเอง** | Markdown มีความสามารถในการจัดรูปแบบจำกัด | ส่งออกไฟล์ CSS ควบคู่กับ Markdown แล้วอ้างอิง | + +## ตัวอย่างทำงานเต็ม (รวมโค้ดทั้งหมด) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +รันโปรแกรมแล้วคุณจะพบทั้ง `doc.md` (พร้อมสมการ LaTeX และลิงก์รูปภาพที่สะอาด) และ `doc.pdf` (สอดคล้องกับ PDF/UA‑2 อย่างเต็มที่) อยู่ใน `YOUR_DIRECTORY` + +## ภาพรวมเชิงภาพ + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*ข้อความแทน:* **convert word to markdown example** – แผนภาพของกระบวนการแปลงจากไฟล์ Word ไปยัง Markdown และ PDF/UA + +## สรุป & ขั้นตอนต่อไป + +เราเพิ่ง **แปลง Word เป็น Markdown** พร้อมคงสมการไว้, เก็บรูปภาพในโฟลเดอร์เป็นระเบียบ, และสร้างไฟล์ **บันทึกเป็น PDF/UA** ที่ผ่านการตรวจสอบการเข้าถึง จุดสำคัญที่ควรจำคือ: + +- ใช้ `LoadOptions.RecoveryMode.Relaxed` เพื่อยอมรับไฟล์ Word ที่ไม่สมบูรณ์ +- ตั้งค่า `OfficeMathExportMode` เป็น `LaTeX` เพื่อเรนเดอร์สมการอย่างสะอาด +- Implement `ResourceSavingCallback` เพื่อควบคุมการส่งออกรูปภาพ +- เปิดใช้งาน `PdfCompliance.PdfUAXmpA2` และ `ExportFloatingShapesAsInlineTag` เพื่อให้ได้ PDF ตามมาตรฐาน + +### สิ่งที่ควรสำรวจต่อ? + +- **CSS แบบกำหนดเองสำหรับ Markdown** – สร้างสไตล์ชีตที่สะท้อนสไตล์ใน Word ของคุณ +- **การประมวลผลแบบแบตช์** – วนลูปผ่านโฟลเดอร์ของไฟล์ `.docx` เพื่อทำการย้ายข้อมูลจำนวนมากอัตโนมัติ +- **ฟีเจอร์ PDF/UA ขั้นสูง** – เพิ่มแท็กกำหนดเอง, ตั้งค่าแอตทริบิวต์ภาษา, หรือฝังคำอธิบายเสียง +- **การรวมกับ CI/CD** – ทำให้ทุกการสร้างผลิต PDF ที่เข้าถึงได้โดยอัตโนมัติ + +หากคุณเจออุปสรรคใด ๆ ให้ตรวจสอบว่าเวอร์ชัน Aspose.Words ของคุณตรงกับ API ที่ใช้ในที่นี้ และอย่าลืมว่าเอกสารของไลบรารีเองเป็นแหล่งอ้างอิงรองที่ดี + +ขอให้เขียนโค้ดอย่างสนุกและขอให้เอกสารของคุณทั้งสวยงาม **และ** เข้าถึงได้! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/programming-with-txtsaveoptions/_index.md b/words/thai/net/programming-with-txtsaveoptions/_index.md index 6d5e19b143..138088704b 100644 --- a/words/thai/net/programming-with-txtsaveoptions/_index.md +++ b/words/thai/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ - [เพิ่มเครื่องหมาย Bidi ในเอกสาร Word](./add-bidi-marks/) | เรียนรู้วิธีการเพิ่มเครื่องหมายทิศทางสองทาง (Bidi) ในเอกสาร Word โดยใช้ Aspose.Words สำหรับ .NET ด้วยคู่มือนี้ รับรองทิศทางข้อความที่ถูกต้องสำหรับเนื้อหาหลายภาษา - | [ใช้อักขระแท็บต่อระดับสำหรับการเยื้องรายการ](./use-tab-character-per-level-for-list-indentation/) | เรียนรู้วิธีการสร้างรายการหลายระดับพร้อมการเยื้องแบบแท็บโดยใช้ Aspose.Words สำหรับ .NET ปฏิบัติตามคู่มือนี้เพื่อการจัดรูปแบบรายการที่แม่นยำในเอกสารของคุณ - | [ใช้ช่องว่างต่อระดับสำหรับการเยื้องรายการ](./use-space-character-per-level-for-list-indentation/) | เรียนรู้วิธีการสร้างรายการหลายระดับพร้อมการเยื้องอักขระช่องว่างใน Aspose.Words สำหรับ .NET คำแนะนำทีละขั้นตอนสำหรับการจัดรูปแบบเอกสารอย่างแม่นยำ | - +- [บันทึก docx เป็น txt – ส่งออกสมการ Word ไปเป็น LaTeX ด้วย C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | เรียนรู้วิธีแปลงไฟล์ docx เป็น txt พร้อมส่งออกสมการ Word เป็น LaTeX ด้วย C# - {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/thai/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/thai/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..bf5c8e6eaa --- /dev/null +++ b/words/thai/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-04-05 +description: บันทึกไฟล์ docx เป็น txt ด้วย Aspose.Words – แปลง Word เป็น txt อย่างรวดเร็วและเรียนรู้วิธีส่งออกสมการคณิตศาสตร์เป็น + LaTeX โค้ด C# ง่าย ไม่ต้องใช้เครื่องมือเสริม +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: th +og_description: บันทึกไฟล์ docx เป็น txt ด้วย C# และดูวิธีส่งออกคณิตศาสตร์เป็น LaTeX ทำตามคู่มือขั้นตอนต่อขั้นตอนนี้เพื่อแปลง Word เป็น txt พร้อมสมการที่คงอยู่. +og_title: บันทึก docx เป็น txt – ส่งออกสมการ Word ไปเป็น LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: บันทึก docx เป็น txt – ส่งออกสมการ Word ไปยัง LaTeX ด้วย C# +url: /th/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# บันทึก docx เป็น txt – ส่งออกสมการ Word เป็น LaTeX ด้วย C# + +เคยต้อง **บันทึก docx เป็น txt** แล้วกังวลว่าสมการของคุณจะหายไปหรือกลายเป็นอักขระที่อ่านไม่ออกหรือไม่? คุณไม่ได้เป็นคนเดียว นักพัฒนาหลายคนเจออุปสรรคนี้เมื่อต้อง **แปลง word เป็น txt** เพื่อการประมวลผลต่อไป โดยเฉพาะเมื่อไฟล์ต้นทางมีวัตถุ Office Math อยู่ + +ข่าวดีคือ? ด้วยไม่กี่บรรทัดของ C# และตัวเลือกที่เหมาะสม คุณไม่เพียงแต่ **แปลง Word เป็น txt** แต่ยังคงสมการทุกสมการเป็น markup LaTeX ที่สะอาด ในบทแนะนำนี้เราจะเดินผ่านกระบวนการทั้งหมด อธิบายว่าทำไมแต่ละการตั้งค่าถึงสำคัญ และแสดงวิธีตรวจสอบผลลัพธ์ + +เราจะครอบคลุม: + +* การติดตั้งไลบรารี Aspose.Words for .NET +* การโหลดไฟล์ `.docx` ที่มีสมการคณิตศาสตร์ +* การกำหนดค่า `TxtSaveOptions` เพื่อให้ **วิธีการส่งออกสมการ** กลายเป็นสตริงที่เป็นมิตรกับ LaTeX +* การบันทึกไฟล์และตรวจสอบผลลัพธ์ + +เมื่อเสร็จสิ้น คุณจะได้สคริปต์ที่นำกลับมาใช้ใหม่ได้ซึ่งทำให้คุณ **บันทึก docx เป็น txt** พร้อมคงสูตรทุกสูตรเป็น LaTeX—เหมาะสำหรับ pipeline ทางวิทยาศาสตร์, static site generators หรือ workflow ใด ๆ ที่ต้องการคณิตศาสตร์แบบ plain‑text + +--- + +## ข้อกำหนดเบื้องต้น + +ก่อนที่เราจะลงลึก โปรดตรวจสอบว่าคุณมี: + +* .NET 6.0 หรือใหม่กว่า (โค้ดนี้ยังทำงานกับ .NET Framework 4.6+ ด้วย) +* Visual Studio 2022 (หรือ IDE ใด ๆ ที่คุณชอบ) +* แพ็กเกจ NuGet **Aspose.Words for .NET** – ติดตั้งด้วย + +```bash +dotnet add package Aspose.Words +``` + +ไม่ต้องใช้ตัวแปลงเพิ่มเติมหรือเครื่องมือภายนอก; Aspose.Words จะจัดการส่วนที่หนักให้เอง + +--- + +## ขั้นตอนที่ 1: ติดตั้งและอ้างอิง Aspose.Words + +แรกสุดให้เพิ่มไลบรารีเข้าในโปรเจกต์ของคุณ หากคุณใช้ command line ให้รันคำสั่งด้านบน ใน Visual Studio คุณก็สามารถคลิกขวา **Dependencies → Manage NuGet Packages** แล้วค้นหา *Aspose.Words* + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **เคล็ดลับ:** ใช้เวอร์ชัน stable ล่าสุด (ณ เมษายน 2026 คือ 24.10) รุ่นใหม่มักมีการแก้บั๊กสำหรับการจัดการ OfficeMath ทำให้คุณหลีกเลี่ยงสัญลักษณ์ที่หายไปโดยไม่คาดคิด + +--- + +## ขั้นตอนที่ 2: โหลดเอกสารต้นฉบับ + +ต่อไปเราจะดึงไฟล์ `.docx` ที่มีสมการที่คุณต้องการเก็บไว้ คลาส `Document` จะทำหน้าที่เป็นตัวแทนของไฟล์ Word ทั้งหมด ให้คุณเข้าถึงข้อความ, รูปภาพ, และวัตถุ Office Math + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +ทำไมต้องโหลดก่อน? Aspose.Words จะทำการพาร์สไฟล์เป็นโมเดลวัตถุ ทำให้เราสามารถตรวจสอบหรือแก้ไขเนื้อหาได้ก่อนตัดสินใจว่าจะส่งออกอย่างไร นี่คือจุดที่ **วิธีการส่งออกสมการ** เริ่มมีความสำคัญ + +--- + +## ขั้นตอนที่ 3: กำหนดค่า TxtSaveOptions สำหรับการส่งออกเป็น LaTeX + +หัวใจของวิธีแก้คือคลาส `TxtSaveOptions` โดยค่าเริ่มต้น การบันทึกเป็น TXT จะลบ Office Math ทั้งหมดออก การตั้งค่า `OfficeMathExportMode` เป็น `LaTeX` จะบอกไลบรารีให้แปลงสมการแต่ละอันเป็นรูปแบบ LaTeX + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**ทำไมต้อง LaTeX?** LaTeX เป็นภาษากลางของการเผยแพร่ทางวิทยาศาสตร์ การส่งออกคณิตศาสตร์แบบนี้ทำให้คุณคงความหมายของสมการไว้ แทนที่จะเป็นภาพแบนหรือสตริงที่อ่านไม่ออก หากคุณต่อไปใส่ไฟล์ TXT นี้ลงในโปรเซสเซอร์ Markdown ที่รองรับ MathJax สมการก็จะแสดงผลได้อย่างสมบูรณ์ + +--- + +## ขั้นตอนที่ 4: บันทึกเอกสารเป็น plain‑text + +เมื่อกำหนดตัวเลือกเรียบร้อย ขั้นตอนสุดท้ายคือบรรทัดเดียวที่เขียนไฟล์ลงดิสก์ + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +เท่านี้—ไฟล์ `.docx` ของคุณก็กลายเป็นไฟล์ `.txt` ที่มีสมการทุกสมการเป็น snippet ของ LaTeX พร้อมสำหรับการใช้งานต่อไป + +--- + +## การตรวจสอบผลลัพธ์ (วิธีบันทึก txt อย่างถูกต้อง) + +เปิด `MathSample.txt` ด้วยโปรแกรมแก้ไขข้อความใด ๆ คุณควรเห็นอย่างเช่น: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +หากคุณพบอักขระเฉพาะของ Word (เช่น `?` หรือสัญลักษณ์ที่หายไป) ให้ตรวจสอบว่า: + +* คุณใช้เวอร์ชัน Aspose.Words ล่าสุด (เวอร์ชันเก่ามีบั๊กกับ OfficeMath) +* เอกสารต้นทางจริง ๆ มีวัตถุ **OfficeMath** ไม่ใช่วัตถุ Legacy Equation Editor หากเป็นแบบหลัง คุณอาจต้องแปลงด้วยตนเองหรือใช้เมธอด `ConvertMathToOfficeMath` ก่อนบันทึก + +--- + +## ความแปรผันทั่วไปและกรณีขอบ + +| สถานการณ์ | วิธีทำ | +|-----------|--------| +| **วัตถุ Legacy Equation Editor** | เรียก `doc.ConvertMathToOfficeMath()` ก่อนขั้นตอน 3 | +| **ต้องการคณิตศาสตร์ Unicode ธรรมดา ไม่ใช่ LaTeX** | ตั้งค่า `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode` | +| **เอกสารขนาดใหญ่ (100 + MB)** | ใช้การสตรีมการบันทึกด้วย `doc.Save(Stream, txtOptions)` เพื่อลดการใช้หน่วยความจำ | +| **ต้องการเก็บชื่อไฟล์ต้นฉบับ** | ใช้ `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` เมื่อสร้างเส้นทางไฟล์ผลลัพธ์ | + +การปรับแต่งเหล่านี้ตอบคำถาม “**วิธีการส่งออกสมการ**” สำหรับ pipeline ต่าง ๆ ทำให้โซลูชันของคุณมั่นคงไม่ว่าที่มาจะเป็นแบบใด + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (รวมทุกขั้นตอนในที่เดียว) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +รันโปรแกรม เปิดไฟล์ `.txt` ที่สร้างขึ้น และคุณจะเห็นสมการ LaTeX ฝังอยู่ตรงที่ควรจะเป็น นี่คือวิธีที่ตรงไปตรงมาที่สุดในการ **แปลง + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/thai/net/working-with-fonts/_index.md b/words/thai/net/working-with-fonts/_index.md index b32fe4c65b..ab93c24824 100644 --- a/words/thai/net/working-with-fonts/_index.md +++ b/words/thai/net/working-with-fonts/_index.md @@ -45,6 +45,7 @@ | [การตั้งค่าแบบอักษรเริ่มต้น](./font-settings-default-instance/) | ในบทช่วยสอนนี้ เรียนรู้วิธีการกำหนดค่าการตั้งค่าแบบอักษรเริ่มต้นในเอกสาร Word ด้วย Aspose.Words สำหรับ .NET - | [รับรายชื่อแบบอักษรที่มีให้เลือก](./get-list-of-available-fonts/) | ค้นพบวิธีรับรายการแบบอักษรที่พร้อมใช้งานโดยใช้ Aspose.Words สำหรับ .NET ในบทช่วยสอนแบบทีละขั้นตอนโดยละเอียดนี้ พัฒนาทักษะการจัดการแบบอักษรของคุณ - | [รับการแจ้งเตือนแบบอักษร](./receive-notifications-of-fonts/) | เรียนรู้วิธีรับการแจ้งเตือนแบบอักษรที่ขาดหายหรือถูกแทนที่เมื่อใช้ Aspose.Words สำหรับ .NET - +- [Aspose การแทนที่แบบอักษร – ตรวจจับแบบอักษรที่หายไปในเอกสาร Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | เรียนรู้วิธีตรวจจับแบบอักษรที่หายไปในเอกสาร Word ด้วย Aspose.Words สำหรับ .NET - | [รับการแจ้งเตือน](./receive-warning-notification/) เรียนรู้วิธีรับการแจ้งเตือนเมื่อใช้ Aspose.Words สำหรับ .NET และจัดการปัญหาหรือคำเตือนต่างๆ ในเอกสารของคุณ - | [ตัวอย่างแหล่งที่มาของฟอนต์ Steam](./resource-steam-font-source-example/) | เรียนรู้วิธีใช้ Resource Stream Font Source เพื่อโหลดแบบอักษรที่กำหนดเองลงใน Aspose.Words สำหรับ .NET - | [รับการทดแทนโดยไม่ต้องมีคำต่อท้าย](./get-substitution-without-suffixes/) | ในบทช่วยสอนนี้ เรียนรู้วิธีรับการแทนที่แบบไม่มีคำต่อท้ายในเอกสาร Word ด้วย Aspose.Words สำหรับ .NET | diff --git a/words/thai/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/thai/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..ff69b7ef1a --- /dev/null +++ b/words/thai/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,215 @@ +--- +category: general +date: 2026-04-05 +description: คู่มือการแทนที่ฟอนต์ของ Aspose เพื่อค้นหาฟอนต์ที่หายไปขณะโหลดเอกสาร Word. + เรียนรู้วิธีตั้งค่าฟอนต์และจัดการฟอนต์ที่หายไปอย่างมีประสิทธิภาพ. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: th +og_description: คู่มือการแทนที่ฟอนต์ของ Aspose เพื่อค้นหาฟอนต์ที่หายไปขณะโหลดเอกสาร + Word. เรียนรู้การกำหนดค่าการตั้งค่าฟอนต์และจัดการฟอนต์ที่หายไปอย่างมีประสิทธิภาพ. +og_title: การแทนที่ฟอนต์ของ Aspose – ตรวจจับฟอนต์ที่หายไปในเอกสาร Word +tags: +- Aspose.Words +- C# +- Font Management +title: การแทนที่ฟอนต์ของ Aspose – ตรวจจับฟอนต์ที่หายไปในเอกสาร Word +url: /th/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – ตรวจจับฟอนต์ที่หายไปในเอกสาร Word + +เคยเจอไฟล์ Word ที่ดูสมบูรณ์แบบบนเครื่องหนึ่งแต่แสดงการเปลี่ยนแปลงฟอนต์แปลก ๆ บนเครื่องอื่นหรือไม่? นั่นคือปัญหา **aspose font substitution** คลาสสิก ซึ่งมักหมายความว่ามีฟอนต์บางตัวหายไปในระบบเป้าหมาย ในบทแนะนำนี้ เราจะสาธิตให้คุณเห็นขั้นตอน‑ต่อ​ขั้นตอนว่าอย่างไรในการ **detect missing fonts** เมื่อคุณ **load a Word document**, วิธี **configure font settings**, และวิธี **handle missing fonts** อย่างราบรื่น + +เราจะเดินผ่านตัวอย่าง C# ที่สมบูรณ์และสามารถรันได้, อธิบายว่าทำไมแต่ละบรรทัดถึงสำคัญ, และแม้แต่แสดงผลลัพธ์คอนโซลที่คุณควรคาดหวัง เมื่อจบคุณจะสามารถตรวจจับการแทนที่ฟอนต์ได้ทันทีที่เอกสารถูกโหลด—ไม่ต้องเดา + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีเปิดใช้งาน diagnostic collector ของ Aspose.Words สำหรับคำเตือนฟอนต์ +- โค้ดที่จำเป็นในการ **load a Word document** ด้วย **font settings** ที่กำหนดเอง +- วิธีวนลูป `WarningInfo` เพื่อแสดงฟอนต์ที่ถูกแทนที่ทั้งหมด +- เคล็ดลับการปิดการแจ้งเตือนที่ไม่ต้องการหรือการให้ฟอนต์สำรอง +- ตัวอย่างพร้อมรันที่คุณสามารถคัดลอก‑วางไปใช้ใน Visual Studio ได้ + +### ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (API ทำงานเช่นเดียวกันบน .NET Framework) +- Aspose.Words for .NET (แพ็กเกจ NuGet `Aspose.Words`) +- ไฟล์ Word ที่อ้างอิงฟอนต์ที่คุณไม่ได้ติดตั้ง (เช่น `MissingFont.docx`) + +หากคุณมีทั้งหมดนี้แล้ว, ไปดำน้ำกันเลย + +## Step 1 – Enable the Diagnostic Collector (Configure Font Settings) + +First things first: Aspose.Words only records font substitution warnings if you tell it to. That’s done by creating a `FontSettings` object and assigning it to a `LoadOptions` instance. Think of this as turning on the “debug lights” for font handling. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Why?** +Without a `FontSettings` object the warning collector stays silent, and you’ll never know which fonts were swapped. By initializing it empty we let Aspose use the default system fonts *and* keep track of any substitutions. + +> **Pro tip:** If you know a specific folder contains corporate fonts, point `FontSettings` there with `SetFontsFolder("path")`. That can reduce the number of missing‑font warnings. + +## Step 2 – Load the Document with the Configured Options (Load Word Document) + +Now that the collector is active, load your `.docx` file using the same `LoadOptions`. This is the moment where Aspose scans the document, looks for every font reference, and decides whether a substitution is needed. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Why does this matter?** +If you simply called `new Document("MissingFont.docx")`, the default settings would apply *and* the warning list would stay empty. Passing `loadOptions` guarantees that the diagnostic collector is hooked into the loading pipeline. + +## Step 3 – Retrieve and Display Font Substitution Warnings (Detect Missing Fonts) + +After the document is in memory, Aspose stores any warnings in `document.WarningCallback.Warnings`. Loop through that collection, filter for `WarningType.FontSubstitution`, and print the description. Each description tells you which font was missing and which one was used instead. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**ผลลัพธ์คอนโซลที่คาดหวัง** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +ผลลัพธ์นี้บอกคุณอย่างชัดเจนว่าฟอนต์ใดบ้างที่หายไปบนเครื่องที่รันโค้ด คุณสามารถตัดสินใจได้ว่าจะติดตั้งฟอนต์ที่หายไป, ฝังฟอนต์เหล่านั้นในเอกสาร, หรือปล่อยให้ใช้การแทนที่ต่อไป + +![การแทนที่ฟอนต์ของ aspose – ผลลัพธ์คอนโซลแสดงฟอนต์ที่ถูกแทนที่](/images/aspose-font-substitution-console.png) + +*ข้อความแทนภาพ:* การแทนที่ฟอนต์ของ aspose – ผลลัพธ์คอนโซลแสดงฟอนต์ที่ถูกแทนที่ + +## Step 4 – Optional: Customize the Substitution Behavior (Handle Missing Fonts) + +Sometimes you don’t just want to know *that* a substitution happened—you want to control *how* it happens. Aspose.Words lets you register a custom `IFontSubstitutionRule`. Below is a quick example that forces any missing font to fall back to `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**When would you use this?** +If you’re generating PDFs for a web service and you know every client can render `Tahoma`, forcing the fallback guarantees visual consistency without having to ship dozens of font files. + +## Full Working Example (All Steps Combined) + +Here’s the entire program you can paste into a new console project. It compiles as‑is, assuming you’ve installed the Aspose.Words NuGet package. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Run the program, watch the console, and you’ll see every missing‑font event printed out. From there you can decide whether to install the missing fonts, embed them, or keep the fallback. + +## คำถามที่พบบ่อย + +**Q: Does this work with PDF conversion?** +Yes. When you later call `doc.Save("output.pdf")`, any fonts that were substituted during loading will be the ones embedded in the PDF. So catching the warnings early helps you avoid surprise font changes in the final PDF. + +**Q: What if I have many documents to process?** +Wrap the loading logic in a try‑catch block and reuse a single `FontSettings` instance across documents. That reduces overhead and keeps the warning collector active for each file. + +**Q: Can I suppress the warnings entirely?** +You can set `loadOptions.WarningCallback = null;` before loading, but you’ll lose the ability to **detect missing fonts**—which is usually not what you want. + +## สรุป + +We’ve covered everything you need to master **aspose font substitution**: enabling the diagnostic collector, loading a Word file with custom **font settings**, extracting the list of missing fonts, and even overriding the default substitution rule to **handle missing fonts** your way. With just a few lines of C# you gain full visibility into font issues that would otherwise hide behind subtle layout changes. + +Next steps? Try embedding the original fonts into the document with `FontSettings.SetFontsFolder` or explore `FontSourceBase` to load fonts from a database. You might also experiment with the `Document.BuiltInStyle` collection to see how style‑level font changes propagate. + +Got more questions about Aspose.Words or font management? Drop a comment, explore the official Aspose documentation, or fire up a new project and play around with the code above. Happy coding, and may your documents always render exactly as intended! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/basic-conversions/_index.md b/words/turkish/net/basic-conversions/_index.md index e9f5c4eebc..ccde9c25d1 100644 --- a/words/turkish/net/basic-conversions/_index.md +++ b/words/turkish/net/basic-conversions/_index.md @@ -26,6 +26,7 @@ Basic Conversions, Aspose.Words for .NET kitaplığını kullanarak temel belge | [Word Dosyasını PDF'ye Dönüştür](./docx-to-pdf/) Aspose.Words for .NET rehberimizle Word dosyalarını PDF'ye nasıl kolayca dönüştürebileceğinizi öğrenin. Hızlı ve güvenilir belge dönüşümü arayan geliştiriciler için mükemmeldir. | | [Word'ü PDF olarak kaydet – Aspose.Words Tam C# Rehberi](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Aspose.Words for .NET kullanarak C# ile Word belgelerini PDF'ye dönüştürmenin adım adım rehberi. | | [C# ile Word'ü PDF'ye Dönüştür – Aspose.Words Rehberi](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Aspose.Words for .NET ile C# kullanarak Word belgelerini PDF'ye nasıl dönüştüreceğinizi adım adım öğrenin. | +| [C# ile Word'ü PDF'ye Dönüştür – Aspose.Words Tam Kılavuzu](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Aspose.Words for .NET kullanarak C# ile Word belgelerini PDF'ye dönüştürmenin adım adım tam rehberi. | | [Docx'i Bayta Dönüştür](./docx-to-byte/) | Verimli belge işleme için Aspose.Words kullanarak .NET'te Docx'i bayt dizisine nasıl dönüştüreceğinizi öğrenin. Adım adım kılavuz dahildir. | | [Docx'i Epub'a Dönüştür](./docx-to-epub/) | DOCX'i Aspose.Words for .NET ile kolayca EPUB'a dönüştürün. .NET uygulamalarınıza kusursuz entegrasyon için eğitimimizi takip edin. | | [Docx'i Mhtml'e Dönüştürme ve E-posta Gönderme](./docx-to-mhtml-and-sending-email/) | Bu adım adım kılavuzda DOCX'i MHTML'e nasıl dönüştüreceğinizi ve Aspose.Words for .NET kullanarak e-postaları nasıl göndereceğinizi öğrenin. Kolay otomasyonla üretkenliğinizi artırın. | diff --git a/words/turkish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/turkish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..9ef05ca93e --- /dev/null +++ b/words/turkish/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,196 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words kullanarak C#'de Word'ü PDF'ye dönüştürün. docx dosyasını + PDF olarak kaydetmeyi, erişilebilir PDF dışa aktarmayı ve Word belgesini verimli + bir şekilde yüklemeyi öğrenin. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: tr +og_description: 'C#''ta Word''ü PDF''ye dönüştürün: adım adım rehber. docx dosyasını + PDF olarak kaydetmeyi, erişilebilir PDF dışa aktarmayı ve Aspose.Words kullanarak + Word belgesini yüklemeyi keşfedin.' +og_title: C#'de Word'ü PDF'ye Dönüştür – Tam Aspose.Words Öğreticisi +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: C#'ta Word'ü PDF'ye Dönüştür – Aspose.Words ile Tam Kılavuz +url: /tr/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# ile Word'ü PDF'e Dönüştürme – Tam Programlama Öğreticisi + +Kısa komut satırı araçlarıyla ya da üçüncü taraf hizmetlerle uğraşmadan **convert word to pdf** yapmanın nasıl olduğunu hiç merak ettiniz mi? Siz tek başınıza değilsiniz. Birçok geliştirici, bir müşterinin DOCX dosyasından doğrudan erişilebilir bir PDF istemesi durumunda bu engelle karşılaşır. İyi haber? Birkaç satır C# ve güçlü Aspose.Words kütüphanesiyle, bir Word belgesini anında standartlara uygun bir PDF'e dönüştürebilirsiniz. + +Bu rehberde bilmeniz gereken her şeyi adım adım ele alacağız: temel **load word document** konularından, doğru seçenekleri yapılandırarak **how to export accessible pdf**'ye, ve sonunda sonucu kaydederek **save docx as pdf**'yi güvenilir bir şekilde yapabilirsiniz. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz, çalıştırmaya hazır bir kod parçacığına sahip olacaksınız. + +> **Pro tip:** PDF/UA‑2 uyumluluğunu hedefliyorsanız (birçok devlet kurumunun gerektirdiği erişilebilirlik standardı), aynı kod ek bir adım gerektirmeden çalışır—sadece doğru `PdfCompliance` bayrağını ayarlayın. + +## Öğrenecekleriniz + +- Aspose.Words kullanarak C# içinde **load word document** nasıl yapılır. +- **how to export accessible pdf** için gerekli tam ayarlar (PDF/UA‑2). +- Bir metod çağrısı ile **save docx as pdf** yapan eksiksiz, çalıştırılabilir bir örnek. +- **c# convert docx pdf** yaparken karşılaşılan yaygın tuzaklar ve bunlardan nasıl kaçınılır. +- Oluşturulan PDF'in erişilebilirlik beklentilerini karşıladığını hızlıca doğrulamanın yolları. + +Harici araçlar yok, karmaşık yapılandırma dosyaları yok—sadece bugün derleyebileceğiniz saf C# kodu. + +## Önkoşullar + +İlerlemeye başlamadan önce şunların olduğundan emin olun: + +1. **.NET 6.0** (veya herhangi bir yeni .NET sürümü) yüklü olmalı. Eski framework'ler de çalışır, ancak aşağıdaki sözdizimi modern SDK'yı varsayar. +2. Aspose.Words for .NET için bir **license**. Kütüphane ücretsiz deneme sunar, ancak üretim için geçerli bir anahtar gerekir. +3. Projenize eklenmiş **Aspose.Words** NuGet paketi: + +```bash +dotnet add package Aspose.Words +``` + +Hepsi bu—ek ikili dosyalar yok, COM etkileşimi yok, sadece temiz bir NuGet referansı. + +![convert word to pdf using Aspose.Words in C#](image-placeholder.png "convert word to pdf using Aspose.Words in C#") + +## Adım‑Adım Uygulama + +Aşağıda süreci mantıksal parçalara ayırıyoruz. Her adım küçük bir kod snippet'i, **neden** önemli olduğuna dair bir açıklama ve gerçek dünyadan bir ipucu içerir. + +### ## Word'ü PDF'e Dönüştür – Kaynak Belgeyi Yükle + +İlk yapmanız gereken şey **load word document**'i belleğe yüklemektir. Aspose.Words, OpenXML ayrıştırmasını soyutlar, böylece DOCX, DOC veya hatta RTF dosyalarıyla format tuhaflıklarıyla uğraşmadan çalışabilirsiniz. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Neden Önemli:** +Dosyayı yüklemek, başlıklar, altbilgiler, stiller ve gizli meta veriler dahil olmak üzere tüm Word dosyasını temsil eden bir `Document` nesnesi oluşturur. Bu adımı atlayıp dosyayı ham bir akış olarak okumaya çalışırsanız, PDF'in nasıl görüneceğini belirleyen düzen bilgilerini kaybedersiniz. + +> **Not:** Aynı `Document` yapıcı `.doc` ve `.rtf` için de çalışır. Bu, kaynak kesinlikle bir DOCX olmasa bile **c# convert docx pdf** yapabileceğiniz anlamına gelir. + +### ## DOCX'i PDF Olarak Kaydet – PDF/UA‑2 Uyumluluğunu Yapılandır + +Şimdi belge bellekte olduğuna göre, Aspose.Words'a PDF'in nasıl oluşturulmasını istediğimizi söylüyoruz. Çoğu kullanım senaryosu için varsayılan ayarlar yeterlidir, ancak bir **accessible PDF**'ye ihtiyacınız olduğunda PDF/UA‑2 uyumluluk bayrağını etkinleştirmeniz gerekir. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Neden Önemli:** +`PdfCompliance.PdfUAXmpA2` kütüphaneye ekran okuyucuların ihtiyaç duyduğu gerekli etiket ve yapıları gömmesini söyler. Bu bayrak olmadan, görünüşte mükemmel bir PDF elde edebilir, ancak erişilebilirlik denetiminde başarısız olur. + +> **Tip:** Sadece normal bir PDF'ye ihtiyacınız varsa, `Compliance` satırını kaldırabilirsiniz. Diğer seçenekler hâlâ yüksek kaliteli bir çıktı verir. + +### ## Word'ü PDF'e Dönüştür – Dosyayı Yaz + +Seçenekler hazır olduğunda, son adım **save docx as pdf** yapmaktır. Bu tek çağrı tüm ağır işleri yapar: düzen dönüşümü, font gömme ve erişilebilirlik etiketleme. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Ne elde edersiniz:** +- `outputPath` konumunda Word düzenini yansıtan bir PDF dosyası. +- `PdfUAXmpA2` bayrağını kullandıysanız, PDF PDF/UA‑2 uyumlu olarak işaretlenir. +- Tüm fontlar gömülüdür, böylece dosya herhangi bir makinede aynı görünür. + +### ## Erişilebilir PDF'i Doğrula (İsteğe Bağlı ama Tavsiye Edilir) + +Dönüştürmeden sonra, PDF'in gerçekten **how to export accessible pdf** doğru bir şekilde yapıldığını iki kez kontrol etmek iyi bir fikirdir. Adobe Acrobat Reader'ın “Accessibility Check” özelliği gibi ücretsiz araçlar veya açık kaynak `pdfcpu` doğrulayıcısını kullanabilirsiniz. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Doğrulayıcı hata raporlamıyorsa, tam erişilebilirlik desteğiyle **convert word to pdf** işlemini başarıyla tamamlamış olursunuz. + +### ## C# ile DOCX'i PDF'e Dönüştürürken Yaygın Tuzaklar + +| Sorun | Neden Oluşur | Çözüm | +|-------|----------------|-----| +| Eksik fontlar | Kaynak DOCX, sunucuda yüklü olmayan özel bir font kullanıyor. | `EmbedFullFonts = true` olarak ayarlayın veya fontu makineye kurun. | +| Büyük dosya boyutu | Görseller tam çözünürlükte gömülüyor. | `ImageCompression = PdfImageCompression.Jpeg` kullanın ve `JpegQuality` değerini daha düşük bir seviyeye ayarlayın. | +| Kırık hiperlinkler | Bağlantılar, istemcide bulunmayan göreli yollara işaret ediyor. | URL'lerin mutlak olduğundan emin olun veya `HyperlinkTarget` özelliğini ayarlayın. | +| Erişilebilirlik etiketleri eksik | `Compliance` bayrağı ayarlanmamış. | Yukarıda gösterildiği gibi `Compliance = PdfCompliance.PdfUAXmpA2` ekleyin. | + +Bunları akılda tutmak, **c# convert docx pdf** rutinizi sağlam ve üretime hazır hâle getirecektir. + +## Tam Çalışan Örnek + +Hepsini bir araya getirerek, şu anda derleyip çalıştırabileceğiniz bağımsız bir konsol uygulaması burada. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Beklenen sonuç:** Programı çalıştırdıktan sonra `C:\Docs` içinde `output.pdf` dosyasını bulacaksınız. Herhangi bir PDF görüntüleyicide açın; düzen `input.docx` ile piksel piksel eşleşmeli ve bir erişilebilirlik kontrolü PDF/UA‑2 uyumluluğunu doğrulayacaktır. + +## Sonuç + +C# ve Aspose.Words kullanarak **convert word to pdf** yapmanın eksiksiz, uçtan uca bir çözümünü adım adım inceledik. **load word document**'i gerçekleştirerek, doğru `PdfSaveOptions`'ı yapılandırarak ve sonunda **save docx as pdf** yaparak, minimum kodla yüksek kaliteli, erişilebilir bir PDF elde edersiniz. İster bir belge‑oluşturma mikroservisi, ister yerel bir toplu dönüştürücü inşa ediyor olun, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-markdownsaveoptions/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/_index.md index 5be26b20dc..251571cb43 100644 --- a/words/turkish/net/programming-with-markdownsaveoptions/_index.md +++ b/words/turkish/net/programming-with-markdownsaveoptions/_index.md @@ -29,9 +29,11 @@ Words Processing with MarkdownSaveOptions, .NET için Aspose.Words kütüphanesi | [docx'i markdown'a dönüştür – Adım Adım C# Rehberi](./convert-docx-to-markdown-step-by-step-c-guide/) | Aspose.Words for .NET kullanarak docx dosyalarını adım adım markdown formatına dönüştürün. | | [docx'i markdown olarak kaydet – LaTeX denklemleriyle Tam C# Rehberi](./save-docx-as-markdown-complete-c-guide-with-latex-equations/) | Aspose.Words for .NET kullanarak docx dosyalarını LaTeX denklemleriyle markdown formatına dönüştürün. Tam C# rehberi. | | [docx'i markdown olarak kaydet – Görüntü Çıkarma ile Tam C# Rehberi](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Aspose.Words for .NET kullanarak docx dosyalarını markdown formatına dönüştürün ve görüntüleri ayıklayın. Tam C# rehberi. | +| [DOCX'i Markdown'a Dönüştür – Aspose.Words ile Görüntü Çıkarma](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Aspose.Words for .NET ile docx dosyalarını markdown'a dönüştürün ve içindeki görüntüleri ayıklayın. Tam C# rehberi. | | [Word'den Markdown Dışa Aktarma – Tam C# Rehberi](./how-to-export-markdown-from-word-complete-c-guide/) | Aspose.Words for .NET kullanarak Word belgelerini Markdown formatına dışa aktarmayı öğrenin. Tam C# rehberiyle adım adım ilerleyin. | | [DOCX'ten Markdown Kaydetme – Adım Adım Rehber](./how-to-save-markdown-from-docx-step-by-step-guide/) | Aspose.Words for .NET kullanarak DOCX dosyasını Markdown formatına kaydetmeyi adım adım öğrenin. | | [DOCX'ten Markdown Dışa Aktarma – Tam Rehber](./how-to-export-markdown-from-docx-complete-guide/) | Aspose.Words for .NET kullanarak DOCX dosyasını Markdown formatına dışa aktarmayı adım adım öğrenin. | +| [Word'ü Markdown'a Dönüştür – PDF/UA Dışa Aktarma ile Tam Rehber](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Aspose.Words for .NET kullanarak Word belgelerini PDF/UA uyumlu olarak dışa aktarın ve Markdown'a dönüştürün. Tam C# rehberi. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..a2faf827ac --- /dev/null +++ b/words/turkish/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,315 @@ +--- +category: general +date: 2026-04-05 +description: DOCX'i Markdown'a dönüştürmeyi ve DOCX'ten resimleri C# ile çıkarmayı + öğrenin. Tam kod ve ipuçlarıyla adım adım rehber. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: tr +og_description: Aspose.Words kullanarak DOCX'i Markdown'a dönüştürün ve DOCX'ten görselleri + çıkarın. Kod, açıklama ve en iyi uygulama ipuçlarıyla tam bir C# öğreticisi. +og_title: DOCX'i Markdown'a Dönüştür – DOCX'ten Görselleri C# ile Çıkar +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: DOCX'i Markdown'a Dönüştür – Aspose.Words ile DOCX'ten Görselleri Çıkar +url: /tr/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# DOCX'i Markdown'e Dönüştür – DOCX'ten Görselleri C# ile Çıkar + +DOCX'i **Markdown'e dönüştürmek** istediğinizde ama çıktıda görsellerin kaybolmasıyla mı mücadele ettiniz? Tek başınıza değilsiniz. Birçok projede markdown sürümü sürüm kontrolü veya statik‑site jeneratörleri için mükemmeldir, ancak resimler geride kalır ve zengin bir belgeyi çorak bir metin dosyasına dönüştürür. + +İyi haber? Birkaç satır C# ve Aspose.Words ile **DOCX'i Markdown'e dönüştürebilir** *ve* **DOCX'ten görselleri otomatik olarak çıkarabilirsiniz**. Bu kılavuz, tüm süreci adım adım anlatır, her parçanın neden önemli olduğunu açıklar ve görsel klasörünüzü düzenli tutmanın yollarını gösterir. + +## Öğrenecekleriniz + +- Resim içeren bir DOCX dosyasını nasıl yüklersiniz. +- Her görselin nereye kaydedileceğini belirleyen özel bir `IResourceSavingCallback` nasıl tanımlanır. +- Oluşturulan markdown'ın çıkarılan görsellere doğru şekilde referans vermesi için `MarkdownSaveOptions` nasıl yapılandırılır. +- Çift görsel adları veya PNG olmayan formatlar gibi kenar durumlarını ele almak için ipuçları. +- Bugün çalıştırabileceğiniz, tamamen kopyala‑yapıştır hazır bir kod örneği. + +### Önkoşullar + +- .NET 6.0 veya üzeri (API .NET Core, .NET Framework ve .NET 5+ üzerinde çalışır). +- **Aspose.Words for .NET** lisansı (ücretsiz deneme sürümü test için yeterlidir). +- C# ve Visual Studio (veya tercih ettiğiniz IDE) konusunda temel bilgi. + +Eğer bunlara sahipseniz, hemen başlayalım. + +--- + +## Adım 1: Projeyi Oluşturun ve Aspose.Words'u Yükleyin + +İlk olarak yeni bir console uygulaması oluşturun (veya mevcut bir çözüme entegre edin). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Pro ipucu:** En yeni NuGet sürümünü (Nisan 2026 itibarıyla 24.12) kullanın; böylece en yeni markdown dışa aktarma iyileştirmelerinden faydalanırsınız. + +--- + +## Adım 2: Görselleri İstediğiniz Yere Kaydedecek Bir Geri Çağırma (Callback) Oluşturun + +Aspose.Words, markdown dışa aktarımı sırasında yazılan her kaynağı (görseller, SVG'ler vb.) yakalamanıza izin verir. `IResourceSavingCallback` uygulayarak şunları yapabilirsiniz: + +1. Markdown dosyanızın yanına bir klasör seçin. +2. Benzersiz bir dosya adı oluşturun (böylece mevcut bir görseli asla üzerine yazmazsınız). +3. Formatı belirleyin (burada tutarlılık için PNG zorunlu kılıyor). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Neden GUID‑tabanlı bir ad? + +Kaynak DOCX aynı orijinal ada sahip iki resim içeriyorsa, basit bir kopyala‑yapıştır birini üzerine yazar. `Guid.NewGuid()` kullanmak benzersizliği garantiler; bu, dönüşümü otomatik bir pipeline’da birçok kez çalıştırdığınızda özellikle kullanışlıdır. + +--- + +## Adım 3: DOCX'i Yükleyin ve Markdown Seçeneklerini Bağlayın + +Şimdi belgeyi belleğe alıp az önce oluşturduğumuz geri çağırmayı ekliyoruz. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Kodun ne yaptığını adım adım inceleyelim + +| Adım | Amaç | +|------|------| +| **Yolları tanımla** | Projenizi esnek tutar; yeniden derlemeden istediğiniz klasöre işaret edebilirsiniz. | +| **DOCX'i yükle** | `Document` Word dosyasını ayrıştırır, tüm öğelere (paragraflar, tablolar, resimler) erişim sağlar. | +| **`MarkdownSaveOptions`'ı yapılandır** | `ResourceSavingCallback` görselleri çıkaran kancadır. Bu olmadan Aspose.Words ayarlara bağlı olarak görselleri base64 olarak gömebilir ya da tamamen atabilir. | +| **Kaydet** | `doc.Save` markdown dosyasını yazar ve her görsel için geri çağırmayı tetikler. | + +--- + +## Adım 4: Çıktıyı Doğrulayın – Ne Görmelisiniz? + +Programı çalıştırdıktan sonra `DocWithImages.md` dosyasını açın. Aşağıdaki gibi markdown görsel bağlantılarını göreceksiniz: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Ve `C:\Docs\MarkdownResources` içinde GUID adlı bir dizi PNG dosyası bulacaksınız. Her birini açın – orijinal DOCX içinde gömülü resimlerle aynı olmalı. + +Markdown dosyasını, göreli yolları destekleyen bir görüntüleyicide (ör. VS Code önizlemesi, GitHub veya bir statik‑site jeneratörü) açarsanız, görseller Word'de olduğu gibi görüntülenecektir. + +### Yaygın Tuzaklar & Nasıl Önlenir + +| Belirti | Muhtemel Neden | Çözüm | +|---------|----------------|------| +| Görseller kırık bağlantı olarak görünüyor | `ResourceFileName` ayarlanmamış, bu yüzden markdown var olmayan bir dosyaya işaret ediyor. | Geri çağırma içinde `args.ResourceFileName = newFileName;` satırının olduğundan emin olun. | +| PNG dosyaları çok büyük | Orijinal görseller JPEG veya BMP idi; PNG'ye dönüştürmek boyutu artırabilir. | `args.ResourceContentType` ile orijinal formatı tespit edin ve koruyun: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Çift görseller hâlâ görünüyor | Statik bir dosya adı yerine GUID kullanmadınız. | GUID mantığına geri dönün veya görsel tipine göre bir sayaç ekleyin. | +| Dönüşüm `FileNotFoundException` hatası veriyor | DOCX dosya yolu yanlış veya klasörde okuma izni yok. | Yolu kontrol edin ve gerekli dosya sistemi izinlerini verin. | + +--- + +## Adım 5: İleri Düzey Ayarlamalar (İsteğe Bağlı) + +### 5.1 Orijinal Görsel Formatlarını Koruyun + +Çıktı görsellerinin orijinal uzantılarını korumak isterseniz geri çağırmayı şu şekilde değiştirin: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Görselleri Base64 Olarak Göm (Ayrı Dosyalar İstemediğinizde) + +Bazen tek dosyalı bir markdown tercih edilir (ör. e‑posta ile gönderim). Seçeneği şu şekilde değiştirin: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Ancak unutmayın: **DOCX'ten görselleri çıkar** çoğu statik‑site iş akışı için birincil hedeftir, bu yüzden klasör yaklaşımı genellikle daha iyi bir seçimdir. + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +Aşağıda tüm program tek bir dosyada verilmiştir. Yolları kendi ortamınıza göre değiştirin ve çalıştırın. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +`dotnet run` ile çalıştırın. Konsol ✅ satırını yazdırdığında markdown dosyasını açın; görsellerin doğru şekilde görüntülendiğini göreceksiniz. + +--- + +## Sonuç + +Artık **DOCX'i Markdown'e dönüştürmek ve DOCX'ten görselleri çıkarmak** için Aspose.Words kullanarak C# içinde **tam, üretim‑hazır bir çözüme** sahipsiniz. Ana anahtar kelime kılavuz boyunca tekrar edildi, bu da arama motorları ve AI asistanları için alaka düzeyini artırır. + +Tek bir geçişte kod: + +1. Word belgesini yükler. +2. Her görseli `IResourceSavingCallback` ile yakalar. +3. Görselleri benzersiz bir adla tahmin edilebilir bir klasöre kaydeder. +4. Bu görsellere referans veren markdown üretir. + +Buradan itibaren: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/turkish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..23b4c37d40 --- /dev/null +++ b/words/turkish/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-05 +description: Word'ü hızlıca Markdown'a dönüştürün ve ayrıca C#'ta PDF/UA olarak nasıl + kaydedileceğini öğrenin. Adım adım kod, ipuçları ve uç durum yönetimi. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: tr +og_description: Aspose.Words ile Word'ü Markdown'a dönüştürün ve PDF/UA olarak kaydedin. + Nedenini, nasıl yapılacağını ve en iyi uygulama ipuçlarını tek bir özlü rehberde + öğrenin. +og_title: Word'ü Markdown'a Dönüştür – Tam C# Öğreticisi +tags: +- Aspose.Words +- C# +- Document Conversion +title: Word'ü Markdown'a Dönüştür – PDF/UA Dışa Aktarımlı Tam Kılavuz +url: /tr/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Word'ü Markdown'a Dönüştür – PDF/UA Dışa Aktarma ile Tam Kılavuz + +Hiç **Word'ü Markdown'a dönüştür**ürken denklemleri veya görselleri kaybetmeden yapmanın mümkün olup olmadığını merak ettiniz mi? Tek başınıza değilsiniz. Birçok geliştirici, `.docx` dosyalarını temiz Markdown'a dönüştürürken aynı zamanda **PDF/UA olarak kaydet**me imkanı sunan güvenilir bir yol arıyor. Bu öğreticide, Aspose.Words for .NET kullanarak tam, çalıştırmaya hazır bir çözümü adım adım inceleyecek, her ayarın neden önemli olduğunu açıklayacak ve OfficeMath ile yüzen şekiller gibi daha karmaşık bölümleri nasıl yöneteceğinizi göstereceğiz. + +Bu rehberin sonunda tek bir C# programına sahip olacaksınız: + +1. Bozulmuş dosyaların çalışmayı durdurmaması için gevşek kurtarma (relaxed recovery) ile bir Word belgesi yüklenecek. +2. Denklemleri LaTeX'e çeviren ve görselleri özel bir geri çağırma (callback) aracılığıyla kaydeden bir Markdown dışa aktarımı yapılacak. +3. Aynı belge, yüzen şekilleri satır içi etiketler olarak gömerek PDF/UA‑2 uyumlu bir dosya olarak kaydedilecek. + +Kulağa çok şey gibi geliyor mu? Endişelenmeyin—hadi başlayalım. + +## Gereksinimler + +- **Aspose.Words for .NET** (yazım anındaki en son sürüm, 23.x). +- Bir .NET geliştirme ortamı (Visual Studio 2022, Rider veya `dotnet` CLI). +- Referans alabileceğiniz bir klasöre yerleştirilmiş örnek bir Word dosyası (`input.docx`). +- C# sözdizimine temel aşinalık—özel bir şey yok, sadece birkaç `using` ifadesi yeterli. + +> **Pro ipucu:** NuGet paket yöneticisi kullanıyorsanız, kütüphaneyi şu komutla ekleyin +> `dotnet add package Aspose.Words` ya da Visual Studio NuGet UI üzerinden. + +## Adım 1 – Gevşek Kurtarma ile Word Belgesini Yükle + +Harici kaynaklardan gelen Word dosyaları küçük bozulmalar içerebilir. **Gevşek** kurtarma (Relaxed) etkinleştirildiğinde Aspose.Words bir istisna fırlatmak yerine devam eder. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Neden önemli:** +- `RecoveryMode.Relaxed` tek bir hatalı paragrafın tüm dönüşümü durdurmasını engeller. +- Bir `FontSettings` nesnesi sağlamak, eksik yazı tiplerinin sorunsuz bir şekilde ikame edilmesini sağlar; bu, denklemleri daha sonra LaTeX olarak render ederken kritik öneme sahiptir. + +## Adım 2 – Markdown'a Dışa Aktar (OfficeMath → LaTeX, Görseller Geri Çağırma ile) + +Markdown, Word denklemlerini yerel olarak temsil edemez. Aspose.Words, **OfficeMath** nesnelerini çoğu Markdown rendercısının anlayabileceği LaTeX'e çevirebilir. Görseller ise bir yere kaydedilmelidir; özel bir **kaynak‑kaydetme geri çağırması** klasör yapısı ve adlandırma üzerinde tam kontrol sağlar. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Kaynak‑Kaydetme Geri Çağırması + +Aşağıda, her görseli `images` adlı bir alt‑klasöre kaydeden ve dosyaları `img001.png`, `img002.png` gibi adlandıran küçük bir uygulama yer alıyor. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Neden buna ihtiyacınız var:** +- Bir geri çağırma olmadan Aspose.Words rastgele GUID adlarıyla düz bir klasör oluşturur; bu da sürüm kontrolünü zorlaştırır. +- Adlandırma şemasını kontrol ederek Markdown deposunu düzenli ve yeniden üretilebilir tutarsınız. + +### Beklenen Markdown Çıktısı + +Programı çalıştırdıktan sonra `doc.md` dosyasını açtığınızda şunu göreceksiniz: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Denklemler `$$ … $$` içinde LaTeX olarak yer alır ve görseller, az önce oluşturduğunuz `images` klasörüne referans verir. + +## Adım 3 – PDF/UA‑2 (Erişilebilirlik‑Hazır) Olarak Dışa Aktar + +Belgeyi ekran okuyucular veya diğer yardımcı teknolojilere ihtiyaç duyan kullanıcılarla paylaşmanız gerekiyorsa, **PDF/UA‑2** uyumluluğu altın standarttır. Aspose.Words bunu tek bir bayrakla zorlayabilir ve yüzen şekilleri satır içi etiketlere dönüştürerek dönüşüm sırasında kaybolmalarını önleyebilir. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Neden PDF/UA önemli:** +- PDF/UA (Evrensel Erişilebilirlik), oluşturulan PDF'in doğru etiketleme, mantıksal okuma sırası ve görseller için alternatif metin içermesini garanti eder. +- `ExportFloatingShapesAsInlineTag` ayarı, metin kutuları veya balonlar gibi şekillerin atlanmadığından veya yanlış konumlandırılmadığından emin olur; karmaşık düzenlerin dönüştürülmesinde sıkça karşılaşılan bir tuzaktır. + +### PDF/UA Uyumluluğunu Doğrulama + +Dışa aktarmadan sonra PDF'i Adobe Acrobat Pro'da açın ve **“Accessibility Check”** (Araçlar → Erişilebilirlik → Tam Kontrol) çalıştırın. Araç **0 hata** rapor ediyorsa başarılı olmuşsunuz demektir. + +## Kenar Durumları & Yaygın Tuzaklar + +| Durum | Dikkat Edilmesi Gereken | Çözüm / Öneri | +|----------------------------------------|----------------------------------------------------------|----------------------------------------------------------| +| Word dosyası **desteklenmeyen yazı tipleri** içeriyor | Yazı tipleri ikame edilebilir, denklem düzeni bozulabilir | Geri dönüş yazı tipleriyle özel bir `FontSettings` sağlayın. | +| Büyük belgeler (> 100 MB) | Dönüşüm sırasında bellek baskısı | `LoadOptions` ile `LoadFormat.Docx` kullanın ve dosyayı akış (stream) olarak işleyin. | +| Görseller **EMF/WMF** vektör grafikleri | İstenmeyen şekilde rasterleştirilebilir | Kaydetmeden önce `ImageSaveOptions` ile PNG'ye dönüştürün. | +| PDF/UA, **iç içe tablolar** üzerinde doğrulama hatası veriyor | Etiketleme belirsizleşebilir | Motoru desteklemek için `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` etkinleştirin. | +| Özel stilleri **korumak** gerekiyor | Markdown sınırlı stil yeteneklerine sahiptir | Markdown ile birlikte bir CSS dosyası dışa aktarın ve ona referans verin. | + +## Tam Çalışan Örnek (Tüm Kod Birlikte) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Programı çalıştırın; `doc.md` (LaTeX denklemleri ve temiz görsel bağlantılarıyla) ve `doc.pdf` (tamamen PDF/UA‑2 uyumlu) dosyalarını `YOUR_DIRECTORY` içinde bulacaksınız. + +## Görsel Genel Bakış + +![Word'ü markdown'a dönüştürme örneği](https://example.com/placeholder.png "Word'ü markdown'a dönüştürme örneği – giriş Word dosyasını, Markdown çıktısını ve PDF/UA dosyasını gösterir") + +*Alt metin:* **Word'ü markdown'a dönüştürme örneği** – bir Word dosyasından Markdown ve PDF/UA'ya dönüşüm hattını gösteren diyagram. + +## Özet & Sonraki Adımlar + +**Word'ü Markdown'a dönüştürdük**, denklemleri bozulmadan koruduk, görselleri düzenli bir klasörde sakladık ve erişilebilirlik kontrollerini geçen **PDF/UA olarak kaydet** dosyası ürettik. Temel çıkarımlar şunlardır: + +- `LoadOptions.RecoveryMode.Relaxed` kullanarak kusurlu Word dosyalarına tolerans gösterin. +- Temiz denklem render'ı için `OfficeMathExportMode` değerini `LaTeX` olarak ayarlayın. +- Görsel çıktısını kontrol etmek için bir `ResourceSavingCallback` uygulayın. +- Standartlara uygun bir PDF için `PdfCompliance.PdfUAXmpA2` ve `ExportFloatingShapesAsInlineTag` özelliklerini etkinleştirin. + +### Sonra Neler Keşfedebilir? + +- **Markdown için Özel CSS** – Word stillerinizi yansıtan bir stil sayfası oluşturun. +- **Toplu işleme** – `.docx` dosyalarının bulunduğu bir klasörü döngüye alarak büyük göçleri otomatikleştirin. +- **Gelişmiş PDF/UA özellikleri** – özel etiketler ekleyin, dil öznitelikleri ayarlayın veya sesli açıklamalar gömün. +- **CI/CD Entegrasyonu** – her derlemenin otomatik olarak erişilebilir PDF'ler üretmesini sağlayın. + +Bir sorunla karşılaşırsanız, Aspose.Words sürümünüzün burada kullanılan API ile eşleştiğini bir kez daha kontrol edin ve kütüphanenin kendi belgelerinin sağlam bir ikincil referans olduğunu unutmayın. + +Kodlamanın tadını çıkarın, ve belgelerinizin hem güzel **hem** erişilebilir kalmasını dileriz! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/programming-with-txtsaveoptions/_index.md b/words/turkish/net/programming-with-txtsaveoptions/_index.md index 6a3fef3f94..899ce93f41 100644 --- a/words/turkish/net/programming-with-txtsaveoptions/_index.md +++ b/words/turkish/net/programming-with-txtsaveoptions/_index.md @@ -27,6 +27,7 @@ Bu eğitimler sayesinde, Aspose.Words for .NET'in işlevselliklerinden tam olara | [Word Belgesine Bidi İşaretleri Ekleme](./add-bidi-marks/) | Bu kılavuzla Aspose.Words for .NET kullanarak Word belgelerine çift yönlü (Bidi) işaretlerin nasıl ekleneceğini öğrenin. Çok dilli içerik için uygun metin yönünü sağlayın. | | [Liste Girintisi İçin Seviye Başına Sekme Karakteri Kullan](./use-tab-character-per-level-for-list-indentation/) | Aspose.Words for .NET kullanarak sekmeli girintili çok seviyeli listeler oluşturmayı öğrenin. Belgelerinizde hassas liste biçimlendirmesi için bu kılavuzu izleyin. | | [Liste Girintisi İçin Seviye Başına Boşluk Karakteri Kullan](./use-space-character-per-level-for-list-indentation/) | Aspose.Words for .NET'te boşluk karakteri girintili çok seviyeli listelerin nasıl oluşturulacağını öğrenin. Hassas belge biçimlendirmesi için adım adım kılavuz. | +| [DOCX'i TXT Olarak Kaydet – Word Denklemlerini LaTeX'e C# ile Dışa Aktarma](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Bu eğitimde, Aspose.Words for .NET kullanarak DOCX dosyasını TXT olarak kaydederken Word denklemlerini LaTeX formatına nasıl dışa aktaracağınızı öğrenin. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/turkish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/turkish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..ab877a0262 --- /dev/null +++ b/words/turkish/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Aspose.Words ile docx dosyasını txt olarak kaydedin – Word'ü hızlıca + txt'ye dönüştürün ve matematik denklemlerini LaTeX olarak dışa aktarmayı öğrenin. + Basit C# kodu, ekstra araç gerekmez. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: tr +og_description: docx'i C#'ta txt olarak kaydedin ve matematiği LaTeX'e nasıl dışa + aktaracağınızı görün. Denklemler bozulmadan Word'ü txt'ye dönüştürmek için bu adım + adım rehberi izleyin. +og_title: docx'i txt olarak kaydet – Word denklemlerini LaTeX'e aktar +tags: +- Aspose.Words +- C# +- Document Conversion +title: docx'i txt olarak kaydet – Word denklemlerini C# ile LaTeX'e aktar +url: /tr/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# docx'i txt olarak kaydet – Word denklemlerini LaTeX'e C# ile dışa aktar + +Ever needed to **save docx as txt** but worried that your equations would disappear or turn into unreadable gibberish? You're not the only one. Many developers hit that wall when they try to **convert word to txt** for downstream processing, especially when the source file contains Office Math objects. + +The good news? With a few lines of C# and the right options, you can not only **convert Word to txt** but also keep every equation as clean LaTeX markup. In this tutorial we’ll walk through the whole process, explain why each setting matters, and show you how to verify the result. + +We'll cover: + +* Installing the Aspose.Words for .NET library +* Loading a `.docx` that contains math equations +* Configuring `TxtSaveOptions` so that **how to export math** becomes a LaTeX‑friendly string +* Saving the file and checking the output + +By the end, you’ll have a reusable snippet that lets you **save docx as txt** while preserving every formula as LaTeX—perfect for scientific pipelines, static site generators, or any workflow that needs plain‑text math. + +--- + +## Önkoşullar + +Before we dive in, make sure you have: + +* .NET 6.0 or later (the code works with .NET Framework 4.6+ as well) +* Visual Studio 2022 (or any IDE you prefer) +* The **Aspose.Words for .NET** NuGet package – install it with + +```bash +dotnet add package Aspose.Words +``` + +No additional converters or external tools are required; Aspose.Words handles the heavy lifting internally. + +--- + +## Adım 1: Aspose.Words'ı Yükleyin ve Referans Verin + +First, add the library to your project. If you’re using the command line, run the command above. In Visual Studio you can also right‑click **Dependencies → Manage NuGet Packages** and search for *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Use the latest stable version (as of April 2026 it’s 24.10). Newer releases bring bug fixes for OfficeMath handling, so you’ll avoid surprising missing symbols. + +--- + +## Adım 2: Kaynak Belgeyi Yükleyin + +Now we pull the `.docx` that contains the equations you want to keep. The `Document` class abstracts the whole Word file, giving you access to text, images, and Office Math objects. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Why load it first? Aspose.Words parses the file into an object model, allowing us to inspect or modify content before we decide how to export it. This is where **how to export math** decisions start to matter. + +--- + +## Adım 3: LaTeX Dışa Aktarım İçin TxtSaveOptions'ı Yapılandırın + +The heart of the solution is the `TxtSaveOptions` class. By default, saving to TXT strips out Office Math entirely. Setting `OfficeMathExportMode` to `LaTeX` tells the library to translate each equation into its LaTeX representation. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX is the lingua franca of scientific publishing. By exporting math this way, you keep the semantics of the equation instead of a flat image or a garbled string. If you later feed the TXT into a Markdown processor that supports MathJax, the equations will render perfectly. + +--- + +## Adım 4: Belgeyi Düz Metin Olarak Kaydedin + +With the options configured, the final step is a one‑liner that writes the file to disk. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +That’s it—your `.docx` is now a `.txt` file where every equation appears as a LaTeX snippet, ready for downstream consumption. + +--- + +## Çıktıyı Doğrulama (txt'yi doğru şekilde kaydetme) + +Open `MathSample.txt` in any text editor. You should see something like: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +If you spot raw Word‑specific characters (e.g., `?` or missing symbols), double‑check that: + +* You’re using a recent Aspose.Words version (older builds had bugs with OfficeMath). +* The source document actually contains **OfficeMath** objects—not legacy Equation Editor objects. For the latter, you may need to convert them manually or use the `ConvertMathToOfficeMath` method before saving. + +--- + +## Yaygın Varyasyonlar ve Kenar Durumları + +| Durum | Ne yapılmalı | +|-----------|------------| +| **Legacy Equation Editor** nesneleri | Call `doc.ConvertMathToOfficeMath()` before step 3. | +| **LaTeX yerine düz Unicode matematik** gerekir | Set `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Büyük belgeler (100 + MB)** | Stream the save operation using `doc.Save(Stream, txtOptions)` to avoid high memory usage. | +| **Orijinal dosya adını korumak istiyorsunuz** | Use `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` when constructing the output path. | + +These tweaks answer the “**how to export math**” question for different pipelines, ensuring your solution is robust no matter the source. + +--- + +## Tam Çalışan Örnek (Tüm adımlar bir arada) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Run the program, open the generated `.txt`, and you’ll see the LaTeX equations embedded right where they belonged. This is the most straightforward way to **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/turkish/net/working-with-fonts/_index.md b/words/turkish/net/working-with-fonts/_index.md index 924616f109..e06d829914 100644 --- a/words/turkish/net/working-with-fonts/_index.md +++ b/words/turkish/net/working-with-fonts/_index.md @@ -25,6 +25,7 @@ Metni farklı yazı tipleriyle biçimlendirmek, yazı tipi değiştirme kurallar ## Eğitimler | Başlık | Açıklama | | --- | --- | +| [Aspose Yazı Tipi İkamesi – Word Belgelerinde Eksik Yazı Tiplerini Algıla](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Aspose.Words for .NET kullanarak Word belgelerindeki eksik yazı tiplerini nasıl tespit edeceğinizi öğrenin. | | [Yazı Tipi Biçimlendirme](./font-formatting/) | Aspose.Words for .NET kullanarak Word belgelerindeki yazı tiplerini nasıl biçimlendireceğinizi ayrıntılı, adım adım bir kılavuzla öğrenin. | | [Yazı Tipi Satır Aralığını Al](./get-font-line-spacing/) | Bu adım adım eğitimle Aspose.Words for .NET kullanarak yazı tipi satır aralığını nasıl elde edeceğinizi öğrenin. Geliştiriciler için mükemmel. | | [DrawingML Metin Efektini Kontrol Et](./check-drawingml-text-effect/) Ayrıntılı, adım adım kılavuzumuzla Aspose.Words for .NET kullanarak Word belgelerindeki DrawingML metin efektlerini nasıl kontrol edeceğinizi öğrenin. Belgelerinizi kolaylıkla geliştirin. | @@ -40,7 +41,7 @@ Metni farklı yazı tipleriyle biçimlendirmek, yazı tipi değiştirme kurallar | [Font Klasörlerini Öncelikli Olarak Ayarla](./set-fonts-folders-with-priority/) | Aspose.Words for .NET kullanarak Word belgelerinde font klasörlerini öncelikli olarak nasıl ayarlayacağınızı öğrenin. Kılavuzumuz belgelerinizin her seferinde mükemmel şekilde işlenmesini sağlar. | | [True Type Yazı Tipleri Klasörünü Ayarla](./set-true-type-fonts-folder/) | Aspose.Words for .NET kullanarak Word belgelerinde True Type Fonts klasörünün nasıl ayarlanacağını öğrenin. Tutarlı font yönetimini sağlamak için ayrıntılı, adım adım kılavuzumuzu izleyin. | | [İşleme Sırasında Varsayılan Yazı Tipini Belirle](./specify-default-font-when-rendering/) | Aspose.Words for .NET kullanarak Word belgelerini işlerken varsayılan yazı tipini nasıl belirleyeceğinizi öğrenin. Platformlar arasında tutarlı belge görünümünü sağlayın. | -| [Yükleme Seçenekleriyle Yazı Tipi Ayarları](./font-settings-with-load-options/) Aspose.Words for .NET'te yükleme seçenekleriyle yazı tipi ayarlarının nasıl yönetileceğini öğrenin. Geliştiricilerin Word belgelerinde tutarlı yazı tipi görünümünü sağlamaları için adım adım kılavuz. +| [Yükleme Seçenekleriyle Yazı Tipi Ayarları](./font-settings-with-load-options/) Aspose.Words for .NET'te yükleme seçenekleriyle yazı tipi ayarlarının nasıl yönetileceğini öğrenin. Geliştiricilerin Word belgelerinde tutarlı yazı tipi görünümünü sağlamaları için adım adım kılavuz. | | [Yazı Tipleri Klasörünü Ayarla](./set-fonts-folder/) | Word belgelerinizin eksik yazı tipleri olmadan doğru şekilde işlenmesini sağlamak için Aspose.Words for .NET'te özel yazı tipleri klasörünün nasıl ayarlanacağını öğrenin. | | [Yazı Tipi Ayarları Varsayılan Örnek](./font-settings-default-instance/) | Bu eğitimde, Aspose.Words for .NET ile bir Word belgesinde varsayılan yazı tipi ayarlarının nasıl yapılandırılacağını öğrenin. | | [Mevcut Yazı Tiplerinin Listesini Alın](./get-list-of-available-fonts/) | Bu detaylı adım adım eğitimde Aspose.Words for .NET kullanarak mevcut fontların listesini nasıl alacağınızı keşfedin. Font yönetimi becerilerinizi artırın. | diff --git a/words/turkish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/turkish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..d0d33f534c --- /dev/null +++ b/words/turkish/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-04-05 +description: Word belgesi yüklenirken eksik yazı tiplerini tespit etmek için Aspose + yazı tipi ikame rehberi. Yazı tipi ayarlarını yapılandırmayı ve eksik yazı tiplerini + verimli bir şekilde yönetmeyi öğrenin. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: tr +og_description: Aspose yazı tipi ikame rehberi, Word belgesi yüklenirken eksik yazı + tiplerini tespit etmenizi sağlar. Yazı tipi ayarlarını yapılandırmayı ve eksik yazı + tiplerini etkili bir şekilde yönetmeyi öğrenin. +og_title: Aspose Yazı Tipi Değiştirme – Word Belgelerindeki Eksik Yazı Tiplerini Tespit + Et +tags: +- Aspose.Words +- C# +- Font Management +title: Aspose Yazı Tipi Değiştirme – Word Belgelerindeki Eksik Yazı Tiplerini Tespit + Et +url: /tr/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Word Belgelerinde Eksik Yazı Tiplerini Algılamak + +Bir Word dosyasının bir bilgisayarda mükemmel göründüğünü, başka bir bilgisayarda ise garip yazı tipi değişiklikleri gösterdiğini hiç gördünüz mü? Bu, klasik **aspose font substitution** sorunudur ve genellikle hedef sistemde bazı yazı tiplerinin eksik olduğu anlamına gelir. Bu öğreticide, **Word belgesi yüklerken eksik yazı tiplerini nasıl algılayacağınızı**, **yazı tipi ayarlarını nasıl yapılandıracağınızı** ve **eksik yazı tiplerini nazikçe nasıl ele alacağınızı** adım adım göstereceğiz. + +Tamamen çalıştırılabilir bir C# örneği üzerinden ilerleyecek, her satırın neden önemli olduğunu açıklayacak ve beklemeniz gereken konsol çıktısını göstereceğiz. Sonuna kadar, bir belge yüklendiği anda yazı tipi ikamelerini anında görebileceksiniz—tahmin yürütmeye gerek kalmayacak. + +## Öğrenecekleriniz + +- Aspose.Words’ün yazı tipi uyarıları için tanılayıcı toplayıcısını nasıl etkinleştireceğinizi. +- Özel **yazı tipi ayarları**yla **Word belgesi** nasıl **yüklenir**. +- `WarningInfo` nesneleri üzerinde döngü kurarak her ikame edilen yazı tipini nasıl listeleyeceğinizi. +- İstenmeyen uyarıları nasıl bastıracağınız veya yedek yazı tipleri sağlayacağınız hakkında ipuçları. +- Visual Studio’ya kopyalayıp yapıştırabileceğiniz hazır bir örnek. + +### Önkoşullar + +- .NET 6.0 veya üzeri (API, .NET Framework’te aynı şekilde çalışır). +- Aspose.Words for .NET (NuGet paketi `Aspose.Words`). +- Yüklü olmayan bir yazı tipine referans veren bir Word dosyası (ör. `MissingFont.docx`). + +Eğer bunlara sahipseniz, başlayalım. + +## Adım 1 – Tanılayıcı Toplayıcıyı Etkinleştirin (Yazı Tipi Ayarlarını Yapılandırın) + +İlk iş: Aspose.Words yalnızca siz ona söyleseniz yazı tipi ikame uyarılarını kaydeder. Bunun için bir `FontSettings` nesnesi oluşturup bir `LoadOptions` örneğine atamanız gerekir. Bunu, yazı tipi işleme için “debug ışıklarını” açmak gibi düşünün. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Neden?** +`FontSettings` nesnesi olmadan uyarı toplayıcı sessiz kalır ve hangi yazı tiplerinin değiştirildiğini asla öğrenemezsiniz. Boş bir şekilde başlatmak, Aspose’un varsayılan sistem yazı tiplerini kullanmasına izin verir *ve* herhangi bir ikameyi izler. + +> **İpucu:** Belirli bir klasörün kurumsal yazı tiplerini içerdiğini biliyorsanız, `FontSettings`i `SetFontsFolder("path")` ile o klasöre yönlendirin. Bu, eksik‑yazı‑tipi uyarılarının sayısını azaltabilir. + +## Adım 2 – Belgeyi Yapılandırılmış Seçeneklerle Yükleyin (Word Belgesini Yükle) + +Toplayıcı aktif olduğuna göre, aynı `LoadOptions` ile `.docx` dosyanızı yükleyin. İşte bu an, Aspose’un belgeyi taradığı, her yazı tipi referansını kontrol ettiği ve ikame gerekip gerekmediğine karar verdiği zamandır. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Neden önemli?** +Sadece `new Document("MissingFont.docx")` çağırırsanız, varsayılan ayarlar uygulanır *ve* uyarı listesi boş kalır. `loadOptions` geçmek, tanılayıcı toplayıcının yükleme hattına bağlanmasını garantiler. + +## Adım 3 – Yazı Tipi İkame Uyarılarını Alın ve Görüntüleyin (Eksik Yazı Tiplerini Algılayın) + +Belge belleğe alındıktan sonra, Aspose uyarıları `document.WarningCallback.Warnings` içinde saklar. Bu koleksiyonu döngüye alıp `WarningType.FontSubstitution` için filtreleyin ve açıklamayı yazdırın. Her açıklama, hangi yazı tipinin eksik olduğunu ve yerine hangi yazı tipinin kullanıldığını söyler. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Beklenen konsol çıktısı** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Bu çıktı, kodu çalıştıran makinede tam olarak hangi yazı tiplerinin eksik olduğunu gösterir. Artık eksik yazı tiplerini yükleyebilir, belgeye gömebilir veya ikameyi olduğu gibi bırakabilirsiniz. + +![Konsol çıktısı, aspose font substitution uyarılarını gösteriyor](/images/aspose-font-substitution-console.png) + +*Görsel alt metni:* aspose font substitution – ikame edilen yazı tiplerini listeleyen konsol çıktısı + +## Adım 4 – İsteğe Bağlı: İkame Davranışını Özelleştirin (Eksik Yazı Tiplerini Ele Alın) + +Bazen sadece bir ikame gerçekleştiğini bilmek yetmez; *nasıl* gerçekleştiğini kontrol etmek istersiniz. Aspose.Words, özel bir `IFontSubstitutionRule` kaydetmenize izin verir. Aşağıda, eksik bir yazı tipinin `Tahoma`ya düşmesini zorlayan hızlı bir örnek bulabilirsiniz. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Ne zaman kullanılır?** +Web hizmeti için PDF oluşturuyorsanız ve her istemcinin `Tahoma`yı render edebileceğini biliyorsanız, bu yedekleme görsel tutarlılığı sağlar ve yüzlerce yazı tipi dosyası gönderme ihtiyacını ortadan kaldırır. + +## Tam Çalışan Örnek (Tüm Adımlar Birleştirildi) + +Yeni bir console projesine yapıştırabileceğiniz tam program aşağıdadır. Aspose.Words NuGet paketini kurduğunuz sürece olduğu gibi derlenir. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Programı çalıştırın, konsola bakın ve her eksik‑yazı‑tipi olayının yazdırıldığını göreceksiniz. Bundan sonra eksik yazı tiplerini yükleyebilir, belgeye gömebilir veya yedeklemeyi sürdürmeyi seçebilirsiniz. + +## Sık Sorulan Sorular + +**S: Bu PDF dönüşümüyle çalışır mı?** +Evet. Daha sonra `doc.Save("output.pdf")` çağırdığınızda, yükleme sırasında ikame edilen yazı tipleri PDF’e gömülür. Bu yüzden uyarıları erken yakalamak, final PDF’inde sürpriz yazı tipi değişikliklerini önlemeye yardımcı olur. + +**S: İşlem yapmam gereken çok sayıda belge varsa ne yapmalıyım?** +Yükleme mantığını bir try‑catch bloğuna sarın ve bir `FontSettings` örneğini belgeler arasında yeniden kullanın. Bu, yükleme süresini azaltır ve her dosya için uyarı toplayıcısını aktif tutar. + +**S: Uyarıları tamamen bastırabilir miyim?** +`loadOptions.WarningCallback = null;` satırını yüklemeden önce ayarlayabilirsiniz, ancak **eksik yazı tiplerini algılamayı** kaybedersiniz—ki bu genellikle istenmeyen bir durumdur. + +## Sonuç + +**aspose font substitution** konusunda ihtiyacınız olan her şeyi kapsadık: tanılayıcı toplayıcıyı etkinleştirme, özel **yazı tipi ayarları**yla bir Word dosyasını yükleme, eksik yazı tiplerinin listesini çıkarma ve varsayılan ikame kuralını **eksik yazı tiplerini** kendi yolunuzla ele alacak şekilde geçersiz kılma. Sadece birkaç C# satırıyla, aksi takdirde ince düzen değişikliklerinin arkasında gizlenen yazı tipi sorunlarına tam görünürlük kazandırırsınız. + +Sonraki adımlar? Orijinal yazı tiplerini belgeye `FontSettings.SetFontsFolder` ile gömmeyi deneyin ya da `FontSourceBase`i kullanarak yazı tiplerini bir veritabanından yükleyin. Ayrıca `Document.BuiltInStyle` koleksiyonunu inceleyerek stil‑seviyesi yazı tipi değişikliklerinin nasıl yayıldığını görebilirsiniz. + +Aspose.Words veya yazı tipi yönetimi hakkında daha fazla sorunuz mu var? Yorum bırakın, resmi Aspose belgelerini keşfedin veya yeni bir proje başlatıp yukarıdaki kodla oynayın. İyi kodlamalar, ve belgeleriniz her zaman istediğiniz gibi render olsun! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/basic-conversions/_index.md b/words/vietnamese/net/basic-conversions/_index.md index f5a19d54fb..60b67aca2b 100644 --- a/words/vietnamese/net/basic-conversions/_index.md +++ b/words/vietnamese/net/basic-conversions/_index.md @@ -25,6 +25,7 @@ Basic Conversions hướng dẫn bạn cách chuyển đổi tài liệu cơ b | [Chuyển đổi Docx sang Rtf](./docx-to-rtf/) | Tìm hiểu cách chuyển đổi DOCX sang RTF bằng Aspose.Words cho .NET với hướng dẫn từng bước của chúng tôi. Chuyển đổi dễ dàng để xử lý tài liệu liền mạch. | | [Chuyển đổi tệp Word sang PDF](./docx-to-pdf/) Tìm hiểu cách dễ dàng chuyển đổi tệp Word sang PDF bằng Aspose.Words cho .NET với hướng dẫn của chúng tôi. Hoàn hảo cho các nhà phát triển đang tìm kiếm chuyển đổi tài liệu nhanh chóng và đáng tin cậy. | | [Chuyển đổi Word sang PDF trong C# bằng Aspose.Words – Hướng dẫn](./convert-word-to-pdf-in-c-using-aspose-words-guide/) | Hướng dẫn chi tiết cách chuyển đổi tài liệu Word sang PDF trong C# sử dụng Aspose.Words, kèm ví dụ mã nguồn. | +| [Chuyển đổi Word sang PDF trong C# – Hướng dẫn đầy đủ với Aspose.Words](./convert-word-to-pdf-in-c-full-guide-with-aspose-words/) | Hướng dẫn chi tiết cách chuyển đổi tài liệu Word sang PDF trong C# bằng Aspose.Words, kèm ví dụ mã nguồn đầy đủ. | | [Lưu Word thành PDF với Aspose.Words – Hướng dẫn C# đầy đủ](./save-word-as-pdf-with-aspose-words-complete-c-guide/) | Hướng dẫn chi tiết cách lưu tài liệu Word thành PDF bằng Aspose.Words trong C#, kèm ví dụ mã nguồn. | | [Chuyển đổi Docx sang Byte](./docx-to-byte/) | Tìm hiểu cách chuyển đổi Docx sang mảng byte trong .NET bằng Aspose.Words để xử lý tài liệu hiệu quả. Có kèm hướng dẫn từng bước. | | [Chuyển đổi Docx sang Epub](./docx-to-epub/) | Chuyển đổi DOCX sang EPUB dễ dàng với Aspose.Words cho .NET. Làm theo hướng dẫn của chúng tôi để tích hợp liền mạch vào các ứng dụng .NET của bạn. | diff --git a/words/vietnamese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md b/words/vietnamese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md new file mode 100644 index 0000000000..669570ccc2 --- /dev/null +++ b/words/vietnamese/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-04-05 +description: Chuyển đổi Word sang PDF trong C# bằng Aspose.Words. Tìm hiểu cách lưu + tệp docx thành PDF, xuất PDF có khả năng truy cập và tải tài liệu Word một cách + hiệu quả. +draft: false +keywords: +- convert word to pdf +- save docx as pdf +- how to export accessible pdf +- load word document +- c# convert docx pdf +language: vi +og_description: Chuyển đổi Word sang PDF trong C# với hướng dẫn từng bước. Khám phá + cách lưu docx thành PDF, xuất PDF có thể truy cập và tải tài liệu Word bằng Aspose.Words. +og_title: Chuyển đổi Word sang PDF trong C# – Hướng dẫn đầy đủ Aspose.Words +tags: +- Aspose.Words +- PDF/UA +- C# +- Document Conversion +title: Chuyển đổi Word sang PDF trong C# – Hướng dẫn đầy đủ với Aspose.Words +url: /vi/net/basic-conversions/convert-word-to-pdf-in-c-full-guide-with-aspose-words/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi Word sang PDF trong C# – Hướng dẫn lập trình đầy đủ + +Bạn đã bao giờ tự hỏi cách **convert word to pdf** mà không phải vật lộn với các công cụ dòng lệnh rắc rối hay dịch vụ bên thứ ba chưa? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp phải rào cản này khi khách hàng yêu cầu một PDF có khả năng truy cập ngay từ file DOCX. Tin tốt là gì? Chỉ với vài dòng C# và thư viện mạnh mẽ Aspose.Words, bạn có thể biến tài liệu Word thành PDF tuân thủ tiêu chuẩn trong chớp mắt. + +Trong hướng dẫn này, chúng ta sẽ đi qua mọi thứ bạn cần biết: từ các kiến thức cơ bản **load word document**, đến cấu hình các tùy chọn đúng để **how to export accessible pdf**, và cuối cùng lưu kết quả để bạn có thể **save docx as pdf** một cách đáng tin cậy. Khi kết thúc, bạn sẽ có một đoạn mã sẵn sàng chạy mà bạn có thể chèn vào bất kỳ dự án .NET nào. + +> **Mẹo chuyên nghiệp:** Nếu bạn đang nhắm tới tuân thủ PDF/UA‑2 (tiêu chuẩn khả năng truy cập mà nhiều cơ quan chính phủ yêu cầu), cùng một đoạn mã sẽ hoạt động mà không cần bước bổ sung—chỉ cần đặt cờ `PdfCompliance` đúng. + +--- + +## Những gì bạn sẽ học + +- Cách **load word document** bằng Aspose.Words trong C#. +- Các thiết lập chính xác cần thiết để **how to export accessible pdf** (PDF/UA‑2). +- Một ví dụ hoàn chỉnh, có thể chạy được, **save docx as pdf** chỉ bằng một lời gọi phương thức. +- Những lỗi thường gặp khi **c# convert docx pdf** và cách tránh chúng. +- Các cách nhanh để xác minh PDF đã tạo đáp ứng các yêu cầu khả năng truy cập. + +Không cần công cụ bên ngoài, không cần file cấu hình khó hiểu—chỉ có C# thuần túy mà bạn có thể biên dịch ngay hôm nay. + +--- + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn bạn đã có: + +1. **.NET 6.0** (hoặc bất kỳ phiên bản .NET mới nào). Các framework cũ cũng hoạt động, nhưng cú pháp dưới đây giả định SDK hiện đại. +2. Một **license** cho Aspose.Words for .NET. Thư viện cung cấp bản dùng thử miễn phí, nhưng để sản xuất bạn sẽ cần key hợp lệ. +3. Gói **Aspose.Words** NuGet đã được thêm vào dự án của bạn: + +```bash +dotnet add package Aspose.Words +``` + +Thế là xong—không cần binary bổ sung, không cần COM interop, chỉ một tham chiếu NuGet sạch sẽ. + +--- + +![chuyển đổi word sang pdf bằng Aspose.Words trong C#](image-placeholder.png "chuyển đổi word sang pdf bằng Aspose.Words trong C#") + +--- + +## Thực hiện từng bước + +Dưới đây chúng tôi chia quy trình thành các khối logic. Mỗi bước bao gồm một đoạn mã ngắn, giải thích **tại sao** nó quan trọng, và một mẹo dựa trên kinh nghiệm thực tế. + +### ## Convert Word to PDF – Load the Source Document + +Việc đầu tiên bạn cần làm là **load word document** vào bộ nhớ. Aspose.Words trừu tượng hoá việc phân tích OpenXML, vì vậy bạn có thể làm việc với file DOCX, DOC, hoặc thậm chí RTF mà không lo lắng về các quirks của định dạng. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +// Path to your input file – change this to wherever your DOCX lives. +string inputPath = @"C:\Docs\input.docx"; + +// Load the Word document. +Document sourceDoc = new Document(inputPath); +``` + +**Tại sao điều này quan trọng:** +Việc tải file tạo ra một đối tượng `Document` đại diện cho toàn bộ file Word, bao gồm header, footer, style và metadata ẩn. Nếu bỏ qua bước này hoặc cố đọc file dưới dạng stream thô, bạn sẽ mất thông tin bố cục mà sau này quyết định cách PDF hiển thị. + +> **Lưu ý phụ:** Constructor `Document` giống nhau cũng hoạt động với `.doc` và `.rtf`. Điều này có nghĩa là bạn có thể **c# convert docx pdf** ngay cả khi nguồn không phải là DOCX thuần. + +### ## Save DOCX as PDF – Configure PDF/UA‑2 Compliance + +Bây giờ tài liệu đã ở trong bộ nhớ, chúng ta chỉ định cho Aspose.Words cách tạo PDF. Đối với hầu hết các trường hợp, các thiết lập mặc định là đủ, nhưng khi bạn cần một **accessible PDF** thì phải bật cờ tuân thủ PDF/UA‑2. + +```csharp +// Set up PDF save options. +PdfSaveOptions pdfSaveOptions = new PdfSaveOptions +{ + // Enforce PDF/UA‑2 (accessible PDF) compliance. + Compliance = PdfCompliance.PdfUAXmpA2, + + // Optional: embed all fonts to avoid missing glyphs on other machines. + EmbedFullFonts = true, + + // Optional: preserve the original document's layout exactly. + PreserveFormFields = true +}; +``` + +**Tại sao điều này quan trọng:** +`PdfCompliance.PdfUAXmpA2` báo cho thư viện nhúng các thẻ và cấu trúc cần thiết mà các trình đọc màn hình dựa vào. Nếu không có cờ này, bạn có thể nhận được một PDF trông đẹp mắt nhưng sẽ thất bại trong kiểm tra khả năng truy cập. + +> **Mẹo:** Nếu bạn chỉ cần một PDF thông thường, có thể bỏ qua dòng `Compliance`. Các tùy chọn còn lại vẫn cho ra đầu ra chất lượng cao. + +### ## Convert Word to PDF – Write the File + +Với các tùy chọn đã sẵn sàng, bước cuối cùng là **save docx as pdf**. Lời gọi duy nhất này thực hiện toàn bộ công việc nặng: chuyển đổi bố cục, nhúng phông chữ, và gắn thẻ khả năng truy cập. + +```csharp +// Destination path for the PDF. +string outputPath = @"C:\Docs\output.pdf"; + +// Save the document as PDF using the configured options. +sourceDoc.Save(outputPath, pdfSaveOptions); +``` + +**Bạn sẽ nhận được:** +- Một file PDF tại `outputPath` phản ánh chính xác bố cục Word. +- Nếu bạn đã dùng cờ `PdfUAXmpA2`, PDF sẽ được đánh dấu là tuân thủ PDF/UA‑2. +- Tất cả phông chữ được nhúng, vì vậy file sẽ trông giống hệt trên bất kỳ máy nào. + +### ## Verify the Accessible PDF (Optional but Recommended) + +Sau khi chuyển đổi, nên kiểm tra lại PDF thực sự **how to export accessible pdf** đúng chưa. Bạn có thể dùng các công cụ miễn phí như “Accessibility Check” của Adobe Acrobat Reader hoặc trình kiểm tra `pdfcpu` mã nguồn mở. + +```bash +pdfcpu validate -mode=pdfua2 "C:\Docs\output.pdf" +``` + +Nếu trình kiểm tra không báo lỗi, bạn đã **convert word to pdf** thành công với hỗ trợ khả năng truy cập đầy đủ. + +### ## Common Pitfalls When You C# Convert DOCX to PDF + +| Vấn đề | Tại sao xảy ra | Cách khắc phục | +|-------|----------------|----------------| +| Thiếu phông chữ | File DOCX nguồn sử dụng phông chữ tùy chỉnh chưa được cài trên server. | Đặt `EmbedFullFonts = true` hoặc cài phông chữ trên máy. | +| Kích thước file lớn | Hình ảnh được nhúng ở độ phân giải đầy đủ. | Sử dụng `ImageCompression = PdfImageCompression.Jpeg` và giảm `JpegQuality`. | +| Liên kết hỏng | Đường dẫn liên kết là tương đối và không tồn tại trên client. | Đảm bảo URL là tuyệt đối hoặc điều chỉnh thuộc tính `HyperlinkTarget`. | +| Thiếu thẻ khả năng truy cập | Cờ `Compliance` chưa được đặt. | Thêm `Compliance = PdfCompliance.PdfUAXmpA2` như trên. | + +Nhớ những điểm này sẽ giúp quy trình **c# convert docx pdf** của bạn trở nên vững chắc và sẵn sàng cho môi trường production. + +--- + +## Ví dụ đầy đủ hoạt động + +Kết hợp tất cả lại, dưới đây là một ứng dụng console tự chứa mà bạn có thể biên dịch và chạy ngay. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Load the Word document you want to convert. + string inputPath = @"C:\Docs\input.docx"; + Document sourceDoc = new Document(inputPath); + + // 2️⃣ Set up PDF save options to enforce PDF/UA‑2 compliance. + PdfSaveOptions pdfSaveOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, // makes the PDF accessible + EmbedFullFonts = true, // avoids missing glyphs + PreserveFormFields = true + }; + + // 3️⃣ Save the document as a PDF using the configured options. + string outputPath = @"C:\Docs\output.pdf"; + sourceDoc.Save(outputPath, pdfSaveOptions); + + Console.WriteLine($"✅ Successfully converted Word to PDF!\nSaved at: {outputPath}"); + // Optional: run an external validator here if you want to double‑check accessibility. + } +} +``` + +**Kết quả mong đợi:** Sau khi chạy chương trình, bạn sẽ thấy `output.pdf` trong `C:\Docs`. Mở nó bằng bất kỳ trình xem PDF nào; bố cục sẽ khớp pixel‑for‑pixel với `input.docx`, và kiểm tra khả năng truy cập sẽ xác nhận tuân thủ PDF/UA‑2. + +--- + +## Kết luận + +Chúng ta vừa đi qua một giải pháp toàn diện, đầu‑cuối‑đầu‑cuối cho cách **convert word to pdf** bằng C# và Aspose.Words. Bằng cách **load word document**, cấu hình đúng `PdfSaveOptions`, và cuối cùng **save docx as pdf**, bạn sẽ có một PDF chất lượng cao, có khả năng truy cập, với ít mã nhất. Dù bạn đang xây dựng một microservice tạo tài liệu, một công cụ chuyển đổi batch tại chỗ, + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md b/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md index ec576d7f37..d815530672 100644 --- a/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md +++ b/words/vietnamese/net/programming-with-markdownsaveoptions/_index.md @@ -32,6 +32,8 @@ Words Processing with MarkdownSaveOptions là một nguồn tài nguyên chuyên | [Lưu docx thành markdown – Hướng dẫn đầy đủ C# với trích xuất hình ảnh](./save-docx-as-markdown-full-c-guide-with-image-extraction/) | Hướng dẫn chi tiết cách lưu file docx thành markdown và trích xuất hình ảnh bằng C# và Aspose.Words. | | [Xuất Markdown từ Word – Hướng dẫn đầy đủ C#](./how-to-export-markdown-from-word-complete-c-guide/) | Hướng dẫn chi tiết cách xuất tài liệu Word sang định dạng Markdown bằng C# và Aspose.Words, bao gồm các tùy chọn và ví dụ thực tế. | | [Xuất Markdown từ DOCX – Hướng dẫn đầy đủ](./how-to-export-markdown-from-docx-complete-guide/) | Hướng dẫn chi tiết cách xuất file DOCX sang Markdown bằng C# và Aspose.Words, bao gồm các tùy chọn và ví dụ thực tế. | +| [Chuyển DOCX sang Markdown – Trích xuất hình ảnh từ DOCX bằng Aspose.Words](./convert-docx-to-markdown-extract-images-from-docx-with-aspos/) | Hướng dẫn chuyển DOCX sang Markdown và trích xuất hình ảnh từ tài liệu bằng Aspose.Words cho .NET. | +| [Chuyển Word sang Markdown – Hướng dẫn đầy đủ với xuất PDF/UA](./convert-word-to-markdown-full-guide-with-pdf-ua-export/) | Hướng dẫn chi tiết cách chuyển tài liệu Word sang Markdown và xuất PDF/UA bằng C# và Aspose.Words. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md b/words/vietnamese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md new file mode 100644 index 0000000000..1fc555fd0b --- /dev/null +++ b/words/vietnamese/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/_index.md @@ -0,0 +1,316 @@ +--- +category: general +date: 2026-04-05 +description: Học cách chuyển đổi DOCX sang Markdown và trích xuất hình ảnh từ DOCX + trong C#. Hướng dẫn từng bước với mã nguồn đầy đủ và các mẹo. +draft: false +keywords: +- convert docx to markdown +- extract images from docx +- Aspose.Words markdown conversion +- C# document processing +- image extraction C# +language: vi +og_description: Chuyển đổi DOCX sang Markdown và trích xuất hình ảnh từ DOCX bằng + Aspose.Words. Hướng dẫn C# đầy đủ với mã nguồn, giải thích và các mẹo thực hành + tốt nhất. +og_title: Chuyển DOCX sang Markdown – Trích xuất hình ảnh từ DOCX bằng C# +tags: +- Aspose.Words +- C# +- Markdown +- DOCX +- Image extraction +title: Chuyển DOCX sang Markdown – Trích xuất hình ảnh từ DOCX bằng Aspose.Words +url: /vi/net/programming-with-markdownsaveoptions/convert-docx-to-markdown-extract-images-from-docx-with-aspos/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển DOCX sang Markdown – Trích xuất hình ảnh từ DOCX trong C# + +Bạn đã bao giờ cần **chuyển DOCX sang Markdown** nhưng gặp khó khăn vì các hình ảnh biến mất trong kết quả chưa? Bạn không phải là người duy nhất. Trong nhiều dự án, phiên bản markdown là hoàn hảo cho việc kiểm soát phiên bản hoặc các trình tạo trang tĩnh, nhưng các hình ảnh lại bị bỏ lại, biến một tài liệu phong phú thành một tệp văn bản trống rỗng. + +Tin tốt? Chỉ với vài dòng C# và Aspose.Words, bạn có thể **chuyển DOCX sang Markdown** *và* **tự động trích xuất hình ảnh từ DOCX**. Hướng dẫn này sẽ đưa bạn qua toàn bộ quá trình, giải thích lý do mỗi phần quan trọng, và thậm chí chỉ cho bạn cách giữ thư mục hình ảnh gọn gàng. + +## Những gì bạn sẽ học + +- Cách tải một tệp DOCX có chứa hình ảnh. +- Cách định nghĩa một `IResourceSavingCallback` tùy chỉnh để quyết định nơi lưu mỗi hình ảnh. +- Cách cấu hình `MarkdownSaveOptions` để markdown được tạo tham chiếu đúng các hình ảnh đã trích xuất. +- Mẹo xử lý các trường hợp đặc biệt như tên hình ảnh trùng lặp hoặc định dạng không phải PNG. +- Một mẫu mã hoàn chỉnh, sẵn sàng sao chép‑dán mà bạn có thể chạy ngay hôm nay. + +### Yêu cầu trước + +- .NET 6.0 trở lên (API hoạt động trên .NET Core, .NET Framework và .NET 5+). +- Giấy phép cho **Aspose.Words for .NET** (bản dùng thử miễn phí đủ cho việc thử nghiệm). +- Kiến thức cơ bản về C# và Visual Studio (hoặc IDE yêu thích của bạn). + +Nếu bạn đã có những thứ trên, hãy bắt đầu. + +--- + +## Bước 1: Thiết lập dự án và cài đặt Aspose.Words + +Đầu tiên, tạo một ứng dụng console mới (hoặc tích hợp vào một solution hiện có). + +```bash +dotnet new console -n DocxToMarkdownDemo +cd DocxToMarkdownDemo +dotnet add package Aspose.Words +``` + +> **Mẹo chuyên nghiệp:** Sử dụng phiên bản NuGet mới nhất (tính đến tháng 4 2026 là 24.12) để có các cải tiến mới nhất cho việc xuất markdown. + +--- + +## Bước 2: Tạo Callback để lưu hình ảnh ở vị trí bạn muốn + +Aspose.Words cho phép bạn chặn mọi tài nguyên (hình ảnh, SVG, v.v.) được ghi trong quá trình xuất markdown. Bằng cách triển khai `IResourceSavingCallback` bạn có thể: + +1. Chọn một thư mục nằm cạnh tệp markdown của bạn. +2. Tạo một tên tệp duy nhất (để bạn không bao giờ ghi đè lên hình ảnh đã tồn tại). +3. Quyết định định dạng (ở đây chúng tôi ép PNG để đồng nhất). + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +/// +/// Saves each image extracted from the DOCX into a dedicated folder +/// with a GUID‑based filename. The markdown file will reference the +/// new filename via args.ResourceFileName. +/// +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + + public ImageResourceSaver(string targetFolder) + { + _targetFolder = targetFolder; + // Ensure the folder exists before we start writing files. + Directory.CreateDirectory(_targetFolder); + } + + public void ResourceSaving(ResourceSavingArgs args) + { + // Generate a unique name to avoid collisions. + string newFileName = $"img_{Guid.NewGuid():N}.png"; + + // Full physical path where the image will be written. + string fullPath = Path.Combine(_targetFolder, newFileName); + + // Tell the markdown exporter what name to use in the .md file. + args.ResourceFileName = newFileName; + + // Provide a stream that writes to the desired location. + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} +``` + +### Tại sao lại dùng tên dựa trên GUID? + +Nếu DOCX nguồn chứa hai hình ảnh có cùng tên gốc, việc sao chép‑dán đơn giản sẽ ghi đè lên một trong số chúng. Sử dụng `Guid.NewGuid()` đảm bảo tính duy nhất, điều này đặc biệt hữu ích khi bạn chạy chuyển đổi nhiều lần trong một pipeline tự động. + +--- + +## Bước 3: Tải DOCX và cấu hình các tùy chọn Markdown + +Bây giờ chúng ta đưa tài liệu vào bộ nhớ và gắn callback mà chúng ta vừa tạo. + +```csharp +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // -------------------------------------------------------------------- + // 1️⃣ Define paths – adjust these to match your environment. + // -------------------------------------------------------------------- + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMarkdown = @"C:\Docs\DocWithImages.md"; + string imagesFolder = @"C:\Docs\MarkdownResources"; + + // -------------------------------------------------------------------- + // 2️⃣ Load the Word document. + // -------------------------------------------------------------------- + Document doc = new Document(sourceDocx); + + // -------------------------------------------------------------------- + // 3️⃣ Configure MarkdownSaveOptions with our custom saver. + // -------------------------------------------------------------------- + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + // This tells Aspose.Words to call ImageResourceSaver for each image. + ResourceSavingCallback = new ImageResourceSaver(imagesFolder) + }; + + // -------------------------------------------------------------------- + // 4️⃣ Perform the conversion. + // -------------------------------------------------------------------- + doc.Save(outputMarkdown, mdOptions); + + Console.WriteLine("✅ Conversion complete!"); + Console.WriteLine($"Markdown saved to: {outputMarkdown}"); + Console.WriteLine($"Images saved to: {imagesFolder}"); + } +} +``` + +### Những gì mã thực hiện, từng bước + +| Bước | Mục đích | +|------|----------| +| **Xác định đường dẫn** | Giữ cho dự án của bạn linh hoạt; bạn có thể chỉ tới bất kỳ thư mục nào mà không cần biên dịch lại. | +| **Tải DOCX** | `Document` phân tích tệp Word, cho phép truy cập tất cả các thành phần (đoạn văn, bảng, hình ảnh). | +| **Cấu hình `MarkdownSaveOptions`** | `ResourceSavingCallback` là hook để trích xuất hình ảnh. Nếu không có nó, Aspose.Words sẽ nhúng hình ảnh dưới dạng chuỗi base64 hoặc bỏ chúng hoàn toàn, tùy thuộc vào cài đặt. | +| **Lưu** | `doc.Save` ghi tệp markdown và kích hoạt callback cho mỗi hình ảnh. | + +--- + +## Bước 4: Xác minh đầu ra – Bạn sẽ thấy gì? + +Sau khi chạy chương trình, mở `DocWithImages.md`. Bạn sẽ thấy các liên kết hình ảnh markdown trông như sau: + +```markdown +![img_1a2b3c4d5e6f7g8h9i0j.png](MarkdownResources/img_1a2b3c4d5e6f7g8h9i0j.png) +``` + +Và trong `C:\Docs\MarkdownResources` bạn sẽ tìm thấy một loạt các tệp PNG có tên GUID. Mở bất kỳ tệp nào – chúng sẽ giống hệt các hình ảnh đã được nhúng trong DOCX gốc. + +Nếu bạn mở tệp markdown trong một trình xem hỗ trợ đường dẫn tương đối (ví dụ: xem trước VS Code, GitHub, hoặc một trình tạo trang tĩnh), các hình ảnh sẽ hiển thị giống như trong Word. + +### Những lỗi thường gặp & Cách tránh + +| Triệu chứng | Nguyên nhân có thể | Cách khắc phục | +|------------|--------------------|----------------| +| Hình ảnh xuất hiện dưới dạng liên kết hỏng | `ResourceFileName` chưa được đặt, vì vậy markdown trỏ tới tệp không tồn tại. | Đảm bảo `args.ResourceFileName = newFileName;` trong callback. | +| Các tệp PNG quá lớn | Hình ảnh gốc là JPEG hoặc BMP; chuyển sang PNG có thể làm tăng kích thước. | Phát hiện định dạng gốc qua `args.ResourceContentType` và giữ nguyên: `args.ResourceFileName = $"{Guid.NewGuid()}{Path.GetExtension(args.ResourceFileName)}";` | +| Các hình ảnh trùng lặp vẫn xuất hiện | Bạn đã sử dụng tên tệp tĩnh thay vì GUID. | Quay lại logic GUID hoặc thêm bộ đếm cho mỗi loại hình ảnh. | +| Quá trình chuyển đổi ném `FileNotFoundException` | Đường dẫn DOCX nguồn sai hoặc thư mục không có quyền đọc. | Kiểm tra lại đường dẫn và cấp quyền hệ thống tập tin phù hợp. | + +--- + +## Bước 5: Tinh chỉnh nâng cao (Tùy chọn) + +### 5.1 Giữ nguyên định dạng hình ảnh gốc + +Nếu bạn muốn các hình ảnh đầu ra giữ nguyên phần mở rộng gốc, hãy sửa đổi callback: + +```csharp +public void ResourceSaving(ResourceSavingArgs args) +{ + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + // Default to .png if Aspose couldn't determine an extension. + if (string.IsNullOrEmpty(ext)) ext = ".png"; + + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); +} +``` + +### 5.2 Nhúng hình ảnh dưới dạng Base64 (Khi bạn *không* muốn tách riêng các tệp) + +Đôi khi một markdown duy nhất là ưu tiên (ví dụ: để gửi qua email). Thay đổi tùy chọn: + +```csharp +mdOptions.ImagesFolder = string.Empty; // disables external folder +mdOptions.ExportImagesAsBase64 = true; +``` + +Nhưng hãy nhớ: **trích xuất hình ảnh từ DOCX** là mục tiêu chính cho hầu hết các quy trình làm việc với trang tĩnh, vì vậy cách sử dụng thư mục thường là lựa chọn tốt hơn. + +--- + +## Ví dụ Hoạt động đầy đủ (Sẵn sàng sao chép‑dán) + +Dưới đây là toàn bộ chương trình trong một tệp. Chỉ cần thay đổi các đường dẫn thành của bạn và chạy. + +```csharp +// --------------------------------------------------------------- +// Convert DOCX to Markdown – Extract Images from DOCX +// --------------------------------------------------------------- +// NuGet: Aspose.Words (>= 24.12) +// --------------------------------------------------------------- +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class ImageResourceSaver : IResourceSavingCallback +{ + private readonly string _targetFolder; + public ImageResourceSaver(string targetFolder) => Directory.CreateDirectory(_targetFolder = targetFolder); + + public void ResourceSaving(ResourceSavingArgs args) + { + string ext = Path.GetExtension(args.ResourceFileName).ToLowerInvariant(); + if (string.IsNullOrEmpty(ext)) ext = ".png"; + string newFileName = $"img_{Guid.NewGuid():N}{ext}"; + string fullPath = Path.Combine(_targetFolder, newFileName); + args.ResourceFileName = newFileName; + args.Stream = new FileStream(fullPath, FileMode.Create); + } +} + +class Program +{ + static void Main() + { + // 👉 Adjust these paths: + string sourceDocx = @"C:\Docs\WithImages.docx"; + string outputMd = @"C:\Docs\DocWithImages.md"; + string imgFolder = @"C:\Docs\MarkdownResources"; + + // Load the DOCX. + Document doc = new Document(sourceDocx); + + // Set up markdown options with our image saver. + MarkdownSaveOptions mdOptions = new MarkdownSaveOptions + { + ResourceSavingCallback = new ImageResourceSaver(imgFolder) + }; + + // Perform conversion. + doc.Save(outputMd, mdOptions); + + Console.WriteLine("✅ DOCX successfully converted to Markdown."); + Console.WriteLine($"📄 Markdown: {outputMd}"); + Console.WriteLine($"🖼️ Images folder: {imgFolder}"); + } +} +``` + +Chạy nó bằng `dotnet run`. Khi console in ra dòng ✅, mở tệp markdown và bạn sẽ thấy các hình ảnh được hiển thị đúng. + +--- + +## Kết luận + +Bây giờ bạn đã có một **giải pháp hoàn chỉnh, sẵn sàng cho môi trường sản xuất để chuyển DOCX sang Markdown và trích xuất hình ảnh từ DOCX** bằng Aspose.Words trong C#. Từ khóa chính xuất hiện xuyên suốt hướng dẫn, tăng cường tính liên quan cho cả công cụ tìm kiếm và trợ lý AI. + +Trong một lần chạy duy nhất, mã thực hiện: + +1. Tải tài liệu Word. +2. Chặn mỗi hình ảnh qua `IResourceSavingCallback`. +3. Lưu mỗi hình ảnh vào một thư mục dự đoán được với tên duy nhất. +4. Tạo markdown tham chiếu tới các hình ảnh đó. + +Từ đây bạn có thể: + +- Plug + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md b/words/vietnamese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md new file mode 100644 index 0000000000..2422488dc6 --- /dev/null +++ b/words/vietnamese/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-04-05 +description: Chuyển đổi Word sang Markdown nhanh chóng và học cách lưu dưới dạng PDF/UA + trong C#. Mã từng bước, mẹo và xử lý các trường hợp đặc biệt. +draft: false +keywords: +- convert word to markdown +- save as pdf/ua +- Aspose.Words conversion +- Markdown export C# +- PDF/UA compliance +language: vi +og_description: Chuyển đổi Word sang Markdown và lưu dưới dạng PDF/UA với Aspose.Words. + Tìm hiểu lý do, cách thực hiện và các mẹo thực hành tốt nhất trong một hướng dẫn + ngắn gọn. +og_title: Chuyển đổi Word sang Markdown – Hướng dẫn C# hoàn chỉnh +tags: +- Aspose.Words +- C# +- Document Conversion +title: Chuyển đổi Word sang Markdown – Hướng dẫn đầy đủ với xuất PDF/UA +url: /vi/net/programming-with-markdownsaveoptions/convert-word-to-markdown-full-guide-with-pdf-ua-export/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi Word sang Markdown – Hướng dẫn đầy đủ với xuất PDF/UA + +Bạn đã bao giờ tự hỏi làm thế nào **chuyển đổi Word sang Markdown** mà không mất công thức hay hình ảnh chưa? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần một cách đáng tin cậy để biến các tệp `.docx` thành Markdown sạch sẽ đồng thời vẫn có thể **lưu dưới dạng PDF/UA** cho các tệp PDF tuân thủ tiêu chuẩn truy cập. Trong hướng dẫn này, chúng ta sẽ đi qua một giải pháp hoàn chỉnh, sẵn sàng chạy sử dụng Aspose.Words cho .NET, giải thích lý do mỗi thiết lập quan trọng, và chỉ cho bạn cách xử lý các phần khó hơn như OfficeMath và các hình dạng nổi. + +Khi đọc xong hướng dẫn này, bạn sẽ có một chương trình C# duy nhất có thể: + +1. Tải tài liệu Word với chế độ khôi phục nhẹ (để các tệp hỏng không làm ngừng chạy). +2. Xuất nó ra Markdown, chuyển công thức thành LaTeX và lưu hình ảnh qua một callback tùy chỉnh. +3. Lưu cùng tài liệu dưới dạng tệp PDF/UA‑2 tuân thủ, nhúng các hình dạng nổi dưới dạng thẻ inline. + +Nghe có vẻ nhiều? Không sao—cùng bắt đầu. + +## Những gì bạn cần + +- **Aspose.Words cho .NET** (phiên bản mới nhất, 23.x tại thời điểm viết). +- Môi trường phát triển .NET (Visual Studio 2022, Rider, hoặc CLI `dotnet`). +- Một tệp Word mẫu (`input.docx`) đặt trong thư mục bạn có thể tham chiếu. +- Kiến thức cơ bản về cú pháp C#—không cần gì phức tạp, chỉ vài câu lệnh `using`. + +> **Mẹo chuyên nghiệp:** Nếu bạn đang dùng trình quản lý gói NuGet, thêm thư viện bằng +> `dotnet add package Aspose.Words` hoặc qua giao diện NuGet của Visual Studio. + +## Bước 1 – Tải tài liệu Word với chế độ khôi phục nhẹ + +Khi nhận các tệp Word từ nguồn bên ngoài, chúng có thể chứa một số lỗi nhỏ. Bật **Relaxed** recovery cho Aspose.Words tiếp tục xử lý thay vì ném ngoại lệ. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // Define where the input lives. + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + + // 1️⃣ Load the source document with relaxed recovery mode and default font settings. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() // Uses system fonts; customise if needed. + }; + + Document doc = new Document(inputPath, loadOptions); +``` + +**Tại sao điều này quan trọng:** +- `RecoveryMode.Relaxed` ngăn một đoạn văn bị hỏng làm dừng toàn bộ quá trình chuyển đổi. +- Cung cấp một đối tượng `FontSettings` đảm bảo bất kỳ phông chữ nào thiếu sẽ được thay thế một cách nhẹ nhàng, điều này rất quan trọng khi bạn sau này render công thức dưới dạng LaTeX. + +## Bước 2 – Xuất ra Markdown (OfficeMath → LaTeX, Hình ảnh qua Callback) + +Markdown không có cách native để biểu diễn công thức Word. Aspose.Words có thể dịch các đối tượng **OfficeMath** thành LaTeX, mà hầu hết các trình render Markdown đều hiểu. Hình ảnh, tuy nhiên, cần được lưu ở đâu đó; một **callback lưu tài nguyên** tùy chỉnh cho phép bạn kiểm soát hoàn toàn cấu trúc thư mục và cách đặt tên. + +```csharp + // 2️⃣ Export to Markdown – render OfficeMath as LaTeX and handle images via a custom callback. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + doc.Save(markdownPath, markdownOptions); +``` + +### Callback lưu tài nguyên + +Dưới đây là một triển khai nhỏ lưu mọi hình ảnh vào một thư mục con có tên `images` và đặt tên các tệp `img001.png`, `img002.png`, v.v. + +```csharp + // Helper class that Aspose.Words calls for each embedded resource (e.g., images). + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + + public void ResourceSaving(ResourceSavingArgs args) + { + // Ensure the images folder exists. + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + // Build a deterministic file name. + string ext = args.ResourceFileExtension; // e.g., ".png" + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +``` + +**Tại sao bạn cần điều này:** +- Nếu không có callback, Aspose.Words sẽ tạo một thư mục phẳng với các tên GUID ngẫu nhiên, gây rối khi quản lý phiên bản. +- Bằng cách kiểm soát quy tắc đặt tên, bạn giữ cho kho Markdown gọn gàng và có thể tái tạo. + +### Đầu ra Markdown dự kiến + +Mở `doc.md` sau khi chạy và bạn sẽ thấy: + +```markdown +# Sample Heading + +Here is a paragraph with some **bold** text. + +$$ +\int_{a}^{b} f(x)\,dx +$$ + +![Figure 1](images/img001.png) +``` + +Các công thức xuất hiện dưới dạng LaTeX được bao bọc trong `$$ … $$`, và các hình ảnh tham chiếu tới thư mục `images` mà bạn vừa tạo. + +## Bước 3 – Xuất ra PDF/UA‑2 (Sẵn sàng cho truy cập) + +Nếu bạn cần chia sẻ tài liệu với người dùng dựa vào trình đọc màn hình hoặc các công nghệ hỗ trợ khác, **PDF/UA‑2** là tiêu chuẩn vàng. Aspose.Words có thể thực thi điều này chỉ bằng một cờ, và nó cũng có thể làm phẳng các hình dạng nổi thành thẻ inline để chúng không bị mất trong quá trình chuyển đổi. + +```csharp + // 3️⃣ Export to PDF/UA – enforce PDF/UA‑2 compliance and embed floating shapes as inline tags. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + doc.Save(pdfPath, pdfOptions); + } +} +``` + +**Tại sao PDF/UA quan trọng:** +- PDF/UA (Universal Accessibility) đảm bảo PDF tạo ra chứa các thẻ đúng, thứ tự đọc logic, và văn bản thay thế cho hình ảnh. +- Cài đặt `ExportFloatingShapesAsInlineTag` đảm bảo các hình dạng như hộp văn bản hoặc callout không bị bỏ qua hoặc đặt sai vị trí—một lỗi thường gặp khi chuyển đổi bố cục phức tạp. + +### Kiểm tra tính tuân thủ PDF/UA + +Sau khi xuất, mở PDF trong Adobe Acrobat Pro và chạy **“Accessibility Check”** (Công cụ → Truy cập → Kiểm tra đầy đủ). Nếu công cụ báo **0 lỗi**, bạn đã thành công. + +## Trường hợp đặc biệt & Những bẫy thường gặp + +| Tình huống | Điều cần chú ý | Cách khắc phục / Khuyến nghị | +|--------------------------------------------|--------------------------------------------------------|------------------------------------------------------------| +| Tệp Word chứa **phông chữ không hỗ trợ** | Phông chữ có thể bị thay thế, làm hỏng bố cục công thức | Cung cấp một `FontSettings` tùy chỉnh với các phông thay thế. | +| Tài liệu lớn (> 100 MB) | Áp lực bộ nhớ trong quá trình chuyển đổi | Sử dụng `LoadOptions` với `LoadFormat.Docx` và stream tệp. | +| Hình ảnh là đồ họa vector **EMF/WMF** | Chúng có thể bị raster hoá không mong muốn | Chuyển chúng sang PNG qua `ImageSaveOptions` trước khi lưu. | +| PDF/UA không hợp lệ trên **bảng lồng nhau**| Thẻ có thể trở nên mơ hồ | Bật `PdfSaveOptions.TableLayout = PdfTableLayout.AutoFit` để hỗ trợ engine. | +| Cần **giữ lại các style tùy chỉnh** | Markdown có khả năng style hạn chế | Xuất một file CSS bên cạnh Markdown và tham chiếu tới nó. | + +## Ví dụ hoàn chỉnh (Tất cả mã cùng nhau) + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + const string inputPath = @"YOUR_DIRECTORY\input.docx"; + const string markdownPath = @"YOUR_DIRECTORY\doc.md"; + const string pdfPath = @"YOUR_DIRECTORY\doc.pdf"; + + // Load with relaxed recovery. + var loadOptions = new LoadOptions + { + RecoveryMode = LoadOptions.RecoveryMode.Relaxed, + FontSettings = new FontSettings() + }; + Document doc = new Document(inputPath, loadOptions); + + // Markdown export – LaTeX for equations, custom image saver. + var markdownOptions = new MarkdownSaveOptions + { + OfficeMathExportMode = MarkdownSaveOptions.OfficeMathExportMode.LaTeX, + ResourceSavingCallback = new MyMarkdownResourceSaver() + }; + doc.Save(markdownPath, markdownOptions); + + // PDF/UA‑2 export – accessibility compliance. + var pdfOptions = new PdfSaveOptions + { + Compliance = PdfCompliance.PdfUAXmpA2, + ExportFloatingShapesAsInlineTag = true + }; + doc.Save(pdfPath, pdfOptions); + } + + // Callback that stores images in an "images" sub‑folder with sequential names. + class MyMarkdownResourceSaver : IResourceSavingCallback + { + private int _counter = 1; + public void ResourceSaving(ResourceSavingArgs args) + { + string imagesFolder = System.IO.Path.Combine( + System.IO.Path.GetDirectoryName(args.DocumentPath), "images"); + System.IO.Directory.CreateDirectory(imagesFolder); + + string ext = args.ResourceFileExtension; + string fileName = $"img{_counter:D3}{ext}"; + args.ResourceFileName = System.IO.Path.Combine(imagesFolder, fileName); + _counter++; + } + } +} +``` + +Chạy chương trình, và bạn sẽ thấy cả `doc.md` (với công thức LaTeX và liên kết hình ảnh sạch) và `doc.pdf` (đầy đủ tuân thủ PDF/UA‑2) nằm trong `YOUR_DIRECTORY`. + +## Tổng quan trực quan + +![convert word to markdown example](https://example.com/placeholder.png "convert word to markdown example – shows input Word, Markdown output, and PDF/UA file") + +*Văn bản thay thế:* **convert word to markdown example** – sơ đồ quy trình chuyển đổi từ tệp Word sang Markdown và PDF/UA. + +## Tóm tắt & Các bước tiếp theo + +Chúng ta vừa **chuyển đổi Word sang Markdown** trong khi giữ nguyên công thức, lưu hình ảnh vào một thư mục gọn gàng, và tạo ra một tệp **lưu dưới dạng PDF/UA** vượt qua các kiểm tra truy cập. Những điểm quan trọng cần nhớ là: + +- Dùng `LoadOptions.RecoveryMode.Relaxed` để chịu đựng các tệp Word không hoàn hảo. +- Đặt `OfficeMathExportMode` thành `LaTeX` để render công thức sạch sẽ. +- Triển khai `ResourceSavingCallback` để kiểm soát đầu ra hình ảnh. +- Bật `PdfCompliance.PdfUAXmpA2` và `ExportFloatingShapesAsInlineTag` để tạo PDF tuân chuẩn. + +### Bạn có thể khám phá gì tiếp theo? + +- **CSS tùy chỉnh cho Markdown** – tạo stylesheet phản ánh các style trong Word. +- **Xử lý hàng loạt** – lặp qua một thư mục các tệp `.docx` để tự động hoá việc di chuyển quy mô lớn. +- **Các tính năng nâng cao của PDF/UA** – thêm thẻ tùy chỉnh, đặt thuộc tính ngôn ngữ, hoặc nhúng mô tả âm thanh. +- **Tích hợp với CI/CD** – đảm bảo mỗi bản build tạo ra các PDF truy cập được một cách tự động. + +Nếu gặp khó khăn, hãy kiểm tra lại phiên bản Aspose.Words của bạn có khớp với API được dùng ở đây không, và nhớ rằng tài liệu của thư viện là nguồn tham khảo phụ rất tốt. + +Chúc lập trình vui vẻ, và mong tài liệu của bạn luôn **đẹp** **và** **truy cập được**! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/programming-with-txtsaveoptions/_index.md b/words/vietnamese/net/programming-with-txtsaveoptions/_index.md index d9a57685a5..b00cf12b62 100644 --- a/words/vietnamese/net/programming-with-txtsaveoptions/_index.md +++ b/words/vietnamese/net/programming-with-txtsaveoptions/_index.md @@ -27,7 +27,7 @@ Nhờ các hướng dẫn này, bạn sẽ có thể khai thác đầy đủ cá | [Thêm Dấu Bidi vào Tài liệu Word](./add-bidi-marks/) | Tìm hiểu cách thêm dấu hai chiều (Bidi) vào tài liệu Word bằng Aspose.Words cho .NET với hướng dẫn này. Đảm bảo hướng văn bản phù hợp cho nội dung đa ngôn ngữ. | | [Sử dụng ký tự Tab cho mỗi cấp độ để thụt lề danh sách](./use-tab-character-per-level-for-list-indentation/) | Tìm hiểu cách tạo danh sách nhiều cấp với thụt lề theo tab bằng Aspose.Words cho .NET. Thực hiện theo hướng dẫn này để định dạng danh sách chính xác trong tài liệu của bạn. | | [Sử dụng ký tự khoảng trắng cho mỗi cấp độ để thụt lề danh sách](./use-space-character-per-level-for-list-indentation/) | Tìm hiểu cách tạo danh sách nhiều cấp với thụt lề ký tự khoảng trắng trong Aspose.Words cho .NET. Hướng dẫn từng bước để định dạng tài liệu chính xác. | - +| [Lưu docx dưới dạng txt – Xuất công thức Word sang LaTeX bằng C#](./save-docx-as-txt-export-word-equations-to-latex-with-c/) | Hướng dẫn xuất công thức Word sang định dạng LaTeX khi lưu tài liệu docx dưới dạng tệp txt bằng C#. | {{< /blocks/products/pf/tutorial-page-section >}} diff --git a/words/vietnamese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md b/words/vietnamese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md new file mode 100644 index 0000000000..6eb36fa46c --- /dev/null +++ b/words/vietnamese/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-04-05 +description: Lưu docx thành txt với Aspose.Words – nhanh chóng chuyển đổi Word sang + txt và học cách xuất các công thức toán học dưới dạng LaTeX. Mã C# đơn giản, không + cần công cụ bổ sung. +draft: false +keywords: +- save docx as txt +- convert word to txt +- how to export math +- how to save txt +- convert word equations latex +language: vi +og_description: Lưu file docx thành txt trong C# và xem cách xuất công thức sang LaTeX. + Hãy làm theo hướng dẫn từng bước này để chuyển Word sang txt mà vẫn giữ nguyên các + phương trình. +og_title: Lưu docx thành txt – Xuất các phương trình Word sang LaTeX +tags: +- Aspose.Words +- C# +- Document Conversion +title: Lưu docx thành txt – Xuất các phương trình Word sang LaTeX bằng C# +url: /vi/net/programming-with-txtsaveoptions/save-docx-as-txt-export-word-equations-to-latex-with-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# lưu docx thành txt – Xuất công thức Word sang LaTeX bằng C# + +Bạn đã bao giờ cần **save docx as txt** nhưng lo lắng rằng các công thức của mình sẽ biến mất hoặc biến thành những ký tự không đọc được? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp phải vấn đề này khi họ cố gắng **convert word to txt** để xử lý tiếp, đặc biệt khi tệp nguồn chứa các đối tượng Office Math. + +Tin tốt? Với vài dòng C# và các tùy chọn phù hợp, bạn không chỉ có thể **convert Word to txt** mà còn giữ mỗi công thức dưới dạng mã LaTeX sạch sẽ. Trong hướng dẫn này, chúng tôi sẽ đi qua toàn bộ quá trình, giải thích lý do mỗi cài đặt quan trọng, và chỉ cho bạn cách kiểm chứng kết quả. + +Chúng tôi sẽ đề cập tới: + +* Cài đặt thư viện Aspose.Words cho .NET +* Tải một tệp `.docx` chứa các công thức toán học +* Cấu hình `TxtSaveOptions` sao cho **how to export math** trở thành một chuỗi thân thiện với LaTeX +* Lưu tệp và kiểm tra đầu ra + +Khi kết thúc, bạn sẽ có một đoạn mã có thể tái sử dụng cho phép bạn **save docx as txt** trong khi bảo toàn mọi công thức dưới dạng LaTeX—hoàn hảo cho các pipeline khoa học, trình tạo trang tĩnh, hoặc bất kỳ quy trình nào cần toán học dạng văn bản thuần. + +--- + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng bạn có: + +* .NET 6.0 trở lên (mã cũng hoạt động với .NET Framework 4.6+) +* Visual Studio 2022 (hoặc bất kỳ IDE nào bạn thích) +* Gói NuGet **Aspose.Words for .NET** – cài đặt bằng + +```bash +dotnet add package Aspose.Words +``` + +Không cần bất kỳ bộ chuyển đổi hay công cụ bên ngoài nào; Aspose.Words xử lý mọi công việc nặng bên trong. + +--- + +## Bước 1: Cài đặt và tham chiếu Aspose.Words + +Đầu tiên, thêm thư viện vào dự án của bạn. Nếu bạn đang dùng dòng lệnh, chạy lệnh ở trên. Trong Visual Studio bạn cũng có thể nhấp chuột phải vào **Dependencies → Manage NuGet Packages** và tìm kiếm *Aspose.Words*. + +```csharp +// Add the namespace at the top of your file +using Aspose.Words; +using Aspose.Words.Saving; +``` + +> **Pro tip:** Sử dụng phiên bản ổn định mới nhất (tính đến tháng 4 2026 là 24.10). Các bản phát hành mới hơn mang lại các bản sửa lỗi cho việc xử lý OfficeMath, vì vậy bạn sẽ tránh được các ký hiệu bị thiếu bất ngờ. + +--- + +## Bước 2: Tải tài liệu nguồn + +Bây giờ chúng ta tải tệp `.docx` chứa các công thức mà bạn muốn giữ lại. Lớp `Document` trừu tượng hoá toàn bộ tệp Word, cho phép bạn truy cập văn bản, hình ảnh và các đối tượng Office Math. + +```csharp +// Step 2: Load the source document +Document doc = new Document("YOUR_DIRECTORY/input.docx"); + +// Quick sanity check – make sure the document actually loaded +if (doc == null || doc.PageCount == 0) +{ + throw new InvalidOperationException("The document could not be loaded or is empty."); +} +``` + +Tại sao phải tải trước? Aspose.Words phân tích tệp thành một mô hình đối tượng, cho phép chúng ta kiểm tra hoặc sửa đổi nội dung trước khi quyết định cách xuất ra. Đây là nơi các quyết định **how to export math** bắt đầu quan trọng. + +--- + +## Bước 3: Cấu hình TxtSaveOptions để xuất LaTeX + +Trung tâm của giải pháp là lớp `TxtSaveOptions`. Mặc định, lưu dưới dạng TXT sẽ loại bỏ hoàn toàn Office Math. Đặt `OfficeMathExportMode` thành `LaTeX` sẽ yêu cầu thư viện chuyển mỗi công thức thành biểu diễn LaTeX của nó. + +```csharp +// Step 3: Create TxtSaveOptions and set the OfficeMath export mode to LaTeX +TxtSaveOptions txtOptions = new TxtSaveOptions +{ + // This makes every OfficeMath object become LaTeX code in the output file + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + + // Optional: preserve line breaks as they appear in Word + PreserveTableLayout = true, + + // Optional: ensure UTF‑8 encoding so special symbols survive + Encoding = System.Text.Encoding.UTF8 +}; +``` + +**Why LaTeX?** LaTeX là ngôn ngữ chung của xuất bản khoa học. Bằng cách xuất toán học theo cách này, bạn giữ nguyên ngữ nghĩa của công thức thay vì một hình ảnh phẳng hoặc một chuỗi rối. Nếu sau này bạn đưa tệp TXT vào bộ xử lý Markdown hỗ trợ MathJax, các công thức sẽ được hiển thị hoàn hảo. + +--- + +## Bước 4: Lưu tài liệu dưới dạng plain‑text + +Với các tùy chọn đã được cấu hình, bước cuối cùng là một dòng lệnh duy nhất ghi tệp ra đĩa. + +```csharp +// Step 4: Save the document as plain‑text using the configured options +doc.Save("YOUR_DIRECTORY/MathSample.txt", txtOptions); +``` + +Xong—`.docx` của bạn bây giờ đã trở thành tệp `.txt` trong đó mỗi công thức xuất hiện dưới dạng đoạn LaTeX, sẵn sàng cho việc sử dụng tiếp. + +--- + +## Xác minh đầu ra (Cách lưu txt đúng cách) + +Mở `MathSample.txt` trong bất kỳ trình soạn thảo văn bản nào. Bạn sẽ thấy một thứ gì đó như sau: + +``` +This is a sample paragraph. + +Here is an equation in LaTeX: +\[ +\int_{a}^{b} f(x)\,dx = F(b) - F(a) +\] + +Another line of regular text. +``` + +Nếu bạn phát hiện các ký tự đặc thù của Word (ví dụ, `?` hoặc các ký hiệu bị thiếu), hãy kiểm tra lại rằng: + +* Bạn đang sử dụng phiên bản Aspose.Words mới (các bản cũ có lỗi với OfficeMath). +* Tài liệu nguồn thực sự chứa các đối tượng **OfficeMath**—không phải các đối tượng Equation Editor cũ. Đối với loại sau, bạn có thể cần chuyển chúng thủ công hoặc sử dụng phương thức `ConvertMathToOfficeMath` trước khi lưu. + +--- + +## Các biến thể phổ biến & trường hợp đặc biệt + +| Situation | What to do | +|-----------|------------| +| **đối tượng Legacy Equation Editor** | Gọi `doc.ConvertMathToOfficeMath()` trước bước 3. | +| **Bạn cần toán học Unicode thuần, không phải LaTeX** | Đặt `OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.Unicode`. | +| **Tài liệu lớn (100 + MB)** | Dòng (stream) quá trình lưu bằng cách sử dụng `doc.Save(Stream, txtOptions)` để tránh việc sử dụng bộ nhớ cao. | +| **Bạn muốn giữ nguyên tên tệp gốc** | Sử dụng `Path.GetFileNameWithoutExtension(inputPath) + ".txt"` khi tạo đường dẫn đầu ra. | + +Những điều chỉnh này trả lời câu hỏi “**how to export math**” cho các pipeline khác nhau, đảm bảo giải pháp của bạn vững chắc bất kể nguồn. + +--- + +## Ví dụ Hoạt động đầy đủ (Tất cả các bước trong một nơi) + +```csharp +using System; +using System.IO; +using Aspose.Words; +using Aspose.Words.Saving; + +class Program +{ + static void Main() + { + // 1️⃣ Install Aspose.Words via NuGet before running this code. + + // 2️⃣ Load the .docx containing equations + string inputPath = @"YOUR_DIRECTORY\input.docx"; + Document doc = new Document(inputPath); + + // Optional: Convert legacy equations to OfficeMath (covers edge cases) + doc.ConvertMathToOfficeMath(); + + // 3️⃣ Set up TXT save options – LaTeX export for math + TxtSaveOptions txtOptions = new TxtSaveOptions + { + OfficeMathExportMode = TxtSaveOptions.OfficeMathExportMode.LaTeX, + PreserveTableLayout = true, + Encoding = System.Text.Encoding.UTF8 + }; + + // 4️⃣ Define output path and save + string outputPath = Path.Combine( + Path.GetDirectoryName(inputPath), + Path.GetFileNameWithoutExtension(inputPath) + ".txt"); + + doc.Save(outputPath, txtOptions); + + Console.WriteLine($"✅ Successfully saved '{outputPath}'."); + } +} +``` + +Chạy chương trình, mở tệp `.txt` được tạo, và bạn sẽ thấy các công thức LaTeX được nhúng ngay tại vị trí của chúng. Đây là cách đơn giản nhất để **convert + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/words/vietnamese/net/working-with-fonts/_index.md b/words/vietnamese/net/working-with-fonts/_index.md index 3ff7c6370a..ee176e2f47 100644 --- a/words/vietnamese/net/working-with-fonts/_index.md +++ b/words/vietnamese/net/working-with-fonts/_index.md @@ -32,6 +32,7 @@ Cho dù bạn muốn định dạng văn bản bằng các phông chữ khác nh | [Đặt dấu nhấn mạnh phông chữ](./set-font-emphasis-mark/) | Tìm hiểu cách đặt dấu nhấn mạnh phông chữ trong tài liệu Word bằng Aspose.Words cho .NET với hướng dẫn chi tiết từng bước này. Hoàn hảo cho các nhà phát triển .NET. | | [Thiết lập thư mục phông chữ](./set-fonts-folders/) | Tìm hiểu cách thiết lập thư mục phông chữ tùy chỉnh trong Aspose.Words cho .NET với hướng dẫn từng bước toàn diện này. Hoàn hảo cho các nhà phát triển muốn cải thiện phông chữ tài liệu. | | [Bật Tắt Thay Thế Phông Chữ](./enable-disable-font-substitution/) | Tìm hiểu cách bật hoặc tắt tính năng thay thế phông chữ trong tài liệu Word bằng Aspose.Words cho .NET. Đảm bảo tài liệu của bạn trông nhất quán trên mọi nền tảng. | +| [Thay thế phông chữ Aspose – Phát hiện phông chữ thiếu trong tài liệu Word](./aspose-font-substitution-detect-missing-fonts-in-word-docume/) | Tìm hiểu cách phát hiện các phông chữ thiếu trong tài liệu Word bằng Aspose.Words cho .NET. | | [Thiết lập cài đặt dự phòng phông chữ](./set-font-fallback-settings/) | Tìm hiểu cách thiết lập cài đặt thay thế phông chữ trong Aspose.Words cho .NET và tùy chỉnh thay thế phông chữ trong tài liệu Word của bạn. | | [Tải Cài đặt Noto Fallback](./load-noto-fallback-settings/) | Tìm hiểu cách tải cài đặt Noto fallback trong tài liệu Word bằng Aspose.Words cho .NET. Làm theo hướng dẫn từng bước của chúng tôi để đảm bảo tất cả các ký tự hiển thị chính xác. | | [Đặt Fonts Folders Mặc định](./set-fonts-folders-default-instance/) | Tìm hiểu cách thiết lập thư mục phông chữ cho phiên bản mặc định trong Aspose.Words cho .NET với hướng dẫn từng bước này. Tùy chỉnh tài liệu Word của bạn một cách dễ dàng. | diff --git a/words/vietnamese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md b/words/vietnamese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md new file mode 100644 index 0000000000..0eca09f4c3 --- /dev/null +++ b/words/vietnamese/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/_index.md @@ -0,0 +1,217 @@ +--- +category: general +date: 2026-04-05 +description: Hướng dẫn thay thế phông chữ của Aspose để phát hiện phông chữ thiếu + khi tải tài liệu Word. Tìm hiểu cách cấu hình cài đặt phông chữ và xử lý phông chữ + thiếu một cách hiệu quả. +draft: false +keywords: +- aspose font substitution +- detect missing fonts +- load word document +- configure font settings +- handle missing fonts +language: vi +og_description: Hướng dẫn thay thế phông chữ của Aspose để phát hiện các phông chữ + thiếu khi tải tài liệu Word. Tìm hiểu cách cấu hình cài đặt phông chữ và xử lý các + phông chữ thiếu một cách hiệu quả. +og_title: Thay thế phông chữ Aspose – Phát hiện phông chữ thiếu trong tài liệu Word +tags: +- Aspose.Words +- C# +- Font Management +title: Thay thế phông chữ Aspose – Phát hiện phông chữ thiếu trong tài liệu Word +url: /vi/net/working-with-fonts/aspose-font-substitution-detect-missing-fonts-in-word-docume/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Font Substitution – Phát hiện phông chữ thiếu trong tài liệu Word + +Bạn đã bao giờ gặp một tệp Word trông hoàn hảo trên một máy nhưng lại hiển thị các thay đổi phông chữ lạ trên máy khác chưa? Đó là vấn đề **aspose font substitution** kinh điển, thường có nghĩa là một số phông chữ bị thiếu trên hệ thống đích. Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn, từng bước một, cách **phát hiện phông chữ thiếu** khi **tải một tài liệu Word**, cách **cấu hình cài đặt phông chữ**, và cách **xử lý phông chữ thiếu** một cách nhẹ nhàng. + +Chúng tôi sẽ đi qua một ví dụ C# đầy đủ, có thể chạy được, giải thích lý do mỗi dòng quan trọng, và thậm chí cho bạn thấy đầu ra console mà bạn nên mong đợi. Khi kết thúc, bạn sẽ có thể phát hiện các thay thế phông chữ ngay khi tài liệu được tải — không cần đoán mò. + +## Những gì bạn sẽ học + +- Cách bật bộ thu thập chẩn đoán của Aspose.Words để nhận cảnh báo về phông chữ. +- Mã chính xác cần **tải một tài liệu Word** với **cài đặt phông chữ** tùy chỉnh. +- Cách lặp qua các đối tượng `WarningInfo` để liệt kê mọi phông chữ đã được thay thế. +- Mẹo để ẩn các cảnh báo không mong muốn hoặc cung cấp phông chữ dự phòng. +- Một mẫu sẵn sàng chạy mà bạn có thể sao chép‑dán vào Visual Studio. + +### Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (API hoạt động tương tự trên .NET Framework). +- Aspose.Words for .NET (gói NuGet `Aspose.Words`). +- Một tệp Word tham chiếu tới một phông chữ bạn không có trên máy (ví dụ, `MissingFont.docx`). + +Nếu bạn đã có những thứ trên, hãy bắt đầu. + +## Bước 1 – Bật Bộ thu thập Chẩn đoán (Cấu hình Cài đặt Phông chữ) + +Điều đầu tiên: Aspose.Words chỉ ghi lại cảnh báo thay thế phông chữ nếu bạn bật nó. Điều này được thực hiện bằng cách tạo một đối tượng `FontSettings` và gán nó cho một thể hiện `LoadOptions`. Hãy nghĩ đây như việc bật “đèn debug” cho việc xử lý phông chữ. + +```csharp +using Aspose.Words; +using Aspose.Words.Fonts; + +// Step 1: Prepare load options with a fresh FontSettings instance. +LoadOptions loadOptions = new LoadOptions +{ + // The FontSettings object is the hub for all font‑related configuration. + FontSettings = new FontSettings() +}; +``` + +**Tại sao?** +Nếu không có đối tượng `FontSettings`, bộ thu thập cảnh báo sẽ im lặng và bạn sẽ không bao giờ biết phông chữ nào đã bị thay thế. Bằng cách khởi tạo nó rỗng, chúng ta cho phép Aspose sử dụng các phông chữ hệ thống mặc định *và* theo dõi mọi sự thay thế. + +> **Mẹo chuyên nghiệp:** Nếu bạn biết một thư mục cụ thể chứa các phông chữ công ty, hãy chỉ định `FontSettings` tới đó bằng `SetFontsFolder("path")`. Điều này có thể giảm số lượng cảnh báo phông chữ thiếu. + +## Bước 2 – Tải Tài liệu với Các Tùy chọn Đã Cấu hình (Load Word Document) + +Bây giờ bộ thu thập đã hoạt động, hãy tải tệp `.docx` của bạn bằng cùng một `LoadOptions`. Đây là thời điểm Aspose quét tài liệu, tìm mọi tham chiếu phông chữ và quyết định có cần thay thế hay không. + +```csharp +// Step 2: Load the Word file while applying the previously defined load options. +Document document = new Document(@"C:\Docs\MissingFont.docx", loadOptions); +``` + +**Tại sao điều này quan trọng?** +Nếu bạn chỉ gọi `new Document("MissingFont.docx")`, các cài đặt mặc định sẽ được áp dụng *và* danh sách cảnh báo sẽ trống. Việc truyền `loadOptions` đảm bảo bộ thu thập chẩn đoán được gắn vào quy trình tải. + +## Bước 3 – Lấy và Hiển thị Cảnh báo Thay thế Phông chữ (Detect Missing Fonts) + +Sau khi tài liệu đã được nạp vào bộ nhớ, Aspose lưu mọi cảnh báo trong `document.WarningCallback.Warnings`. Duyệt qua bộ sưu tập này, lọc các mục có `WarningType.FontSubstitution`, và in ra mô tả. Mỗi mô tả cho bạn biết phông chữ nào bị thiếu và phông chữ nào đã được dùng thay thế. + +```csharp +// Step 3: Examine the warning list for any font substitution entries. +foreach (WarningInfo warningInfo in document.WarningCallback.Warnings) +{ + if (warningInfo.Type == WarningType.FontSubstitution) + { + // The Description contains a human‑readable message, e.g., + // "Font 'Comic Sans MS' was not found. Substituted with 'Arial'." + Console.WriteLine($"Substituted font: {warningInfo.Description}"); + } +} +``` + +**Đầu ra console dự kiến** + +``` +Substituted font: Font 'MyCustomFont' was not found. Substituted with 'Arial'. +Substituted font: Font 'Times New Roman' was not found. Substituted with 'Calibri'. +``` + +Đầu ra này cho bạn biết chính xác những phông chữ nào đang thiếu trên máy chạy mã. Bạn có thể quyết định cài đặt các phông chữ thiếu, nhúng chúng vào tài liệu, hoặc giữ nguyên việc thay thế. + +![Kết quả console hiển thị cảnh báo thay thế phông chữ của Aspose](/images/aspose-font-substitution-console.png) + +*Văn bản thay thế ảnh:* aspose font substitution – console output listing substituted fonts + +## Bước 4 – Tùy chọn: Tùy chỉnh Hành vi Thay thế (Handle Missing Fonts) + +Đôi khi bạn không chỉ muốn biết *rằng* một sự thay thế đã xảy ra — bạn còn muốn kiểm soát *cách* nó xảy ra. Aspose.Words cho phép bạn đăng ký một `IFontSubstitutionRule` tùy chỉnh. Dưới đây là một ví dụ nhanh buộc bất kỳ phông chữ nào thiếu đều sẽ quay lại `Tahoma`. + +```csharp +// Optional Step 4 – Define a custom substitution rule. +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + // Always return Tahoma regardless of the missing font. + return new FontInfo("Tahoma"); + } +} + +// Apply the rule to the FontSettings we created earlier. +loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add(new TahomaFallbackRule()); +``` + +**Khi nào bạn sẽ dùng điều này?** +Nếu bạn đang tạo PDF cho một dịch vụ web và biết rằng mọi khách hàng đều có thể hiển thị `Tahoma`, việc buộc fallback này đảm bảo tính nhất quán về giao diện mà không cần phải phân phối hàng chục tệp phông chữ. + +## Ví dụ Hoạt động Đầy đủ (Tất cả các Bước Kết hợp) + +Dưới đây là toàn bộ chương trình mà bạn có thể dán vào một dự án console mới. Nó biên dịch ngay, với giả định bạn đã cài đặt gói NuGet Aspose.Words. + +```csharp +using System; +using Aspose.Words; +using Aspose.Words.Fonts; + +class Program +{ + static void Main() + { + // ------------------------------------------------- + // Step 1 – Enable diagnostic collector (configure font settings) + // ------------------------------------------------- + LoadOptions loadOptions = new LoadOptions + { + FontSettings = new FontSettings() + }; + + // ------------------------------------------------- + // Optional: Force all missing fonts to Tahoma + // ------------------------------------------------- + loadOptions.FontSettings.SubstitutionSettings.FontSubstitutionRules.Add( + new TahomaFallbackRule()); + + // ------------------------------------------------- + // Step 2 – Load the document (load word document) + // ------------------------------------------------- + Document doc = new Document(@"C:\Docs\MissingFont.docx", loadOptions); + + // ------------------------------------------------- + // Step 3 – List any font substitutions (detect missing fonts) + // ------------------------------------------------- + foreach (WarningInfo warning in doc.WarningCallback.Warnings) + { + if (warning.Type == WarningType.FontSubstitution) + Console.WriteLine($"Substituted font: {warning.Description}"); + } + } +} + +// ------------------------------------------------- +// Optional custom rule class (handle missing fonts) +// ------------------------------------------------- +class TahomaFallbackRule : IFontSubstitutionRule +{ + public FontInfo Substitute(FontInfo fontInfo, FontSubstitutionInfo substitutionInfo) + { + return new FontInfo("Tahoma"); + } +} +``` + +Chạy chương trình, quan sát console, và bạn sẽ thấy mọi sự kiện phông chữ thiếu được in ra. Từ đó, bạn có thể quyết định cài đặt phông chữ thiếu, nhúng chúng, hoặc giữ nguyên fallback. + +## Câu hỏi Thường gặp + +**H: Điều này có hoạt động với chuyển đổi PDF không?** +Có. Khi bạn sau này gọi `doc.Save("output.pdf")`, bất kỳ phông chữ nào đã được thay thế trong quá trình tải sẽ là những phông chữ được nhúng trong PDF. Vì vậy, việc bắt các cảnh báo sớm giúp bạn tránh những thay đổi phông chữ bất ngờ trong PDF cuối cùng. + +**H: Nếu tôi có nhiều tài liệu cần xử lý thì sao?** +Bao bọc logic tải trong một khối try‑catch và tái sử dụng một thể hiện `FontSettings` duy nhất cho các tài liệu. Điều này giảm tải và giữ cho bộ thu thập cảnh báo hoạt động cho mỗi tệp. + +**H: Tôi có thể tắt hoàn toàn các cảnh báo không?** +Bạn có thể đặt `loadOptions.WarningCallback = null;` trước khi tải, nhưng sẽ mất khả năng **phát hiện phông chữ thiếu** — thường không phải là điều bạn muốn. + +## Kết luận + +Chúng ta đã bao quát mọi thứ bạn cần để làm chủ **aspose font substitution**: bật bộ thu thập chẩn đoán, tải tệp Word với **cài đặt phông chữ** tùy chỉnh, trích xuất danh sách phông chữ thiếu, và thậm chí ghi đè quy tắc thay thế mặc định để **xử lý phông chữ thiếu** theo cách của bạn. Chỉ với vài dòng C#, bạn sẽ có được khả năng quan sát đầy đủ các vấn đề phông chữ mà nếu không sẽ ẩn sau những thay đổi bố cục tinh vi. + +Bước tiếp theo? Hãy thử nhúng các phông chữ gốc vào tài liệu bằng `FontSettings.SetFontsFolder` hoặc khám phá `FontSourceBase` để tải phông chữ từ cơ sở dữ liệu. Bạn cũng có thể thử nghiệm với bộ sưu tập `Document.BuiltInStyle` để xem cách các thay đổi phông chữ ở mức độ style lan truyền như thế nào. + +Có thêm câu hỏi về Aspose.Words hoặc quản lý phông chữ? Để lại bình luận, khám phá tài liệu chính thức của Aspose, hoặc khởi động một dự án mới và chơi thử với mã ở trên. Chúc lập trình vui vẻ, và mong tài liệu của bạn luôn hiển thị đúng như mong muốn! + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file