Flutter HTML转PDF插件flutter_native_html_to_pdf的使用

Flutter Native HTML to PDF

This is a Flutter application that demonstrates the use of the flutter_native_html_to_pdf package to convert HTML content into a PDF file. The generated PDF file can then be shared using the share_plus package.

Features

  • HTML to PDF Conversion: The application converts a predefined HTML content into a PDF file using the flutter_native_html_to_pdf package.
  • PDF Sharing: The generated PDF file can be shared using the share_plus package.

How to Use

  1. Run the application: flutter run
  2. Once the application is running, you will see a button labeled “Share PDF” on the screen.
  3. Click on the “Share PDF” button to generate the PDF from the HTML content and initiate the sharing.

Dependencies

  • flutter_native_html_to_pdf
  • path_provider
  • share_plus

Note

This application is a demonstration of the flutter_native_html_to_pdf package. The HTML content used in this application is a simple static HTML page. You can replace it with your own dynamic HTML content as needed.

Example Code

Here is a complete example of how to use the flutter_native_html_to_pdf package to convert HTML content to a PDF file and share it using the share_plus package.

import 'dart:io';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_native_html_to_pdf/flutter_native_html_to_pdf.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String? generatedPdfFilePath;

  final _flutterNativeHtmlToPdfPlugin = FlutterNativeHtmlToPdf();

  @override
  void initState() {
    super.initState();
    generateExampleDocument();
  }

  Future<void> generateExampleDocument() async {
    const htmlContent = """
<!DOCTYPE html>
<html>
<head>
    <title>Sample HTML Page</title>
</head>
<body>
    <h1>Welcome to My Website!</h1>
    <p>This is a sample paragraph text.</p>
    <img src="https://picsum.photos/200/300" alt="Description of the image">
</body>
</html>
    """;

    Directory appDocDir = await getApplicationDocumentsDirectory();
    final targetPath = appDocDir.path;
    const targetFileName = "mytext";
    final generatedPdfFile =
        await _flutterNativeHtmlToPdfPlugin.convertHtmlToPdf(
      html: htmlContent,
      targetDirectory: targetPath,
      targetName: targetFileName,
    );

    generatedPdfFilePath = generatedPdfFile?.path;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text("Flutter Native Html to PDF"),
        ),
        body: Center(
          child: ElevatedButton(
            child: const Text("Share PDF"),
            onPressed: () async {
              if (generatedPdfFilePath != null) {
                await Share.shareXFiles(
                  [XFile(generatedPdfFilePath!)],
                  text: 'This is a pdf file',
                );
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('PDF not generated yet')),
                );
              }
            },
          ),
        ),
      ),
    );
  }
}

Explanation

  1. Dependencies: The project uses flutter_native_html_to_pdf, path_provider, and share_plus packages.
  2. Initialization: In the initState method, the generateExampleDocument function is called to generate the PDF file from the predefined HTML content.
  3. HTML Content: The htmlContent variable contains the HTML content that will be converted to a PDF.
  4. PDF Generation: The convertHtmlToPdf method of the FlutterNativeHtmlToPdf plugin is used to convert the HTML content to a PDF file. The generated PDF file path is stored in the generatedPdfFilePath variable.
  5. UI: The UI consists of a single button labeled “Share PDF”. When the button is pressed, the Share.shareXFiles method is called to share the generated PDF file.

You can customize the HTML content and the sharing logic as per your requirements.


更多关于Flutter HTML转PDF插件flutter_native_html_to_pdf的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter HTML转PDF插件flutter_native_html_to_pdf的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何使用Flutter插件flutter_native_html_to_pdf将HTML内容转换为PDF文件的代码示例。这个插件允许你在Flutter应用中动态生成PDF文件,非常适合需要从HTML内容生成PDF报告或文档的场景。

首先,你需要在你的pubspec.yaml文件中添加这个插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_native_html_to_pdf: ^2.0.0  # 请注意版本号,使用最新版本

然后,运行flutter pub get来安装依赖。

接下来是一个完整的示例代码,展示如何使用这个插件:

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';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter HTML to PDF Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: _generatePdf,
            child: Text('Generate PDF'),
          ),
        ),
      ),
    );
  }

  Future<void> _generatePdf() async {
    // 定义HTML内容
    String htmlContent = """
      <h1>Hello, World!</h1>
      <p>This is a sample HTML content that will be converted to PDF.</p>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    """;

    // 获取设备存储目录
    final directory = await getApplicationDocumentsDirectory();
    final filePath = "${directory.path}/sample.pdf";

    // 配置PDF生成选项
    final pdfOptions = PdfOptions(
      format: PdfPageFormat.a4,
      margin: PdfPageMargins(top: 20, bottom: 20, left: 20, right: 20),
      permissions: PdfPermissions(
        printing: true,
        modifying: true,
        copying: true,
        annotating: true,
        fillingForms: true,
        extractingContent: true,
        extractingImages: true,
      ),
    );

    // 调用插件生成PDF
    try {
      final result = await FlutterNativeHtmlToPdf.renderHtmlToPdf(
        sourceHtml: htmlContent,
        options: pdfOptions,
      );

      // 保存PDF文件到指定路径
      result.filePath = filePath;
      await result.save();

      // 打印文件路径(用于调试或显示给用户)
      print('PDF saved at: $filePath');

      // 可以在这里添加逻辑,比如打开PDF文件或显示成功消息
    } catch (e) {
      // 处理错误
      print('Error generating PDF: $e');
    }
  }
}

在这个示例中,我们:

  1. 定义了HTML内容,这里是一个简单的HTML字符串。
  2. 使用path_provider插件获取应用文档的存储目录。
  3. 配置了PDF生成的选项,比如页面格式、边距和权限等。
  4. 调用FlutterNativeHtmlToPdf.renderHtmlToPdf方法将HTML内容转换为PDF,并保存到指定路径。
  5. 打印了PDF文件的保存路径(在实际应用中,你可能希望显示一个成功消息或者打开生成的PDF文件)。

确保你已经添加了path_provider插件的依赖,因为我们需要它来访问设备的文件系统:

dependencies:
  path_provider: ^2.0.0  # 请注意版本号,使用最新版本

这个示例展示了基本的用法,你可以根据需求进一步定制HTML内容和PDF选项。

回到顶部