Flutter HTML转PDF插件flutter_html_to_pdf_plus的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter HTML转PDF插件flutter_html_to_pdf_plus的使用

flutter_html_to_pdf_plus 是一个用于从HTML生成PDF文件的Flutter插件。本文将介绍如何使用该插件,并提供完整的示例代码。

安装插件

在你的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter_html_to_pdf_plus: ^latest_version

然后运行 flutter pub get 来安装插件。

使用方法

从原始HTML内容生成PDF

import 'package:flutter_html_to_pdf_plus/flutter_html_to_pdf_plus.dart';
import 'dart:io';

Future<void> generatePdfFromHtmlContent() async {
  var targetPath = "/your/sample/path";
  var targetFileName = "example_pdf_file";

  String htmlContent = """
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
          }
          th, td, p {
            padding: 5px;
            text-align: left;
          }
        </style>
      </head>
      <body>
        <h2>Sample PDF Generated with flutter_html_to_pdf_plus</h2>
        <table style="width:100%">
          <caption>Sample HTML Table</caption>
          <tr>
            <th>Month</th>
            <th>Savings</th>
          </tr>
          <tr>
            <td>January</td>
            <td>100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>50</td>
          </tr>
        </table>
      </body>
    </html>
  """;

  var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
    content: htmlContent,
    configuration: PdfPrinterConfiguration(
      targetPath: targetPath,
      targetFileName: targetFileName,
      margins: PdfPrinterMargins(top: 10, bottom: 10, left: 10, right: 10),
      orientation: PrintOrientation.Landscape,
      printSize: PrintSize.A4
    ),
  );

  print("Generated PDF file path: ${generatedPdfFile.path}");
}

从HTML文件生成PDF

import 'dart:io';
import 'package:flutter_html_to_pdf_plus/flutter_html_to_pdf_plus.dart';

Future<void> generatePdfFromHtmlFile() async {
  var filePath = "/sample_path/example.html";
  var targetPath = "/your/sample/path";
  var targetFileName = "example_pdf_file";

  var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlFilePath(
    htmlFilePath: filePath,
    configuration: PdfPrinterConfiguration(
      targetPath: targetPath,
      targetFileName: targetFileName,
      margins: PdfPrinterMargins(top: 10, bottom: 10, left: 10, right: 10),
      orientation: PrintOrientation.Landscape,
      printSize: PrintSize.A4
    ),
  );

  print("Generated PDF file path: ${generatedPdfFile.path}");
}

从设备图片生成PDF

如果需要在HTML中添加本地图片,可以使用以下方式:

<img src="file:///storage/example/your_sample_image.png" alt="web-img">

或使用 File 对象:

<img src="${imageFile.path}" alt="web-img">

注意:为了减小最终文件大小,建议使用 flutter_image_compress 插件压缩图片。

示例应用

以下是一个完整的示例应用程序,演示了如何生成和查看PDF文件:

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_html_to_pdf_plus/flutter_html_to_pdf_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_filex/open_filex.dart';

void main() {
  runApp(const MaterialApp(home: MyApp()));
}

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

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

class _MyAppState extends State<MyApp> {
  PrintSize? selectedPrintSize;
  PrintOrientation? selectedPrintOrientation;

  Future<String> generateExampleDocument() async {
    const htmlContent = """
    <!DOCTYPE html>
    <html>
      <head>
        <style>
        table, th, td {
          border: 1px solid black;
          border-collapse: collapse;
        }
        th, td, p {
          padding: 5px;
          text-align: left;
        }
        </style>
      </head>
      <body>
        <h2>PDF Generated with flutter_html_to_pdf_plus plugin</h2>
        
        <table style="width:100%">
          <caption>Sample HTML Table</caption>
          <tr>
            <th>Month</th>
            <th>Savings</th>
          </tr>
          <tr>
            <td>January</td>
            <td>100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>50</td>
          </tr>
        </table>
        
        <p>Image loaded from web</p>
        <img src="https://i.imgur.com/wxaJsXF.png" alt="web-img">
      </body>
    </html>
    """;

    Directory appDocDir = await getApplicationDocumentsDirectory();
    final targetPath = appDocDir.path;
    const targetFileName = "example-pdf";

    if (File("$targetPath/$targetFileName.pdf").existsSync()) {
      File("$targetPath/$targetFileName.pdf").deleteSync();
    }

    final generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
      content: htmlContent,
      configuration: PrintPdfConfiguration(
        targetDirectory: targetPath,
        targetName: targetFileName,
        printSize: selectedPrintSize ?? PrintSize.A4,
        printOrientation: selectedPrintOrientation ?? PrintOrientation.Portrait,
      ),
    );
    return generatedPdfFile.path;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Html to PDF'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            DropdownButtonFormField(
              value: selectedPrintOrientation ?? PrintOrientation.Portrait,
              items: [
                ...PrintOrientation.values.map((e) {
                  return DropdownMenuItem(
                    value: e,
                    child: Text(e.toString()),
                  );
                })
              ],
              onChanged: (value) =>
                  setState(() => selectedPrintOrientation = value),
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField(
              value: selectedPrintSize ?? PrintSize.A4,
              items: [
                ...PrintSize.values.map((e) {
                  return DropdownMenuItem(
                    value: e,
                    child: Text(e.toString()),
                  );
                })
              ],
              onChanged: (value) => setState(() => selectedPrintSize = value),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              child: const Text("Open Generated PDF Preview"),
              onPressed: () async {
                final path = await generateExampleDocument();

                await OpenFilex.open(path);
              },
            ),
          ],
        ),
      ),
    );
  }
}

通过上述步骤,你可以轻松地将HTML内容转换为PDF文件并展示在Flutter应用中。


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

1 回复

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


当然,下面是一个关于如何使用 flutter_html_to_pdf_plus 插件将 HTML 内容转换为 PDF 的代码示例。这个插件依赖于 dart_pdfflutter_html 等库来解析 HTML 并生成 PDF。

首先,确保在你的 pubspec.yaml 文件中添加必要的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_html_to_pdf_plus: ^3.0.0  # 请检查最新版本号
  flutter_html: ^3.0.0  # 可能需要其他依赖,确保版本兼容

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

接下来,是一个简单的 Flutter 应用示例,演示如何使用 flutter_html_to_pdf_plus 将 HTML 内容转换为 PDF 并保存到设备:

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html_to_pdf_plus/flutter_html_to_pdf_plus.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 htmlData = """
    <h1>Hello, World!</h1>
    <p>This is a sample HTML content to be converted to PDF.</p>
    """;

    // 获取应用文档目录路径
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    String pdfFilePath = '$appDocPath/sample.pdf';

    // 创建PDF文档
    final doc = pw.Document();

    // 使用flutter_html_to_pdf_plus将HTML转换为PDF
    final renderData = await FlutterHtmlToPdf.renderHtmlToPdf(
      data: htmlData,
      document: doc,
    );

    // 保存PDF到文件
    final File file = File(pdfFilePath);
    await file.writeAsBytes(renderData.bytes);

    // 打印文件路径(可用于调试或后续操作)
    print('PDF saved at: $pdfFilePath');

    // 可选:显示SnackBar通知用户
    // 这里需要一个ScaffoldMessenger的上下文,示例中未包含完整Scaffold结构
    // ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('PDF generated successfully')));
  }
}

注意事项:

  1. 权限处理:在真实应用中,如果需要将生成的 PDF 分享或保存到公共存储,需要处理相应的存储权限。
  2. 错误处理:示例代码中未包含错误处理逻辑,实际应用中建议添加 try-catch 块来捕获并处理可能的异常。
  3. 依赖版本:确保所有依赖库的版本相互兼容,并查看官方文档以获取最新的使用指南和API变更。

这个示例展示了基本的 HTML 到 PDF 转换流程,你可以根据实际需求进一步自定义和扩展功能。

回到顶部