Introduction

The flutter_native_html_to_pdf Flutter package provides a simple bridge to the native WebView components (Android WebView and iOS WKWebView) for rendering HTML and exporting it as a PDF file. This approach yields a PDF that matches the visual fidelity of a real browser, without having to write a custom HTML‑to‑PDF engine in Dart.

When to Use This Package

Consider flutter_native_html_to_pdf when your app needs to:

  • Generate printable invoices, receipts, or reports from HTML templates.
  • Offer a “Save as PDF” feature for rich text content created with a WYSIWYG editor.
  • Maintain pixel‑perfect layout that matches a web view rendering.

It is especially useful for projects that already use HTML for content rendering and want to avoid duplicating layout logic in a pure‑Dart PDF library.

Installation

Add the package to your pubspec.yaml using the Flutter CLI:

Code
flutter pub add flutter_native_html_to_pdf

After the command completes, run flutter pub get to fetch the dependency.

Platform Setup

Both Android and iOS require minimal configuration:

  • Android: Ensure you have the WRITE_EXTERNAL_STORAGE permission if you plan to store PDFs in external storage on devices running Android 10 or lower. For Android 11+, the scoped storage model applies, and you can use the app’s documents directory without extra permissions.
  • iOS: No additional permissions are needed for writing to the app’s sandboxed documents folder. If you intend to share the PDF with other apps, consider adding the UIFileSharingEnabled key to Info.plist.
Tip: Keep all platform‑specific checks inside a dedicated service class to avoid scattering Platform.isAndroid / Platform.isIOS logic throughout your UI code.

Basic Usage Example

The following example demonstrates a minimal, production‑ready way to convert an HTML string to a PDF file and open it using the default viewer.

Dart / Flutter
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_native_html_to_pdf/flutter_native_html_to_pdf.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';

class HtmlToPdfDemo extends StatefulWidget {
  const HtmlToPdfDemo({Key? key}) : super(key: key);

  @override
  State<HtmlToPdfDemo> createState() => _HtmlToPdfDemoState();
}

class _HtmlToPdfDemoState extends State<HtmlToPdfDemo> {
  bool _isGenerating = false;
  String? _pdfPath;

  Future<void> _generatePdf() async {
    setState(() => _isGenerating = true);

    // 1️⃣ Prepare the HTML content.
    const String htmlContent = '''
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          body { font-family: Arial, sans-serif; padding: 20px; }
          h1 { color: #2E86C1; }
        </style>
      </head>
      <body>
        <h1>Invoice #12345</h1>
        <p>Date: 2026‑11‑28</p>
        <p>Thank you for your purchase!</p>
      </body>
    </html>
    ''';

    // 2️⃣ Determine a writable directory.
    final Directory appDocDir = await getApplicationDocumentsDirectory();
    final String outputFile = "${appDocDir.path}/invoice_12345.pdf";

    try {
      // 3️⃣ Call the package API.
      final File pdfFile = await FlutterNativeHtmlToPdf.convertFromHtmlContent(
        htmlContent: htmlContent,
        outputFileName: "invoice_12345",
        outputDirectory: appDocDir.path,
      );

      // 4️⃣ Verify the file exists.
      if (await pdfFile.exists()) {
        setState(() => _pdfPath = pdfFile.path);
        // Optional: open the PDF immediately.
        await OpenFile.open(pdfFile.path);
      }
    } catch (e) {
      // Handle errors gracefully.
      debugPrint('PDF generation failed: $e');
    } finally {
      setState(() => _isGenerating = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('HTML → PDF Demo')),
      body: Center(
        child: _isGenerating
            ? const CircularProgressIndicator()
            : ElevatedButton(
                onPressed: _generatePdf,
                child: const Text('Generate PDF'),
              ),
      ),
    );
  }
}

Key points in the example:

  • Use FlutterNativeHtmlToPdf.convertFromHtmlContent (the primary API documented on pub.dev).
  • Pass a fully‑qualified output directory; the plugin will create the PDF file inside it.
  • Wrap the call in a try/catch block to surface platform‑specific errors.

Alternative API: Converting from a URL

If your HTML lives on a remote server, you can use the URL‑based method:

Code
final File pdfFile = await FlutterNativeHtmlToPdf.convertFromUrl(
  url: "https://example.com/report.html",
  outputFileName: "remote_report",
  outputDirectory: appDocDir.path,
);

Make sure the URL is reachable and that the device has internet access.

Mistakes to Avoid

  • Forgetting to await the conversion. The API returns a
    Code
    Future<File>
    . Not awaiting can lead to race conditions where you try to open a file that hasn't been created yet.
  • Hard‑coding paths. Use path_provider to obtain a reliable directory across platforms.
  • Ignoring platform permissions. On Android, attempting to write outside the app sandbox without proper permissions will cause a runtime exception.
  • Relying on the default WebView settings. Complex CSS or external assets may require enabling JavaScript or adjusting the WebView's cache policy. Check the package README for any additional flags.

Testing the Integration

Because the conversion runs on native WebView components, you should test on both Android and iOS simulators/emulators. Verify that:

  • The generated PDF matches the visual layout of the source HTML.
  • Images referenced via src attributes load correctly (use absolute URLs or embed base64 data URIs).
  • Large HTML documents do not cause memory‑related crashes; consider paginating content if needed.

Best Practices for Clean Architecture

To keep your codebase maintainable, encapsulate the PDF generation logic inside a service class. Example:

Code
class PdfGeneratorService {
  final FlutterNativeHtmlToPdf _pdfPlugin = FlutterNativeHtmlToPdf();

  Future<File> generateFromHtml(String html, String fileName) async {
    final Directory dir = await getApplicationDocumentsDirectory();
    return await _pdfPlugin.convertFromHtmlContent(
      htmlContent: html,
      outputFileName: fileName,
      outputDirectory: dir.path,
    );
  }
}

Inject this service wherever you need PDF creation, and keep UI widgets independent of the third‑party API.

Conclusion

The flutter_native_html_to_pdf package offers a straightforward bridge to native rendering engines, letting you turn HTML into high‑quality PDFs with minimal code. By following the installation steps, handling platform permissions, and isolating the API behind a service layer, you can safely adopt this tool in production‑grade Flutter applications.

Frequently Asked Questions

Does flutter_native_html_to_pdf work on both Android and iOS?

Yes. The package uses Android WebView and iOS WKWebView under the hood, so it can render HTML and produce PDFs on both platforms.

Can I convert a remote HTML page directly to PDF?

Yes. Use the <code>FlutterNativeHtmlToPdf.convertFromUrl</code> method and provide the URL of the page you want to convert.

Do I need any special permissions for Android?

If you write the PDF to external storage on Android 10 or lower, you need the <code>WRITE_EXTERNAL_STORAGE</code> permission. For Android 11+ you can store the file in the app's documents directory without extra permissions.

How can I open the generated PDF after creation?

You can use a package like <code>open_file</code> to launch the default PDF viewer: <code>await OpenFile.open(pdfFile.path);</code>

Is the generated PDF identical to what the WebView displays?

The PDF is rendered by the native WebView engine, so it matches the visual output of the WebView as closely as possible. Complex CSS or JavaScript should be tested to ensure fidelity.