diff --git a/html/arabic/java/advanced-usage/_index.md b/html/arabic/java/advanced-usage/_index.md index 5fd5162504..cad57ab10e 100644 --- a/html/arabic/java/advanced-usage/_index.md +++ b/html/arabic/java/advanced-usage/_index.md @@ -136,6 +136,9 @@ weight: 20 ### [كيفية تشغيل JavaScript في Java – دليل كامل](./how-to-run-javascript-in-java-complete-guide/) تعلم كيفية تشغيل كود JavaScript داخل تطبيقات Java باستخدام Aspose.HTML for Java. +### [XPath مع مساحات الأسماء في Java – دليل كامل لاختيار عناصر SVG](./xpath-with-namespaces-in-java-complete-guide-to-selecting-sv/) +تعلم كيفية استخدام XPath مع مساحات الأسماء في Java لاختيار ومعالجة عناصر SVG بدقة في مستندات HTML. + --- **آخر تحديث:** 2025-11-29 diff --git a/html/arabic/java/advanced-usage/xpath-with-namespaces-in-java-complete-guide-to-selecting-sv/_index.md b/html/arabic/java/advanced-usage/xpath-with-namespaces-in-java-complete-guide-to-selecting-sv/_index.md new file mode 100644 index 0000000000..4c1db593f2 --- /dev/null +++ b/html/arabic/java/advanced-usage/xpath-with-namespaces-in-java-complete-guide-to-selecting-sv/_index.md @@ -0,0 +1,252 @@ +--- +category: general +date: 2026-06-19 +description: شرح XPath مع المساحات الاسمية في Java. تعلّم كيفية تحميل مستند HTML، + تسجيل مساحة اسمية، واختيار مسارات SVG باستخدام تقنيات مساحة اسمية في Java XPath. +draft: false +keywords: +- xpath with namespaces +- java xpath namespace +- how to select svg +- load html document +- extract svg paths +language: ar +og_description: يتيح لك XPath مع المساحات الاسمية في Java تحميل مستند HTML واستخراج + مسارات SVG. اتبع هذا الدليل لإتقان استخدام مساحات الاسم في Java XPath. +og_title: XPath مع المساحات الاسمية في جافا – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: XPath with namespaces in Java explained. Learn how to load HTML document, + register a namespace, and select SVG paths using java xpath namespace techniques. + headline: XPath with Namespaces in Java – Complete Guide to Selecting SVG Elements + type: TechArticle +tags: +- Java +- XPath +- SVG +- HTML Parsing +title: XPath مع الفضاءات الاسمية في جافا – دليل شامل لاختيار عناصر SVG +url: /ar/java/advanced-usage/xpath-with-namespaces-in-java-complete-guide-to-selecting-sv/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# XPath مع المساحات الاسمية في Java – دليل كامل لاختيار عناصر SVG + +هل تساءلت يومًا كيف تستخدم **xpath with namespaces** عندما يحتوي HTML الخاص بك على SVG مضمّن؟ لست وحدك. في العديد من المشاريع الواقعية—مثل لوحات التحكم التي تدمج مخططات أو أدوات استخراج الويب التي تحتاج إلى بيانات متجهة—ليس الاستعلام عن DOM كافيًا لأن عناصر SVG تعيش في مساحة اسم XML منفصلة. الخبر السار؟ ببضع أسطر من Java يمكنك تسجيل مساحة اسم SVG، تشغيل تعبير XPath، واستخراج كل `` تحتاجه. + +في هذا الدرس سنستعرض تحميل مستند HTML، تسجيل مساحة اسم SVG، واستخدام حيل **java xpath namespace** لتعلم **how to select svg**. في النهاية ستتمكن من **extract svg paths** من أي ملف HTML دون عناء. + +--- + +## ما ستحتاجه + +- Java 17 (أو أي JDK حديث) – الكود يعمل على إصدارات أقدم أيضًا، لكن JDK 17 هو الأنسب. +- مكتبة Aspose.HTML for Java (المقتطف يستخدم `com.aspose.html.*`). احصل عليها من Maven Central أو موقع Aspose. +- ملف HTML بسيط يحتوي على كتلة `` (سنسميه `graphics.html`). +- بيئة التطوير المفضلة لديك (IntelliJ IDEA، Eclipse، أو حتى VS Code) – أنا أفضل IntelliJ بفضل أدوات إعادة الهيكلة القوية. + +هذا كل شيء. لا أدوات بناء إضافية، لا محللات XML ثقيلة، فقط بعض الاعتمادات والكود الذي ستراه أدناه. + +--- + +## الخطوة 1 – تحميل مستند HTML (load html document) + +قبل أن نتمكن من الاستعلام عن أي شيء، نحتاج إلى جلب HTML إلى الذاكرة. Aspose.HTML يجعل ذلك سهلًا: + +```java +import com.aspose.html.*; +import com.aspose.html.dom.*; + +public class XPathNamespaceDemo { + public static void main(String[] args) throws Exception { + // Load the HTML file from your file system + try (HTMLDocument document = HTMLDocument.load("YOUR_DIRECTORY/graphics.html")) { + // The rest of the steps go here... + } + } +} +``` + +> **لماذا هذا مهم:** `HTMLDocument.load` يحلل العلامات، يبني شجرة DOM، ويحافظ على مساحات الاسم الأصلية. إذا تخطيت هذه الخطوة وحاولت تحليل سلسلة خام، ستفقد معلومات مساحة الاسم ولن يتطابق XPath مع عنصر ``. + +--- + +## الخطوة 2 – تسجيل مساحة اسم SVG (java xpath namespace) + +SVG يعيش في مساحة الاسم `http://www.w3.org/2000/svg`. إذا لم تخبر محرك XPath عنها، فإن التعبير `//svg:path` سيعيد قائمة عقد فارغة. تسجيل بادئة أمر بسيط كالتالي: + +```java +// Register the SVG namespace with a prefix "svg" +document.getNamespaces().add("svg", "http://www.w3.org/2000/svg"); +``` + +> **نصيحة محترف:** اختر بادئة قصيرة وسهلة التذكر. “svg” هو التقليدي، لكن يمكنك استخدام “s” أو أي شيء آخر—فقط كن متسقًا في سلسلة XPath الخاصة بك. + +--- + +## الخطوة 3 – اختيار جميع عناصر `` (how to select svg) + +الآن الجزء الممتع: تشغيل استعلام XPath فعليًا. لأننا ربطنا البادئة، يستطيع المحرك حلها بشكل صحيح. + +```java +// Use an XPath expression to select all elements +NodeList svgPaths = document.selectNodes("//svg:path"); + +// Print how many we found +System.out.println("Found " + svgPaths.getLength() + " SVG paths."); +``` + +إذا شغلت البرنامج مع ملف HTML غني بـ SVG، يجب أن ترى شيئًا مثل: + +``` +Found 12 SVG paths. +``` + +> **ما الذي يحدث خلف الكواليس؟** `selectNodes` يترجم XPath، يجوب DOM، ويعيد `NodeList` حي. كل إدخال هو عقدة تمثل عنصر ``، مع خاصية `d` وأي معلومات نمطية. + +--- + +## الخطوة 4 – استخراج خاصية `d` من كل مسار (extract svg paths) + +العثور على العقد هو نصف القصة فقط. غالبًا ما تحتاج إلى بيانات المسار الفعلية (`d`) لتصويرها أو تحليلها أو تحويل الأشكال المتجهة. + +```java +for (int i = 0; i < svgPaths.getLength(); i++) { + // Cast the generic Node to an Element so we can access attributes + Element pathElement = (Element) svgPaths.item(i); + String dAttribute = pathElement.getAttribute("d"); + System.out.println("Path " + (i + 1) + ": " + dAttribute); +} +``` + +سيعرض الإخراج سلسلة هندسة كل مسار SVG، على سبيل المثال: + +``` +Path 1: M10 10 L90 10 L90 90 L10 90 Z +Path 2: M20 20 C40 20, 60 40, 80 80 +... +``` + +> **معالجة الحالات الحدية:** قد تفتقر بعض عناصر `` إلى خاصية `d` (نادر لكن ممكن). في هذه الحالة `getAttribute` يعيد سلسلة فارغة. يمكنك الحماية باستخدام شرط بسيط `if (!dAttribute.isEmpty())`. + +--- + +## الخطوة 5 – جمع كل شيء معًا – مثال كامل قابل للتنفيذ + +فيما يلي البرنامج الكامل، جاهز للنسخ‑اللصق في ملف `XPathNamespaceDemo.java`. يتضمن معالجة الأخطاء، تعليقات، وطريقة مساعدة صغيرة للحفاظ على نظافة طريقة `main`. + +```java +import com.aspose.html.*; +import com.aspose.html.dom.*; + +public class XPathNamespaceDemo { + + public static void main(String[] args) throws Exception { + // Adjust the path to point at your actual HTML file + String htmlPath = "YOUR_DIRECTORY/graphics.html"; + + // Load, register namespace, select, and extract + try (HTMLDocument document = HTMLDocument.load(htmlPath)) { + registerSvgNamespace(document); + NodeList svgPaths = selectSvgPaths(document); + printPathCount(svgPaths); + extractAndPrintPathData(svgPaths); + } + } + + // Step 2 – Register namespace + private static void registerSvgNamespace(HTMLDocument doc) { + doc.getNamespaces().add("svg", "http://www.w3.org/2000/svg"); + } + + // Step 3 – XPath selection + private static NodeList selectSvgPaths(HTMLDocument doc) { + return doc.selectNodes("//svg:path"); + } + + // Helper – print how many we found + private static void printPathCount(NodeList list) { + System.out.println("Found " + list.getLength() + " SVG paths."); + } + + // Step 4 – Extract and display each 'd' attribute + private static void extractAndPrintPathData(NodeList list) { + for (int i = 0; i < list.getLength(); i++) { + Element path = (Element) list.item(i); + String d = path.getAttribute("d"); + if (!d.isEmpty()) { + System.out.println("Path " + (i + 1) + ": " + d); + } else { + System.out.println("Path " + (i + 1) + " has no 'd' attribute."); + } + } + } +} +``` + +شغّله باستخدام `javac` و `java` كالمعتاد: + +```bash +javac -cp "path/to/aspose-html.jar" XPathNamespaceDemo.java +java -cp ".:path/to/aspose-html.jar" XPathNamespaceDemo +``` + +يجب أن ترى عدد المسارات متبوعًا بكل سلسلة `d` مطبوعة على وحدة التحكم. + +--- + +## المشكلات الشائعة وكيفية تجنّبها + +| المشكلة | سبب حدوثها | الحل | +|-------|----------------|-----| +| **مجموعة نتائج فارغة** | لم يتم تسجيل مساحة الاسم أو البادئة غير صحيحة. | تأكد من تشغيل `document.getNamespaces().add("svg", "http://www.w3.org/2000/svg")` قبل `selectNodes`. | +| **`ClassCastException`** | محاولة تحويل عقدة غير عنصر (مثل عقدة نص). | تحقق من أن XPath يعيد عناصر فقط (`//svg:path`). | +| **غياب خاصية `d`** | بعض مسارات SVG تُولد ديناميكيًا أو تستخدم مراجع ``. | افحص `path.getAttribute("d")` للعثور على سلاسل فارغة وتعامل معها وفقًا لذلك. | +| **تباطؤ الأداء على ملفات ضخمة** | XPath يمر على كامل DOM في كل استدعاء. | خزن `NodeList` مؤقتًا أو استخدم محلل تدفق إذا كنت تعالج ميغابايتات من SVG. | + +--- + +## توسيع المثال (how to select svg) + +بعد إتقان اختيار ``، يمكنك تطبيق النمط نفسه على عناصر SVG أخرى: + +- **اختيار جميع الدوائر:** `NodeList circles = document.selectNodes("//svg:circle");` +- **استخراج ألوان التعبئة:** `String fill = ((Element) circle).getAttribute("fill");` +- **التصفية حسب الخاصية:** `NodeList redPaths = document.selectNodes("//svg:path[@stroke='red']");` + +المفتاح دائمًا هو نفسه: سجل مساحة الاسم، صغ XPath صحيح، وتكرار العقد الناتجة. + +--- + +## نظرة بصرية + +![Diagram showing xpath with namespaces flowchart](xpath-namespaces-diagram.png){alt="مخطط تدفق xpath مع namespaces"} + +الصورة (النص البديل يتضمن الكلمة المفتاحية الأساسية) توضح خط الأنابيب المكوّن من أربع خطوات: تحميل → تسجيل → استعلام → استخراج. + +--- + +## الخلاصة + +لقد غطينا كل ما تحتاج معرفته حول **xpath with namespaces** في Java: تحميل مستند HTML، تسجيل مساحة اسم SVG، كتابة تعبير XPath لتعلم **how to select svg**، وأخيرًا **extract svg paths** للمعالجة اللاحقة. المثال الكامل يعمل مباشرة، والنصائح الإضافية تساعدك على تجنب الفخاخ الشائعة. + +ما الخطوة التالية؟ جرّب تحويل سلاسل `d` إلى كائنات Java2D `Path2D`، أو مررها إلى مكتبة رسومية لتصيير المتجهات. يمكنك أيضًا استكشاف كتابة المسارات المستخرجة إلى ملف SVG منفصل—مفيد لإنشاء حزم أيقونات مخصصة بسرعة. + +إذا واجهت أي صعوبات، اترك تعليقًا أدناه أو راجع وثائق Aspose.HTML Java للحصول على تفاصيل أعمق عن الـ API. برمجة سعيدة، ولتُعيد XPath دائمًا ما تتوقعه! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تُبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة شفرة كاملة مع شروحات خطوة‑بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [How to Edit HTML Document Tree in Aspose.HTML for Java](/html/english/java/editing-html-documents/edit-html-document-tree/) +- [Handle Document Load Events in Aspose.HTML for Java](/html/english/java/creating-managing-html-documents/handle-document-load-events/) +- [Save SVG Document in Aspose.HTML for Java](/html/english/java/saving-html-documents/save-svg-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/java/conversion-html-to-other-formats/_index.md b/html/arabic/java/conversion-html-to-other-formats/_index.md index 7c53c64117..ae4ccbe390 100644 --- a/html/arabic/java/conversion-html-to-other-formats/_index.md +++ b/html/arabic/java/conversion-html-to-other-formats/_index.md @@ -79,8 +79,6 @@ XPS هو صيغة الطباعة الخاصة بمايكروسوفت. باستخ ### تحويل SVG إلى XPS حوّل رسومات SVG إلى صيغة XPS للطباعة المتسقة عبر الأجهزة. -في الختام، إتقان **html to pdf java** ومجموعة التحويلات الأوسع يفتح أمام أي مطور Java تدفقات عمل مستندات قوية. يقدم Aspose.HTML for Java دروسًا شاملة وسهلة المتابعة تتيح لك تحويل HTML وMarkdown وSVG إلى الصيغ التي تحتاجها، بجودة عالية وتحكم كامل. - ## التحويل - دروس تحويل HTML إلى صيغ أخرى ### [تحويل HTML إلى PDF](./convert-html-to-pdf/) تعلم كيفية تحويل HTML إلى PDF في Java باستخدام Aspose.HTML. أنشئ ملفات PDF عالية الجودة من محتوى HTML بسهولة. @@ -96,8 +94,11 @@ XPS هو صيغة الطباعة الخاصة بمايكروسوفت. باستخ حوّل SVG إلى PDF في Java باستخدام Aspose.HTML. حل سلس لتحويل المستندات بجودة عالية. ### [تحويل SVG إلى XPS](./convert-svg-to-xps/) تعلم كيفية تحويل SVG إلى XPS باستخدام Aspose.HTML for Java. دليل بسيط خطوة بخطوة لتحويلات سلسة. +### [تحويل HTML إلى PDF في Java – دليل خطوة بخطوة](./html-to-pdf-tutorial-convert-html-to-pdf-in-java/) +تعلم كيفية تحويل HTML إلى PDF في Java باستخدام Aspose.HTML. دليل شامل لإنشاء ملفات PDF عالية الجودة. ### [تحويل HTML إلى PDF في Java – دليل خطوة بخطوة مع إعدادات حجم الصفحة](./convert-html-to-pdf-in-java-step-by-step-guide-with-page-siz/) تعلم تحويل HTML إلى PDF في Java مع إعدادات حجم الصفحة خطوة بخطوة باستخدام Aspose.HTML. +### [تحويل HTML إلى PDF في Java – دليل كامل خطوة بخطوة](./convert-html-to-pdf-in-java-full-step-by-step-guide/) ## الأسئلة المتكررة diff --git a/html/arabic/java/conversion-html-to-other-formats/convert-html-to-pdf-in-java-full-step-by-step-guide/_index.md b/html/arabic/java/conversion-html-to-other-formats/convert-html-to-pdf-in-java-full-step-by-step-guide/_index.md new file mode 100644 index 0000000000..f025a8573a --- /dev/null +++ b/html/arabic/java/conversion-html-to-other-formats/convert-html-to-pdf-in-java-full-step-by-step-guide/_index.md @@ -0,0 +1,237 @@ +--- +category: general +date: 2026-06-19 +description: تحويل HTML إلى PDF في Java باستخدام Aspose.HTML. تعلّم كيفية إنشاء PDF + من ملف HTML، وضبط خيارات الصفحة، وإضافة رؤوس في مثال كامل. +draft: false +keywords: +- convert html to pdf +- generate pdf from html file +- how to convert html to pdf java +language: ar +og_description: تحويل HTML إلى PDF في Java باستخدام Aspose.HTML. يوضح هذا الدليل كيفية + إنشاء PDF من ملف HTML مع تخطيط مخصص ورؤوس. +og_title: تحويل HTML إلى PDF في Java – دليل برمجة شامل +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Convert HTML to PDF in Java with Aspose.HTML. Learn how to generate + PDF from HTML file, set page options, and add headers in a complete example. + headline: Convert HTML to PDF in Java – Full Step‑by‑Step Guide + type: TechArticle +- description: Convert HTML to PDF in Java with Aspose.HTML. Learn how to generate + PDF from HTML file, set page options, and add headers in a complete example. + name: Convert HTML to PDF in Java – Full Step‑by‑Step Guide + steps: + - name: Full Listing + text: 'Putting everything together, here’s the complete, ready‑to‑run program:' + - name: 1. HTML File Not Found + text: 'If `htmlFilePath` points to a non‑existent file, `Converter.convert` throws + a `FileNotFoundException`. Wrap the call in a try‑catch block to provide a friendly + message:' + - name: 2. Custom Page Sizes + text: 'Sometimes you need A4 or a custom dimension. Replace `PageSize.LETTER` + with a custom `SizeF`:' + - name: 3. Adding a Footer + text: 'Just like the header, you can inject footer HTML:' + type: HowTo +tags: +- Java +- PDF +- Aspose.HTML +title: تحويل HTML إلى PDF في جافا – دليل كامل خطوة بخطوة +url: /ar/java/conversion-html-to-other-formats/convert-html-to-pdf-in-java-full-step-by-step-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل HTML إلى PDF في Java – دليل خطوة بخطوة كامل + +هل تحتاج إلى **تحويل HTML إلى PDF** في Java؟ تحويل HTML إلى PDF هو طلب شائع عندما تريد إنشاء فواتير قابلة للطباعة، تقارير، أو كتب إلكترونية مباشرة من محتوى الويب. في هذا الدرس سنستعرض مثالًا واقعيًا يوضح ليس فقط كيفية **إنشاء PDF من ملف HTML** بل أيضًا يجيب على السؤال المتكرر **كيف يمكن تحويل HTML إلى PDF باستخدام Java** باستخدام مكتبة Aspose.HTML. + +تخيل أن لديك ملف `invoice.html` يجب إرساله للعملاء كمرفق PDF. بدلاً من طباعة الصفحة يدويًا، يمكنك أتمتة العملية بأكملها ببضع أسطر من كود Java. بنهاية هذا الدليل ستحصل على برنامج جاهز للتنفيذ يُنشئ PDF به هوامش مناسبة، رأس متكرر، وحجم الصفحة الدقيق الذي تحتاجه. + +## ما ستحتاجه + +- **Java Development Kit (JDK) 8 أو أحدث** – أي نسخة حديثة تعمل بشكل جيد. +- **Aspose.HTML for Java** ملفات JAR (يمكنك سحبها من Maven Central أو تنزيل أحدث إصدار). +- ملف HTML بسيط (سنستخدم `invoice.html` الموجود في مجلد تختاره). +- بيئة التطوير المفضلة لديك أو محرر نصوص بسيط – سأستخدم IntelliJ IDEA للصور، لكن الكود لا يعتمد على أي IDE. + +> **نصيحة احترافية:** إذا كنت تستخدم Maven، أضف الاعتماد التالي إلى ملف `pom.xml` الخاص بك: + +```xml + + com.aspose + aspose-html + 23.9 + +``` + +الآن بعد أن انتهينا من المتطلبات الأولية، لننتقل إلى خطوات التحويل الفعلية. + +## الخطوة 1: إعداد المشروع **لتحويل HTML إلى PDF** + +أولاً، أنشئ فئة Java جديدة تسمى `ConvertHtmlToPdfWithOptions`. ستحمل هذه الفئة طريقة `main` التي تدير عملية التحويل. الهدف الأساسي من هذه الخطوة هو التأكد من أن فئات Aspose.HTML متاحة على مسار الفئة (classpath). + +```java +import com.aspose.html.converters.*; +import com.aspose.html.drawing.*; + +public class ConvertHtmlToPdfWithOptions { + public static void main(String[] args) throws Exception { + // The rest of the code will go here + } +} +``` + +> **لماذا هذا مهم:** استيراد `com.aspose.html.converters.*` يمنحك الوصول إلى أداة `Converter`، بينما يوفر `com.aspose.html.drawing.*` ثوابت حجم الصفحة وإعدادات الهوامش. بدون هذه الاستيرادات سيظهر خطأ في التجميع “cannot find symbol”. + +## الخطوة 2: تكوين **خيارات تحويل PDF** – *إنشاء PDF من ملف HTML* + +داخل طريقة `main`، عرّف مسار ملف HTML المصدر ومسار ملف PDF الوجهة. ثم أنشئ كائن `PdfConversionOptions` واضبط التخطيط ليتناسب مع المستندات بحجم الورق الشائع. + +```java +// Step 2.1: Define source HTML and target PDF locations +String htmlFilePath = "YOUR_DIRECTORY/invoice.html"; +String pdfFilePath = "YOUR_DIRECTORY/invoice.pdf"; + +// Step 2.2: Create conversion options and set page layout +PdfConversionOptions pdfOptions = new PdfConversionOptions(); +pdfOptions.setPageSize(PageSize.LETTER); // Standard US Letter (8.5" x 11") +pdfOptions.setMarginTop(20); // 20 points ≈ 0.28" +pdfOptions.setMarginBottom(20); +pdfOptions.setMarginLeft(15); +pdfOptions.setMarginRight(15); +``` + +> **شرح:** +> - `PageSize.LETTER` يضمن أن الناتج يطابق تنسيقًا قابلًا للطباعة شائعًا. +> - تُعبّر الهوامش بالنقاط (نقطة واحدة = 1/72 بوصة). عدّلها إذا كان تصميمك يتطلب تباعدًا أضيق أو أوسع. +> - هذه الإعدادات هي جوهر **كيفية تحويل HTML إلى PDF باستخدام Java** عندما تحتاج إلى تحكم دقيق في التخطيط النهائي. + +## الخطوة 3: إضافة رأس – *إنشاء PDF من ملف HTML* مع لمسة من العلامة التجارية + +غالبًا ما يحتوي PDF احترافي على رأس أو تذييل في كل صفحة. تسمح لك Aspose.HTML بحقن HTML خام لهذا الغرض. أدناه نضيف رأسًا صغيرًا ومركّزًا يقرأ “Invoice – Confidential”. + +```java +// Step 3: Add a simple header that appears on every page +pdfOptions.setHeaderHtml( + "
Invoice – Confidential
" +); +``` + +> **لماذا نستخدم HTML للرؤوس؟** لأنك تستطيع تنسيقه باستخدام CSS تمامًا مثل أي محتوى ويب آخر—خطوط، ألوان، وحتى صور. هذه المرونة تُعد فائدة كبيرة مقارنةً بالمكتبات القديمة التي تجبرك على استخدام واجهات رسم منخفضة المستوى. + +## الخطوة 4: تنفيذ التحويل – لحظة الحقيقة + +أخيرًا، استدعِ `Converter.convert` مع المسارات والخيارات التي ضبطتها. هذه السطر الواحد يقوم بكل العمل الشاق: تحليل HTML، تطبيق CSS، ترتيب الصفحات، وكتابة ملف PDF. + +```java +// Step 4: Convert the HTML to PDF using the configured options +Converter.convert(htmlFilePath, pdfFilePath, pdfOptions); +System.out.println("PDF generated successfully at: " + pdfFilePath); +``` + +> **ماذا يحدث خلف الكواليس؟** تقوم Aspose.HTML بتحليل DOM، حل الموارد الخارجية (صور، خطوط)، حساب التخطيط بناءً على حجم الصفحة الذي حددته، وتدفق النتيجة إلى تدفق PDF. إذا حدث أي خطأ—ملف مفقود، HTML غير صالح، أو نقص في الذاكرة—ترمي المكتبة استثناءً وصفيًا، نتركه يمر للأعلى لتبسيط المثال. + +### القائمة الكاملة + +بدمج كل ما سبق، إليك البرنامج الكامل الجاهز للتنفيذ: + +```java +import com.aspose.html.converters.*; +import com.aspose.html.drawing.*; + +public class ConvertHtmlToPdfWithOptions { + public static void main(String[] args) throws Exception { + // Step 1: Define source HTML and target PDF file locations + String htmlFilePath = "YOUR_DIRECTORY/invoice.html"; + String pdfFilePath = "YOUR_DIRECTORY/invoice.pdf"; + + // Step 2: Create PDF conversion options and set page layout + PdfConversionOptions pdfOptions = new PdfConversionOptions(); + pdfOptions.setPageSize(PageSize.LETTER); // Use standard Letter size + pdfOptions.setMarginTop(20); // Top margin (points) + pdfOptions.setMarginBottom(20); // Bottom margin (points) + pdfOptions.setMarginLeft(15); // Left margin (points) + pdfOptions.setMarginRight(15); // Right margin (points) + + // Step 3: Add a simple header that will appear on every page + pdfOptions.setHeaderHtml( + "
Invoice – Confidential
" + ); + + // Step 4: Perform the conversion from HTML to PDF using the configured options + Converter.convert(htmlFilePath, pdfFilePath, pdfOptions); + System.out.println("PDF generated successfully at: " + pdfFilePath); + } +} +``` + +> **الناتج المتوقع:** بعد تشغيل البرنامج، ستجد `invoice.pdf` في نفس الدليل. افتحه بأي عارض PDF وسترى مستندًا بحجم Letter، هوامش علوية/سفلية 20 نقطة، هوامش جانبية 15 نقطة، والرأس “Invoice – Confidential” مركّزًا في كل صفحة. + +## معالجة الحالات الشائعة + +### 1. ملف HTML غير موجود +إذا كان `htmlFilePath` يشير إلى ملف غير موجود، فإن `Converter.convert` يرمي استثناء `FileNotFoundException`. غلف الاستدعاء بكتلة try‑catch لتقديم رسالة ودية: + +```java +try { + Converter.convert(htmlFilePath, pdfFilePath, pdfOptions); +} catch (FileNotFoundException e) { + System.err.println("The HTML source file was not found: " + htmlFilePath); + return; +} +``` + +### 2. أحجام صفحات مخصصة +أحيانًا تحتاج إلى حجم A4 أو أبعاد مخصصة. استبدل `PageSize.LETTER` بـ `SizeF` مخصص: + +```java +pdfOptions.setPageSize(new SizeF(595, 842)); // A4 in points (210mm x 297mm) +``` + +### 3. إضافة تذييل +تمامًا كما في الرأس، يمكنك حقن HTML للتذييل: + +```java +pdfOptions.setFooterHtml( + "
Page of
" +); +``` + +تتفهم Aspose.HTML المتغيرات `pageNumber` و `totalPages` تلقائيًا. + +## ملخص سريع + +- **الهدف الأساسي:** **تحويل HTML إلى PDF** في Java مع تحكم كامل في التخطيط. +- **الخطوات الرئيسية:** إعداد المشروع، تكوين `PdfConversionOptions`، إضافة رأس/تذييل HTML، واستدعاء `Converter.convert`. +- **الأهداف الثانوية:** عرضنا كيف **ننشئ PDF من ملف HTML** وأجبنا على **كيفية تحويل HTML إلى PDF باستخدام Java** مع أمثلة عملية. +- **الخطوات التالية:** جرّب جداول منسقة بـ CSS، أدرج صورًا، أو غيّر الاتجاه باستخدام `PdfConversionOptions.setPageOrientation(PageOrientation.LANDSCAPE)` للحصول على PDF أفقي. + +## الخاتمة + +أصبح لديك الآن مثال جاهز للإنتاج يوضح بالضبط **كيفية تحويل HTML إلى PDF** باستخدام Aspose.HTML for Java. غطى الدرس كل شيء من إعداد المشروع إلى التعامل مع الهوامش والرؤوس والحالات الخاصة، مما يمنحك الثقة لدمج هذه المنطق في تطبيقات أكبر—سواء كنت تبني محرك فواتير، خدمة تقارير، أو نظام أرشفة مستندات. + +هل ترغب في التعمق أكثر؟ اطلع على المواضيع ذات الصلة مثل **إنشاء PDF من ملف HTML** باستخدام استعلامات وسائط CSS، أو استكشف **كيفية تحويل HTML إلى PDF باستخدام Java** للمعالجة الدفعة مع تعدد الخيوط. الاحتمالات لا حصر لها، ومع الأساس الذي بنيناه سيسهل عليك تعديل الكود لأي سيناريو. + +برمجة سعيدة، ولا تتردد في ترك تعليق إذا واجهت أي صعوبة! + +![convert html to pdf example](https://example.com/images/convert-html-to-pdf.png "convert html to pdf + + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك. + +- [Convert HTML to PDF Java – Configuring Environment in Aspose.HTML](/html/english/java/configuring-environment/) +- [How to Convert HTML to PDF Java - Set Page Margins with Aspose.HTML](/html/english/java/advanced-usage/css-extensions-adding-title-page-number/) +- [Convert HTML to PDF in Java – Step‑by‑Step Guide with Page Size Settings](/html/english/java/conversion-html-to-other-formats/convert-html-to-pdf-in-java-step-by-step-guide-with-page-siz/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/html/arabic/java/conversion-html-to-other-formats/html-to-pdf-tutorial-convert-html-to-pdf-in-java/_index.md b/html/arabic/java/conversion-html-to-other-formats/html-to-pdf-tutorial-convert-html-to-pdf-in-java/_index.md new file mode 100644 index 0000000000..7ced302f45 --- /dev/null +++ b/html/arabic/java/conversion-html-to-other-formats/html-to-pdf-tutorial-convert-html-to-pdf-in-java/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-19 +description: تعلم كيفية إنشاء ملف PDF من HTML باستخدام مثال Java بسيط. يوضح لك هذا + الدرس حول تحويل HTML إلى PDF كيفية تحويل ملف HTML إلى PDF باستخدام OpenHTMLtoPDF. +draft: false +keywords: +- html to pdf tutorial +- generate pdf from html +- convert html file pdf +- create pdf from html +- convert webpage to pdf +language: ar +og_description: يظهر لك دليل تحويل HTML إلى PDF كيفية إنشاء PDF من HTML باستخدام Java. + اتبع الخطوات لتحويل ملف HTML إلى PDF بسرعة. +og_title: 'دليل تحويل HTML إلى PDF: دليل التحويل بجافا' +schemas: +- author: Aspose + dateModified: '2026-06-19' + description: Learn how to generate pdf from html using a simple Java example. This + html to pdf tutorial shows you how to convert html file pdf with OpenHTMLtoPDF. + headline: 'html to pdf tutorial: Convert HTML to PDF in Java' + type: TechArticle +- description: Learn how to generate pdf from html using a simple Java example. This + html to pdf tutorial shows you how to convert html file pdf with OpenHTMLtoPDF. + name: 'html to pdf tutorial: Convert HTML to PDF in Java' + steps: + - name: '**Resource flexibility** – the method first checks if the supplied path + points to a real file; if not, it falls back to a classpath resource. That means + you can **convert webpage to pdf** later by feeding a URL string (just replace + the `withHtmlContent` call with `withUri`).' + text: '**Resource flexibility** – the method first checks if the supplied path + points to a real file; if not, it falls back to a classpath resource. That means + you can **convert webpage to pdf** later by feeding a URL string (just replace + the `withHtmlContent` call with `withUri`).' + - name: '**Automatic directory creation** – `Files.createDirectories` guarantees + the `target/` folder exists, so you won’t get a “No such file or directory” + error.' + text: '**Automatic directory creation** – `Files.createDirectories` guarantees + the `target/` folder exists, so you won’t get a “No such file or directory” + error.' + - name: '**Single‑line conversion** – `PdfRendererBuilder` handles CSS, fonts, and + page layout internally. No need to manually manage PDF pages; the library does + it for you, keeping the example short and focused on the **convert html file + pdf** concept.' + text: '**Single‑line conversion** – `PdfRendererBuilder` handles CSS, fonts, and + page layout internally. No need to manually manage PDF pages; the library does + it for you, keeping the example short and focused on the **convert html file + pdf** concept.' + type: HowTo +tags: +- Java +- PDF +- HTML conversion +title: 'دليل تحويل HTML إلى PDF: تحويل HTML إلى PDF في جافا' +url: /ar/java/conversion-html-to-other-formats/html-to-pdf-tutorial-convert-html-to-pdf-in-java/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# دليل تحويل HTML إلى PDF – تحويل صفحة HTML إلى ملف PDF باستخدام Java + +هل تساءلت يومًا كيف تحول صفحة HTML ثابتة إلى مستند PDF أنيق دون مغادرة بيئة التطوير المتكاملة؟ لست وحدك. في هذا **html to pdf tutorial** سنستعرض مثالًا كاملًا وجاهزًا للتنفيذ بلغة Java يقوم **generate pdf from html** في بضع دقائق فقط. + +سنغطي كل ما تحتاجه — إعداد المشروع، إضافة المكتبة المناسبة، كتابة كود التحويل، وحتى نصيحة سريعة لتحويل صفحة ويب حية إلى PDF. في النهاية ستتمكن من **convert html file pdf** على جهازك الخاص، وستفهم كيفية **create pdf from html** لأي مشروع مستقبلي. + +## ما ستحتاجه + +- Java 17 أو أحدث (الكود يعمل مع أي JDK حديث) +- Maven أو Gradle (سنظهر مقتطف Maven) +- ملف HTML صغير تريد تحويله إلى PDF (سننشئه مباشرةً) +- بيئة تطوير متكاملة أو محرر نصوص بسيط — الخيار لك + +هذا كل شيء. لا خوادم ثقيلة، لا SDKs مدفوعة، فقط Java صافية ومكتبة مفتوحة المصدر مجانية. + +## الخطوة 1: html to pdf tutorial – إعداد مشروع Maven + +أولًا، أنشئ مشروع Maven جديد (أو أضف إلى مشروع موجود). الاعتماد الوحيد الذي تحتاجه فعليًا هو **OpenHTMLtoPDF**، الذي يتولى تحويل HTML وCSS إلى PDF. + +```xml + + + 4.0.0 + com.example + html-to-pdf-demo + 1.0.0 + + 17 + 17 + + + + + + com.openhtmltopdf + openhtmltopdf-pdfbox + 1.0.10 + + + + com.openhtmltopdf + openhtmltopdf-svg-support + 1.0.10 + + + +``` + +**Pro tip:** إذا كنت تستخدم Gradle، يمكن إضافة نفس الاعتمادات تحت `implementation` في `build.gradle`. + +لماذا هذه الخطوة مهمة: بدون المكتبة لا يعرف JVM كيف يترجم وسوم HTML إلى أوامر رسم PDF. OpenHTMLtoPDF خفيفة الوزن، تُصان بانتظام، وتدعم CSS‑2.1، لذا يبقى تنسيقك كما هو. + +## الخطوة 2: generate pdf from html – إعداد ملف HTML تجريبي + +لننشئ ملف `input.html` صغيرًا بجوار مصدر Java الخاص بنا. هذا يحافظ على المثال مستقلًا ويظهر سير عمل **create pdf from html**. + +```html + + + + + + Sample Report + + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +يمكنك استبدال المحتوى بأي شيء — جداول، صور، حتى JavaScript (مع أن المُعالج يتجاهل السكريبتات). الجزء المهم هو أن الملف موجود على مسار الـ classpath حتى يتمكن المحول من العثور عليه. + +## الخطوة 3: convert html file pdf – كتابة أداة التحويل + +الآن قلب **html to pdf tutorial**: فئة `HtmlToPdfConverter` الصغيرة التي تقرأ HTML وتكتب PDF. الكود أدناه مثال كامل قابل للتنفيذ؛ انسخه إلى `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### لماذا يعمل هذا الكود + +1. **مرونة الموارد** – تتحقق الطريقة أولًا إذا كان المسار المقدم يشير إلى ملف حقيقي؛ إذا لم يكن كذلك، تعود إلى مورد على classpath. هذا يعني أنه يمكنك **convert webpage to pdf** لاحقًا بتمرير سلسلة URL (فقط استبدل استدعاء `withHtmlContent` بـ `withUri`). + +2. **إنشاء الدليل تلقائيًا** – `Files.createDirectories` يضمن وجود مجلد `target/`، لذا لن تواجه خطأ “No such file or directory”. + +3. **تحويل سطر واحد** – `PdfRendererBuilder` يتعامل مع CSS، الخطوط، وتخطيط الصفحة داخليًا. لا حاجة لإدارة صفحات PDF يدويًا؛ المكتبة تقوم بذلك لك، مما يجعل المثال مختصرًا ومركزًا على مفهوم **convert html file pdf**. + +## الخطوة 4: create pdf from html – تشغيل البرنامج والتحقق + +افتح طرفية في جذر المشروع ونفّذ: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +إذا تم إعداد كل شيء بشكل صحيح، سترى: + +``` +✅ PDF successfully created at target/output.pdf +``` + +افتح `target/output.pdf` بأي عارض PDF. يجب أن ترى عنوان “Monthly Sales Report” المنسق، نص الفقرة، ونفس الهوامش التي عرّفتها في كتلة ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +You can replace the content with anything—tables, images, even JavaScript (though the renderer ignores scripts). The important part is that the file lives on the classpath so the converter can locate it. + +## 步骤 3:convert html file pdf – 编写转换工具类 + +Now the heart of the **html to pdf tutorial**: a tiny `HtmlToPdfConverter` class that reads the HTML and writes a PDF. The code below is a full, runnable example; copy‑paste it into `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### 为什么这段代码有效 + +1. **Resource flexibility** – 方法首先检查提供的路径是否指向真实文件;如果不是,则回退到 classpath 资源。这意味着你可以通过传入 URL 字符串来 **convert webpage to pdf**(只需将 `withHtmlContent` 调用替换为 `withUri`)。 + +2. **Automatic directory creation** – `Files.createDirectories` 确保 `target/` 文件夹存在,避免出现 “No such file or directory” 错误。 + +3. **Single‑line conversion** – `PdfRendererBuilder` 在内部处理 CSS、字体和页面布局。无需手动管理 PDF 页面;库会为你完成,使示例简短且专注于 **convert html file pdf** 概念。 + +## 步骤 4:create pdf from html – 运行程序并验证 + +Open a terminal in the project root and execute: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +If everything is set up correctly you’ll see: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Open `target/output.pdf` with any PDF viewer. You should see the styled “Monthly Sales Report” header, the paragraph text, and the same margins you defined in the HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Můžete nahradit obsah čímkoli – tabulkami, obrázky, dokonce JavaScriptem (renderovač skripty ignoruje). Důležité je, aby soubor byl na classpath, aby jej konvertor mohl najít. + +## Krok 3: convert html file pdf – Napište konverzní utilitu + +Nyní jádro **html to pdf tutorial**: malá třída `HtmlToPdfConverter`, která načte HTML a zapíše PDF. Níže uvedený kód je kompletní, spustitelný příklad; zkopírujte jej do `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Proč tento kód funguje + +1. **Resource flexibility** – metoda nejprve zkontroluje, zda zadaná cesta ukazuje na skutečný soubor; pokud ne, přejde na zdroj v classpath. To znamená, že později můžete **convert webpage to pdf** zadáním URL řetězce (stačí nahradit volání `withHtmlContent` za `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` zajišťuje, že složka `target/` existuje, takže nedostanete chybu „No such file or directory“. + +3. **Single‑line conversion** – `PdfRendererBuilder` interně zpracovává CSS, fonty a rozvržení stránek. Není potřeba ručně spravovat PDF stránky; knihovna to udělá za vás, což udržuje příklad stručný a zaměřený na koncept **convert html file pdf**. + +## Krok 4: create pdf from html – Spusťte program a ověřte výsledek + +Otevřete terminál v kořenovém adresáři projektu a spusťte: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Pokud je vše nastaveno správně, uvidíte: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Otevřete `target/output.pdf` v libovolném PDF prohlížeči. Měli byste vidět stylizovaný nadpis „Monthly Sales Report“, text odstavce a stejné okraje, které jste definovali v HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Je kunt de inhoud vervangen door alles—tabellen, afbeeldingen, zelfs JavaScript (hoewel de renderer scripts negeert). Het belangrijke is dat het bestand op de classpath staat zodat de converter het kan vinden. + +## Stap 3: convert html file pdf – Schrijf de conversie‑utility + +Nu het hart van de **html to pdf tutorial**: een kleine `HtmlToPdfConverter`‑klasse die de HTML leest en een PDF schrijft. De onderstaande code is een volledig, uitvoerbaar voorbeeld; kopieer‑en‑plak het naar `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Waarom deze code werkt + +1. **Resource flexibility** – de methode controleert eerst of het opgegeven pad naar een echt bestand wijst; zo niet, dan valt hij terug op een classpath‑resource. Dat betekent dat je later **convert webpage to pdf** kunt doen door een URL‑string te gebruiken (vervang simpelweg de `withHtmlContent`‑aanroep door `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` zorgt ervoor dat de map `target/` bestaat, zodat je geen “No such file or directory”‑fout krijgt. + +3. **Single‑line conversion** – `PdfRendererBuilder` verwerkt CSS, lettertypen en paginalay-out intern. Geen noodzaak om PDF‑pagina's handmatig te beheren; de bibliotheek doet het voor je, waardoor het voorbeeld kort blijft en zich richt op het **convert html file pdf** concept. + +## Stap 4: create pdf from html – Voer het programma uit en controleer + +Open een terminal in de project‑root en voer uit: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Als alles correct is ingesteld zie je: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Open `target/output.pdf` met een PDF‑viewer. Je zou de gestylede “Monthly Sales Report”‑kop, de alinea‑tekst, en dezelfde marges die je in het HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +You can replace the content with anything—tables, images, even JavaScript (though the renderer ignores scripts). The important part is that the file lives on the classpath so the converter can locate it. + +## Step 3: convert html file pdf – Write the conversion utility + +Now the heart of the **html to pdf tutorial**: a tiny `HtmlToPdfConverter` class that reads the HTML and writes a PDF. The code below is a full, runnable example; copy‑paste it into `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Why this code works + +1. **Resource flexibility** – the method first checks if the supplied path points to a real file; if not, it falls back to a classpath resource. That means you can **convert webpage to pdf** later by feeding a URL string (just replace the `withHtmlContent` call with `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` guarantees the `target/` folder exists, so you won’t get a “No such file or directory” error. + +3. **Single‑line conversion** – `PdfRendererBuilder` handles CSS, fonts, and page layout internally. No need to manually manage PDF pages; the library does it for you, keeping the example short and focused on the **convert html file pdf** concept. + +## Step 4: create pdf from html – Run the program and verify + +Open a terminal in the project root and execute: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +If everything is set up correctly you’ll see: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Open `target/output.pdf` with any PDF viewer. You should see the styled “Monthly Sales Report” header, the paragraph text, and the same margins you defined in the HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Vous pouvez remplacer le contenu par n’importe quoi — tables, images, même du JavaScript (bien que le moteur ignore les scripts). L’important est que le fichier se trouve sur le classpath afin que le convertisseur puisse le localiser. + +## Étape 3 : convertir fichier html en pdf – Écrire l’utilitaire de conversion + +Voici le cœur du **tutoriel html vers pdf** : une petite classe `HtmlToPdfConverter` qui lit le HTML et écrit un PDF. Le code ci‑dessous est un exemple complet et exécutable ; copiez‑collez‑le dans `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Pourquoi ce code fonctionne + +1. **Flexibilité des ressources** – la méthode vérifie d’abord si le chemin fourni pointe vers un vrai fichier ; sinon, elle revient à une ressource du classpath. Cela signifie que vous pouvez **convertir une page web en pdf** plus tard en fournissant une chaîne d’URL (remplacez simplement l’appel `withHtmlContent` par `withUri`). + +2. **Création automatique de répertoires** – `Files.createDirectories` garantit que le dossier `target/` existe, évitant ainsi l’erreur « No such file or directory ». + +3. **Conversion en une ligne** – `PdfRendererBuilder` gère le CSS, les polices et la mise en page des pages en interne. Pas besoin de gérer manuellement les pages PDF ; la bibliothèque le fait pour vous, ce qui garde l’exemple court et centré sur le concept **convertir fichier html en pdf**. + +## Étape 4 : créer pdf à partir de html – Exécuter le programme et vérifier + +Ouvrez un terminal à la racine du projet et lancez : + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Si tout est correctement configuré, vous verrez : + +``` +✅ PDF successfully created at target/output.pdf +``` + +Ouvrez `target/output.pdf` avec n’importe quel lecteur PDF. Vous devriez voir l’en‑tête stylisé « Monthly Sales Report », le texte du paragraphe, et les mêmes marges que vous avez définies dans le bloc ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Sie können den Inhalt durch alles ersetzen – Tabellen, Bilder, sogar JavaScript (der Renderer ignoriert jedoch Skripte). Wichtig ist, dass die Datei im Klassenpfad liegt, damit der Konverter sie finden kann. + +## Schritt 3: convert html file pdf – Das Konvertierungs‑Utility schreiben + +Jetzt das Herzstück des **html to pdf tutorial**: eine kleine `HtmlToPdfConverter`‑Klasse, die das HTML liest und ein PDF schreibt. Der untenstehende Code ist ein vollständiges, ausführbares Beispiel; kopieren Sie ihn nach `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Warum dieser Code funktioniert + +1. **Ressourcen‑Flexibilität** – die Methode prüft zuerst, ob der angegebene Pfad auf eine echte Datei zeigt; falls nicht, greift sie auf eine Klassenpfad‑Ressource zurück. Das bedeutet, Sie können später **convert webpage to pdf** ausführen, indem Sie einen URL‑String übergeben (einfach den Aufruf `withHtmlContent` durch `withUri` ersetzen). + +2. **Automatisches Erstellen von Verzeichnissen** – `Files.createDirectories` stellt sicher, dass der Ordner `target/` existiert, sodass Sie keinen „No such file or directory“-Fehler erhalten. + +3. **Einzeilige Konvertierung** – `PdfRendererBuilder` verarbeitet CSS, Schriften und Seitenlayout intern. Es ist nicht nötig, PDF‑Seiten manuell zu verwalten; die Bibliothek übernimmt das für Sie und hält das Beispiel kurz und fokussiert auf das **convert html file pdf**‑Konzept. + +## Schritt 4: create pdf from html – Das Programm ausführen und überprüfen + +Öffnen Sie ein Terminal im Projekt‑Root und führen Sie aus: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Wenn alles korrekt eingerichtet ist, sehen Sie: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Öffnen Sie `target/output.pdf` mit einem beliebigen PDF‑Betrachter. Sie sollten die formatierte Überschrift „Monthly Sales Report“, den Absatztext und dieselben Ränder sehen, die Sie im HTML‑` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Μπορείτε να αντικαταστήσετε το περιεχόμενο με οτιδήποτε—πίνακες, εικόνες, ακόμη και JavaScript (αν και ο renderer αγνοεί τα scripts). Το σημαντικό είναι το αρχείο να βρίσκεται στο classpath ώστε ο μετατροπέας να το εντοπίσει. + +## Βήμα 3: convert html file pdf – Γράψτε το βοηθητικό πρόγραμμα μετατροπής + +Τώρα η καρδιά του **html to pdf tutorial**: μια μικρή κλάση `HtmlToPdfConverter` που διαβάζει το HTML και γράφει ένα PDF. Ο παρακάτω κώδικας είναι ένα πλήρες, εκτελέσιμο παράδειγμα· αντιγράψτε‑και‑επικολλήστε το στο `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Γιατί αυτός ο κώδικας λειτουργεί + +1. **Resource flexibility** – η μέθοδος πρώτα ελέγχει αν η παρεχόμενη διαδρομή δείχνει σε πραγματικό αρχείο· αν όχι, επιστρέφει σε πόρο του classpath. Αυτό σημαίνει ότι μπορείτε να **convert webpage to pdf** αργότερα παρέχοντας μια διεύθυνση URL (απλώς αντικαταστήστε την κλήση `withHtmlContent` με `withUri`). + +2. **Automatic directory creation** – η `Files.createDirectories` εγγυάται ότι ο φάκελος `target/` υπάρχει, ώστε να μην λάβετε σφάλμα “No such file or directory”. + +3. **Single‑line conversion** – η `PdfRendererBuilder` διαχειρίζεται εσωτερικά CSS, γραμματοσειρές και διάταξη σελίδας. Δεν χρειάζεται να διαχειριστείτε χειροκίνητα τις σελίδες PDF· η βιβλιοθήκη το κάνει για εσάς, κρατώντας το παράδειγμα σύντομο και εστιασμένο στην έννοια **convert html file pdf**. + +## Βήμα 4: create pdf from html – Εκτελέστε το πρόγραμμα και επαληθεύστε + +Ανοίξτε ένα τερματικό στη ρίζα του έργου και εκτελέστε: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Αν όλα έχουν ρυθμιστεί σωστά, θα δείτε: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Ανοίξτε το `target/output.pdf` με οποιονδήποτε προβολέα PDF. Θα πρέπει να δείτε την μορφοποιημένη κεφαλίδα “Monthly Sales Report”, το κείμενο παραγράφου, και τα ίδια περιθώρια που ορίσατε στο μπλοκ ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +आप सामग्री को कुछ भी से बदल सकते हैं—टेबल, चित्र, यहाँ तक कि JavaScript (हालांकि रेंडरर स्क्रिप्ट को अनदेखा करता है)। महत्वपूर्ण बात यह है कि फ़ाइल क्लासपाथ पर मौजूद हो ताकि कन्वर्टर उसे ढूँढ सके। + +## चरण 3: convert html file pdf – रूपांतरण यूटिलिटी लिखें + +अब **html to pdf tutorial** का मुख्य भाग: एक छोटा `HtmlToPdfConverter` क्लास जो HTML पढ़ता है और PDF लिखता है। नीचे दिया गया कोड एक पूर्ण, चलाने योग्य उदाहरण है; इसे `src/main/java/com/example/HtmlToPdfConverter.java` में कॉपी‑पेस्ट करें। + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### यह कोड क्यों काम करता है + +1. **Resource flexibility** – यह मेथड पहले जांचता है कि दिया गया पथ वास्तविक फ़ाइल की ओर इशारा करता है या नहीं; यदि नहीं, तो यह क्लासपाथ रिसोर्स पर वापस जाता है। इसका मतलब है कि आप बाद में एक URL स्ट्रिंग देकर **convert webpage to pdf** कर सकते हैं (सिर्फ `withHtmlContent` कॉल को `withUri` से बदलें)। + +2. **Automatic directory creation** – `Files.createDirectories` सुनिश्चित करता है कि `target/` फ़ोल्डर मौजूद है, इसलिए आपको “No such file or directory” त्रुटि नहीं मिलेगी। + +3. **Single‑line conversion** – `PdfRendererBuilder` आंतरिक रूप से CSS, फ़ॉन्ट और पेज लेआउट को संभालता है। PDF पेज को मैन्युअली प्रबंधित करने की आवश्यकता नहीं; लाइब्रेरी आपके लिए यह करती है, जिससे उदाहरण छोटा और **convert html file pdf** अवधारणा पर केंद्रित रहता है। + +## चरण 4: create pdf from html – प्रोग्राम चलाएँ और सत्यापित करें + +प्रोजेक्ट रूट में एक टर्मिनल खोलें और चलाएँ: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +यदि सब कुछ सही ढंग से सेट है तो आप देखेंगे: + +``` +✅ PDF successfully created at target/output.pdf +``` + +`target/output.pdf` को किसी भी PDF व्यूअर से खोलें। आपको स्टाइल किया हुआ “Monthly Sales Report” हेडर, पैराग्राफ टेक्स्ट, और वही मार्जिन दिखने चाहिए जो आपने HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +你可以將內容換成任何東西——表格、圖片,甚至 JavaScript(雖然渲染器會忽略腳本)。重要的是檔案必須位於 classpath 上,讓轉換器能夠找到它。 + +## 步驟 3:convert html file pdf – 撰寫轉換工具類別 + +現在進入 **HTML 轉 PDF 教學** 的核心:一個小型的 `HtmlToPdfConverter` 類別,用來讀取 HTML 並輸出 PDF。以下程式碼是一個完整、可執行的範例,請直接貼到 `src/main/java/com/example/HtmlToPdfConverter.java` 中。 + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### 為什麼這段程式碼可行 + +1. **資源彈性** – 方法會先檢查提供的路徑是否指向實體檔案;若不是,則回退至 classpath 資源。這表示你之後可以透過傳入 URL 字串來 **convert webpage to pdf**(只需將 `withHtmlContent` 呼叫換成 `withUri`)。 +2. **自動建立目錄** – `Files.createDirectories` 確保 `target/` 資料夾存在,避免出現「No such file or directory」錯誤。 +3. **單行轉換** – `PdfRendererBuilder` 內部處理 CSS、字型與頁面版面配置。無需手動管理 PDF 頁面;函式庫會替你完成,使範例保持簡潔,且聚焦於 **convert html file pdf** 的概念。 + +## 步驟 4:create pdf from html – 執行程式並驗證 + +在專案根目錄開啟終端機,執行以下指令: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +若設定正確,你會看到: + +``` +✅ PDF successfully created at target/output.pdf +``` + +使用任何 PDF 檢視器開啟 `target/output.pdf`。你應該會看到已套用樣式的「Monthly Sales Report」標題、段落文字,以及在 HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +A tartalmat bármi mással helyettesítheted – táblázatok, képek, akár JavaScript (bár a renderelő figyelmen kívül hagyja a szkripteket). A lényeg, hogy a fájl a classpath‑on legyen, hogy a konverter megtalálja. + +## 3. lépés: convert html file pdf – Konverziós segédprogram írása + +Most jön a **html to pdf tutorial** szíve: egy apró `HtmlToPdfConverter` osztály, amely beolvassa a HTML‑t és PDF‑et ír ki. Az alábbi kód egy teljes, futtatható példa; másold be a `src/main/java/com/example/HtmlToPdfConverter.java` fájlba. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Miért működik ez a kód + +1. **Resource flexibility** – a metódus először ellenőrzi, hogy a megadott útvonal valódi fájlra mutat-e; ha nem, visszaesik egy classpath erőforrásra. Ez azt jelenti, hogy később **convert webpage to pdf** is elvégezhető egy URL karakterlánc megadásával (csak cseréld le a `withHtmlContent` hívást `withUri`‑ra). + +2. **Automatic directory creation** – a `Files.createDirectories` garantálja, hogy a `target/` mappa létezik, így nem kapsz „No such file or directory” hibát. + +3. **Single‑line conversion** – a `PdfRendererBuilder` belsőleg kezeli a CSS‑t, betűtípusokat és az oldalelrendezést. Nincs szükség a PDF oldalak kézi kezelésére; a könyvtár megteszi helyetted, így a példa rövid és a **convert html file pdf** koncepcióra fókuszál. + +## 4. lépés: create pdf from html – Program futtatása és ellenőrzés + +Nyiss egy terminált a projekt gyökerében és futtasd: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Ha minden helyesen van beállítva, a következőt fogod látni: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Nyisd meg a `target/output.pdf` fájlt bármely PDF‑nézővel. Látnod kell a stílusos „Monthly Sales Report” fejlécet, a bekezdés szövegét, és ugyanazokat a margókat, amelyeket az HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Anda dapat mengganti kontennya dengan apa saja—tabel, gambar, bahkan JavaScript (meskipun perender mengabaikan skrip). Bagian pentingnya adalah file tersebut berada di classpath sehingga konverter dapat menemukannya. + +## Langkah 3: convert html file pdf – Menulis utilitas konversi + +Sekarang inti dari **html to pdf tutorial**: kelas kecil `HtmlToPdfConverter` yang membaca HTML dan menulis PDF. Kode di bawah ini adalah contoh lengkap yang dapat dijalankan; salin‑tempel ke `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Mengapa kode ini berhasil + +1. **Resource flexibility** – metode pertama memeriksa apakah jalur yang diberikan mengarah ke file nyata; jika tidak, ia beralih ke sumber daya classpath. Itu berarti Anda dapat **convert webpage to pdf** nanti dengan memberikan string URL (cukup ganti panggilan `withHtmlContent` dengan `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` memastikan folder `target/` ada, sehingga Anda tidak akan mendapatkan error “No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` menangani CSS, font, dan tata letak halaman secara internal. Tidak perlu mengelola halaman PDF secara manual; pustaka melakukannya untuk Anda, menjadikan contoh singkat dan terfokus pada konsep **convert html file pdf**. + +## Langkah 4: create pdf from html – Menjalankan program dan memverifikasi + +Buka terminal di root proyek dan jalankan: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Jika semuanya telah disiapkan dengan benar Anda akan melihat: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Buka `target/output.pdf` dengan penampil PDF apa pun. Anda seharusnya melihat header “Monthly Sales Report” yang bergaya, teks paragraf, dan margin yang sama seperti yang Anda definisikan dalam blok ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Puoi sostituire il contenuto con qualsiasi cosa—tabelle, immagini, anche JavaScript (anche se il renderer ignora gli script). La parte importante è che il file risieda nel classpath così il convertitore può individuarlo. + +## Step 3: convert html file pdf – Write the conversion utility + +Ora il cuore del **html to pdf tutorial**: una piccola classe `HtmlToPdfConverter` che legge l’HTML e scrive un PDF. Il codice qui sotto è un esempio completo e eseguibile; copialo in `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Why this code works + +1. **Resource flexibility** – il metodo controlla prima se il percorso fornito punta a un file reale; in caso contrario, ricade su una risorsa del classpath. Questo significa che potrai **convert webpage to pdf** in seguito passando una stringa URL (basta sostituire la chiamata `withHtmlContent` con `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` garantisce che la cartella `target/` esista, così non otterrai l’errore “No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` gestisce CSS, font e layout di pagina internamente. Non è necessario gestire manualmente le pagine PDF; la libreria lo fa per te, mantenendo l’esempio breve e focalizzato sul concetto **convert html file pdf**. + +## Step 4: create pdf from html – Run the program and verify + +Apri un terminale nella radice del progetto ed esegui: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Se tutto è configurato correttamente vedrai: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Apri `target/output.pdf` con qualsiasi visualizzatore PDF. Dovresti vedere l’intestazione stilizzata “Monthly Sales Report”, il testo del paragrafo, e gli stessi margini che hai definito nel blocco ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +内容はテーブルや画像、JavaScript でも構いません(ただしレンダラはスクリプトを無視します)。重要なのは、ファイルがクラスパス上にあることです。コンバータがそれを見つけられるようにします。 + +## ステップ 3: convert html file pdf – 変換ユーティリティの作成 + +これが **html to pdf tutorial** の核心です: HTML を読み込み PDF を出力する小さな `HtmlToPdfConverter` クラスです。以下のコードは完全な実行例ですので、`src/main/java/com/example/HtmlToPdfConverter.java` にコピー&ペーストしてください。 + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### このコードが機能する理由 + +1. **Resource flexibility** – メソッドはまず指定されたパスが実際のファイルかどうかを確認し、そうでなければクラスパスリソースにフォールバックします。これにより、後で URL 文字列を渡すだけで **convert webpage to pdf** が可能です(`withHtmlContent` の呼び出しを `withUri` に置き換えるだけ)。 + +2. **Automatic directory creation** – `Files.createDirectories` が `target/` フォルダの存在を保証するため、“No such file or directory” エラーが発生しません。 + +3. **Single‑line conversion** – `PdfRendererBuilder` が内部で CSS、フォント、ページレイアウトを処理します。PDF ページを手動で管理する必要はなく、ライブラリがすべて行うため、例は短くなり **convert html file pdf** の概念に集中できます。 + +## ステップ 4: create pdf from html – プログラムを実行して確認 + +プロジェクトルートでターミナルを開き、次のコマンドを実行します: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +正しく設定されていれば、次のように表示されます: + +``` +✅ PDF successfully created at target/output.pdf +``` + +`target/output.pdf` を任意の PDF ビューアで開きます。スタイルが適用された “Monthly Sales Report” ヘッダー、段落テキスト、HTML の ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +내용을 표, 이미지, 심지어 JavaScript 등으로 교체할 수 있습니다(렌더러는 스크립트를 무시합니다). 중요한 점은 파일이 클래스패스에 존재해야 변환기가 이를 찾을 수 있다는 것입니다. + +## Step 3: convert html file pdf – 변환 유틸리티 작성 + +이제 **html to pdf tutorial**의 핵심인, HTML을 읽고 PDF로 쓰는 작은 `HtmlToPdfConverter` 클래스를 살펴보겠습니다. 아래 코드는 완전한 실행 가능한 예제로, `src/main/java/com/example/HtmlToPdfConverter.java`에 복사·붙여넣기 하면 됩니다. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### 이 코드가 작동하는 이유 + +1. **Resource flexibility** – 메서드는 먼저 제공된 경로가 실제 파일인지 확인하고, 아니면 클래스패스 리소스로 대체합니다. 따라서 나중에 URL 문자열을 제공하면 **convert webpage to pdf**를 수행할 수 있습니다(`withHtmlContent` 호출을 `withUri`로 교체하면 됩니다). +2. **Automatic directory creation** – `Files.createDirectories`는 `target/` 폴더가 존재하도록 보장하므로 “No such file or directory” 오류가 발생하지 않습니다. +3. **Single‑line conversion** – `PdfRendererBuilder`는 CSS, 폰트, 페이지 레이아웃을 내부적으로 처리합니다. PDF 페이지를 수동으로 관리할 필요가 없으며, 라이브러리가 이를 수행해 예제를 간결하게 유지하고 **convert html file pdf** 개념에 집중할 수 있습니다. + +## Step 4: create pdf from html – 프로그램 실행 및 확인 + +프로젝트 루트에서 터미널을 열고 다음을 실행하세요: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +모든 설정이 올바르게 되어 있으면 다음과 같은 출력이 보일 것입니다: + +``` +✅ PDF successfully created at target/output.pdf +``` + +`target/output.pdf`를 PDF 뷰어로 열어보세요. 스타일이 적용된 “Monthly Sales Report” 헤더와 단락 텍스트, 그리고 HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Możesz zamienić zawartość na cokolwiek — tabele, obrazy, nawet JavaScript (choć renderer ignoruje skrypty). Ważne, aby plik znajdował się w classpath, aby konwerter mógł go odnaleźć. + +## Krok 3: convert html file pdf – Napisz narzędzie konwersji + +Teraz serce **html to pdf tutorial**: mała klasa `HtmlToPdfConverter`, która odczytuje HTML i zapisuje PDF. Poniższy kod to pełny, działający przykład; skopiuj i wklej go do `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Dlaczego ten kod działa + +1. **Resource flexibility** – metoda najpierw sprawdza, czy podana ścieżka wskazuje na rzeczywisty plik; jeśli nie, przechodzi do zasobu w classpath. To oznacza, że możesz później **convert webpage to pdf**, podając ciąg URL (wystarczy zamienić wywołanie `withHtmlContent` na `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` zapewnia, że folder `target/` istnieje, więc nie otrzymasz błędu „No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` obsługuje CSS, czcionki i układ strony wewnętrznie. Nie ma potrzeby ręcznego zarządzania stronami PDF; biblioteka robi to za Ciebie, utrzymując przykład krótki i skoncentrowany na koncepcji **convert html file pdf**. + +## Krok 4: create pdf from html – Uruchom program i zweryfikuj + +Otwórz terminal w katalogu głównym projektu i uruchom: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Jeśli wszystko jest poprawnie skonfigurowane, zobaczysz: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Otwórz `target/output.pdf` w dowolnym przeglądarce PDF. Powinieneś zobaczyć sformatowany nagłówek „Monthly Sales Report”, tekst akapitu oraz te same marginesy, które zdefiniowałeś w bloku ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Você pode substituir o conteúdo por qualquer coisa — tabelas, imagens, até JavaScript (embora o renderizador ignore scripts). A parte importante é que o arquivo esteja no classpath para que o conversor possa localizá‑lo. + +## Etapa 3: convert html file pdf – Escrever a utilidade de conversão + +Agora o coração do **html to pdf tutorial**: uma pequena classe `HtmlToPdfConverter` que lê o HTML e grava um PDF. O código abaixo é um exemplo completo e executável; copie‑e cole em `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Por que este código funciona + +1. **Resource flexibility** – o método primeiro verifica se o caminho fornecido aponta para um arquivo real; caso contrário, recorre a um recurso do classpath. Isso significa que você pode **convert webpage to pdf** mais tarde fornecendo uma string URL (basta substituir a chamada `withHtmlContent` por `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` garante que a pasta `target/` exista, evitando o erro “No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` lida com CSS, fontes e layout de página internamente. Não há necessidade de gerenciar manualmente as páginas PDF; a biblioteca faz isso por você, mantendo o exemplo curto e focado no conceito **convert html file pdf**. + +## Etapa 4: create pdf from html – Executar o programa e verificar + +Abra um terminal na raiz do projeto e execute: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Se tudo estiver configurado corretamente, você verá: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Abra `target/output.pdf` com qualquer visualizador de PDF. Você deverá ver o cabeçalho estilizado “Monthly Sales Report”, o texto do parágrafo e as mesmas margens que você definiu no bloco ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +You can replace the content with anything—tables, images, even JavaScript (though the renderer ignores scripts). The important part is that the file lives on the classpath so the converter can locate it. + +## Step 3: convert html file pdf – Write the conversion utility + +Now the heart of the **html to pdf tutorial**: a tiny `HtmlToPdfConverter` class that reads the HTML and writes a PDF. The code below is a full, runnable example; copy‑paste it into `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Why this code works + +1. **Resource flexibility** – the method first checks if the supplied path points to a real file; if not, it falls back to a classpath resource. That means you can **convert webpage to pdf** later by feeding a URL string (just replace the `withHtmlContent` call with `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` guarantees the `target/` folder exists, so you won’t get a “No such file or directory” error. + +3. **Single‑line conversion** – `PdfRendererBuilder` handles CSS, fonts, and page layout internally. No need to manually manage PDF pages; the library does it for you, keeping the example short and focused on the **convert html file pdf** concept. + +## Step 4: create pdf from html – Run the program and verify + +Open a terminal in the project root and execute: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +If everything is set up correctly you’ll see: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Open `target/output.pdf` with any PDF viewer. You should see the styled “Monthly Sales Report” header, the paragraph text, and the same margins you defined in the HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Puedes reemplazar el contenido con cualquier cosa—tablas, imágenes, incluso JavaScript (aunque el renderizador ignora los scripts). Lo importante es que el archivo esté en el classpath para que el conversor pueda localizarlo. + +## Paso 3: convertir archivo html a pdf – Escribe la utilidad de conversión + +Ahora el corazón del **html to pdf tutorial**: una pequeña clase `HtmlToPdfConverter` que lee el HTML y escribe un PDF. El código a continuación es un ejemplo completo y ejecutable; cópialo y pégalo en `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Por qué funciona este código + +1. **Flexibilidad de recursos** – el método primero verifica si la ruta suministrada apunta a un archivo real; si no, recurre a un recurso del classpath. Eso significa que puedes **convert webpage to pdf** más tarde proporcionando una cadena URL (simplemente reemplaza la llamada `withHtmlContent` por `withUri`). + +2. **Creación automática de directorios** – `Files.createDirectories` garantiza que la carpeta `target/` exista, por lo que no obtendrás un error de “No such file or directory”. + +3. **Conversión en una sola línea** – `PdfRendererBuilder` maneja CSS, fuentes y el diseño de página internamente. No es necesario gestionar manualmente las páginas PDF; la biblioteca lo hace por ti, manteniendo el ejemplo corto y centrado en el concepto **convert html file pdf**. + +## Paso 4: crear pdf desde html – Ejecuta el programa y verifica + +Abre una terminal en la raíz del proyecto y ejecuta: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Si todo está configurado correctamente verás: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Abre `target/output.pdf` con cualquier visor de PDF. Deberías ver el encabezado estilizado “Monthly Sales Report”, el texto del párrafo y los mismos márgenes que definiste en el bloque ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Du kan ersätta innehållet med vad som helst—tabeller, bilder, till och med JavaScript (även om renderaren ignorerar skript). Det viktiga är att filen finns på classpath så att konverteraren kan hitta den. + +## Steg 3: convert html file pdf – Skriv konverteringsverktyget + +Nu hjärtat i **html to pdf tutorial**: en liten `HtmlToPdfConverter`‑klass som läser HTML och skriver en PDF. Koden nedan är ett komplett, körbart exempel; kopiera‑klistra in den i `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Varför den här koden fungerar + +1. **Resource flexibility** – metoden kontrollerar först om den angivna sökvägen pekar på en riktig fil; om inte, faller den tillbaka på en classpath‑resurs. Det betyder att du kan **convert webpage to pdf** senare genom att mata in en URL‑sträng (byt bara `withHtmlContent`‑anropet mot `withUri`). +2. **Automatic directory creation** – `Files.createDirectories` garanterar att `target/`‑mappen finns, så du får inte ett “No such file or directory”-fel. +3. **Single‑line conversion** – `PdfRendererBuilder` hanterar CSS, typsnitt och sidlayout internt. Ingen behov av att manuellt hantera PDF‑sidor; biblioteket gör det åt dig, vilket håller exemplet kort och fokuserat på konceptet **convert html file pdf**. + +## Steg 4: create pdf from html – Kör programmet och verifiera + +Öppna en terminal i projektets rot och kör: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Om allt är korrekt konfigurerat kommer du att se: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Öppna `target/output.pdf` med någon PDF‑visare. Du bör se den stylade “Monthly Sales Report”-rubriken, paragraftexten, och samma marginaler som du definierade i HTML‑` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +คุณสามารถแทนที่เนื้อหาได้ด้วยอะไรก็ได้—ตาราง, รูปภาพ, แม้กระทั่ง JavaScript (แม้ว่าเรนเดอร์จะละเว้นสคริปต์). สิ่งสำคัญคือไฟล์ต้องอยู่บน classpath เพื่อให้ตัวแปลงสามารถหาได้ + +## Step 3: convert html file pdf – Write the conversion utility + +ตอนนี้เป็นหัวใจของ **html to pdf tutorial**: คลาส `HtmlToPdfConverter` เล็ก ๆ ที่อ่าน HTML แล้วเขียนเป็น PDF. โค้ดด้านล่างเป็นตัวอย่างเต็มที่สามารถรันได้; คัดลอกและวางลงในไฟล์ `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Why this code works + +1. **Resource flexibility** – วิธีการจะตรวจสอบก่อนว่าพาธที่ให้มาชี้ไปยังไฟล์จริงหรือไม่; หากไม่, จะย้อนกลับไปใช้ทรัพยากรบน classpath. นั่นหมายความว่าคุณสามารถ **convert webpage to pdf** ในภายหลังโดยส่งสตริง URL (เพียงเปลี่ยนการเรียก `withHtmlContent` เป็น `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` ทำให้แน่ใจว่าโฟลเดอร์ `target/` มีอยู่, ดังนั้นคุณจะไม่เจอข้อผิดพลาด “No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` จัดการ CSS, ฟอนต์, และการจัดหน้าโดยอัตโนมัติ ไม่จำเป็นต้องจัดการหน้า PDF ด้วยตนเอง; ไลบรารีทำให้คุณ, ทำให้ตัวอย่างสั้นและมุ่งเน้นที่แนวคิด **convert html file pdf**. + +## Step 4: create pdf from html – Run the program and verify + +เปิดเทอร์มินัลในโฟลเดอร์รากของโครงการและรันคำสั่ง: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +หากทุกอย่างตั้งค่าอย่างถูกต้องคุณจะเห็น: + +``` +✅ PDF successfully created at target/output.pdf +``` + +เปิด `target/output.pdf` ด้วยโปรแกรมดู PDF ใดก็ได้ คุณควรเห็นหัวข้อ “Monthly Sales Report” ที่มีสไตล์, ข้อความย่อหน้า, และขอบที่คุณกำหนดในบล็อก ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +İçeriği istediğiniz gibi değiştirebilirsiniz—tablolar, görseller, hatta JavaScript (renderlayıcı scriptleri görmez). Önemli olan dosyanın sınıf yolunda (classpath) bulunması, böylece dönüştürücü ona erişebilir. + +## Adım 3: convert html file pdf – Dönüştürme yardımcı sınıfını yazın + +Şimdi **html to pdf öğreticisinin** kalbi: HTML'i okuyup PDF yazan küçük bir `HtmlToPdfConverter` sınıfı. Aşağıdaki kod tam, çalıştırılabilir bir örnek; `src/main/java/com/example/HtmlToPdfConverter.java` içine kopyalayıp yapıştırın. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Bu kod neden çalışıyor + +1. **Kaynak esnekliği** – metod önce verilen yolun gerçek bir dosya olup olmadığını kontrol eder; değilse sınıf yolu (classpath) kaynağına geri döner. Böylece daha sonra bir URL dizesi vererek **convert webpage to pdf** yapabilirsiniz (sadece `withHtmlContent` çağrısını `withUri` ile değiştirin). + +2. **Otomatik dizin oluşturma** – `Files.createDirectories` `target/` klasörünün var olduğunu garanti eder, böylece “No such file or directory” hatası almazsınız. + +3. **Tek satırda dönüşüm** – `PdfRendererBuilder` CSS, font ve sayfa düzenini dahili olarak yönetir. PDF sayfalarını manuel olarak yönetmenize gerek yok; kütüphane bunu sizin yerinize yapar ve örnek **convert html file pdf** kavramına odaklanır. + +## Adım 4: create pdf from html – Programı çalıştırın ve doğrulayın + +Proje kök dizininde bir terminal açın ve şu komutu çalıştırın: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Her şey doğru kurulduysa şu çıktıyı görürsünüz: + +``` +✅ PDF successfully created at target/output.pdf +``` + +`target/output.pdf` dosyasını herhangi bir PDF görüntüleyicide açın. Stil verilen “Monthly Sales Report” başlığını, paragraf metnini ve HTML ` + + +

Monthly Sales Report

+

This PDF was generated directly from an HTML file using Java.

+

All you need is a few lines of code.

+ + +``` + +Bạn có thể thay thế nội dung bằng bất kỳ thứ gì—bảng, hình ảnh, thậm chí JavaScript (mặc dù bộ render sẽ bỏ qua các script). Điều quan trọng là tệp phải nằm trên classpath để bộ chuyển đổi có thể tìm thấy nó. + +## Bước 3: convert html file pdf – Viết tiện ích chuyển đổi + +Bây giờ là phần cốt lõi của **html to pdf tutorial**: một lớp `HtmlToPdfConverter` nhỏ đọc HTML và ghi ra PDF. Mã dưới đây là một ví dụ đầy đủ, có thể chạy; sao chép‑dán vào `src/main/java/com/example/HtmlToPdfConverter.java`. + +```java +package com.example; + +import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; + +/** + * Simple utility that converts an HTML file to PDF. + * It demonstrates the "convert html file pdf" use‑case. + */ +public class HtmlToPdfConverter { + + /** + * Converts the given HTML file to a PDF file. + * + * @param htmlPath path to the source HTML file (can be absolute or classpath) + * @param pdfPath destination path for the generated PDF + * @throws IOException if reading or writing fails + */ + public static void convert(String htmlPath, String pdfPath) throws IOException { + // Resolve the HTML file – support both absolute paths and classpath resources + InputStream htmlStream = Files.exists(Path.of(htmlPath)) + ? Files.newInputStream(Path.of(htmlPath)) + : HtmlToPdfConverter.class.getResourceAsStream(htmlPath); + + if (htmlStream == null) { + throw new FileNotFoundException("HTML source not found: " + htmlPath); + } + + // Ensure the output directory exists + Path pdfFile = Path.of(pdfPath); + Files.createDirectories(pdfFile.getParent()); + + try (OutputStream os = Files.newOutputStream(pdfFile); + InputStream is = htmlStream) { + + // Builder does the heavy lifting – it parses HTML + CSS and writes PDF bytes + new PdfRendererBuilder() + .withHtmlContent(new String(is.readAllBytes()), null) // base URI null = no external resources + .toStream(os) + .run(); + } + } + + // Demo entry point – feel free to run this class directly + public static void main(String[] args) { + // Step 1: Specify the input HTML file location + String htmlPath = "src/main/resources/input.html"; + + // Step 2: Specify the desired output PDF file location + String pdfPath = "target/output.pdf"; + + // Step 3: Convert the HTML document to PDF using default conversion settings + try { + convert(htmlPath, pdfPath); + System.out.println("✅ PDF successfully created at " + pdfPath); + } catch (Exception e) { + System.err.println("❌ Conversion failed: " + e.getMessage()); + e.printStackTrace(); + } + } +} +``` + +### Tại sao mã này hoạt động + +1. **Resource flexibility** – phương thức đầu tiên kiểm tra xem đường dẫn được cung cấp có trỏ tới một tệp thực tế không; nếu không, nó sẽ quay lại tài nguyên trên classpath. Điều này có nghĩa là bạn có thể **convert webpage to pdf** sau này bằng cách truyền một chuỗi URL (chỉ cần thay thế lời gọi `withHtmlContent` bằng `withUri`). + +2. **Automatic directory creation** – `Files.createDirectories` đảm bảo thư mục `target/` tồn tại, vì vậy bạn sẽ không gặp lỗi “No such file or directory”. + +3. **Single‑line conversion** – `PdfRendererBuilder` xử lý CSS, phông chữ và bố cục trang nội bộ. Không cần quản lý các trang PDF thủ công; thư viện làm việc này cho bạn, giữ cho ví dụ ngắn gọn và tập trung vào khái niệm **convert html file pdf**. + +## Bước 4: create pdf from html – Chạy chương trình và xác minh + +Mở terminal trong thư mục gốc của dự án và thực thi: + +```bash +mvn compile exec:java -Dexec.mainClass=com.example.HtmlToPdfConverter +``` + +Nếu mọi thứ được thiết lập đúng, bạn sẽ thấy: + +``` +✅ PDF successfully created at target/output.pdf +``` + +Mở `target/output.pdf` bằng bất kỳ trình xem PDF nào. Bạn sẽ thấy tiêu đề “Monthly Sales Report” được định dạng, đoạn văn bản, và các lề giống như bạn đã định nghĩa trong khối `