Flutter HTML与PDF渲染插件html_pdf_widgets的使用

Flutter HTML与PDF渲染插件html_pdf_widgets的使用

html_pdf_widgets 是一个在 Flutter 应用中将 HTML 内容转换为 PDF 文档的包。它支持多种富文本编辑器格式。通过此包,您可以轻松生成包含列表、段落、图像、引用、标题等元素的 PDF 文件。

该包是在 htmltopdfwidgets 包的基础上简化了代码、添加更多功能并修复了一些错误而构建的。

特性

  • 在 Flutter 应用中将 HTML 内容转换为 PDF 文档
  • 支持富文本编辑器格式
  • 无缝集成到您的 Flutter 项目中
  • 轻量且易于使用

安装

pubspec.yaml 文件中添加以下依赖项:

dependencies:
  html_pdf_widgets: <最新版本>

使用方法

要在您的 Flutter 项目中使用 html_pdf_widgets,请遵循以下步骤:

  1. 导入包:
import 'package:html_pdf_widgets/html_pdf_widgets.dart';
  1. 将 HTML 转换为 PDF:
void main() {
  createDocument();
}

// HTML 内容
const htmlText = '''
  <h1>AppFlowyEditor</h1>
  <h2>👋 Welcome to <strong><em><a href="appflowy.io">AppFlowy Editor</a></em></strong></h2>
  <p>AppFlowy Editor is a <strong>highly customizable</strong> <em>rich-text editor</em></p>
  <hr />
  <p><u>Here</u> is an example <del>your</del> you can give a try</p>
  <br>
  <span style="font-weight: bold;background-color: #cccccc;font-style: italic;">Span element</span>
  <span style="font-weight: medium;text-decoration: underline;">Span element two</span>
  <br>
  <span style="font-weight: 900;text-decoration: line-through;">Span element three</span>
  <a href="https://appflowy.io">This is an anchor tag!</a>
  <img src="https://images.squarespace-cdn.com/content/v1/617f6f16b877c06711e87373/c3f23723-37f4-44d7-9c5d-6e2a53064ae7/Asset+10.png?format=1500w" />
  <h3>Features!</h3>
  <ul>
    <li>[x] Customizable</li>
    <li>[x] Test-covered</li>
    <li>[ ] more to come!</li>
  </ul>
  <ol>
    <li>First item</li>
    <li>Second item</li>
  </ol>
  <li>List element</li>
  <blockquote>
    <p>This is a quote!</p>
  </blockquote>
  <code>
    Code block
  </code>
  <em>Italic one</em> <i>Italic two</i>
  <b>Bold tag</b>
  <img src="http://appflowy.io" alt="AppFlowy">
  <p>You can also use <strong><em>AppFlowy Editor</em></strong> as a component to build your own app.</p>
  <h3>Awesome features</h3>

  <p>If you have questions or feedback, please submit an issue on Github or join the community along with 1000+ builders!</p>
  <h3>Checked Boxes</h3>
  <input type="checkbox" id="option2" checked> 
  <label for="option2">Option 2</label>
  <input type="checkbox" id="option3"> 
  <label for="option3">Option 3</label>
''';

void createDocument() async {
  // 文件路径
  const filePath = 'example.pdf';
  final file = File(filePath);
  final newpdf = Document();

  // 将 HTML 转换为 PDF 元素
  final List<Widget> widgets = await HTMLToPdf().convert(
    htmlText,
  );

  // 添加页面
  newpdf.addPage(MultiPage(
      maxPages: 200,
      build: (context) {
        return widgets;
      }));

  // 写入文件
  await file.writeAsBytes(await newpdf.save());
}

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

1 回复

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


当然,以下是如何在Flutter应用中使用html_pdf_widgets插件来渲染HTML并生成PDF的示例代码。这个插件结合了HTML渲染和PDF生成的功能,使得在Flutter应用中处理这些需求变得相对简单。

首先,确保你的Flutter项目中已经添加了html_pdf_widgets依赖。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  html_pdf_widgets: ^x.y.z  # 请将x.y.z替换为最新版本号

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

接下来是一个简单的示例,展示如何使用html_pdf_widgets来渲染HTML并生成PDF:

import 'package:flutter/material.dart';
import 'package:html_pdf_widgets/html_pdf_widgets.dart';
import 'package:printing/printing.dart';

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

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

  Future<void> _generatePdf() async {
    final htmlData = """
      <h1>Hello, World!</h1>
      <p>This is a simple HTML to PDF conversion example.</p>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    """;

    final pdf = await htmlToPdf(
      data: htmlData,
      format: PdfPageFormat.a4,
      margin: EdgeInsets.all(20),
    );

    final String directory = (await getApplicationDocumentsDirectory()).path;
    final String path = '$directory/example.pdf';
    File file = File(path);
    await file.writeAsBytes(pdf.bytes);

    // Optionally, open the PDF in the device's default PDF viewer
    if (await canLaunchUrl(Uri.parse('file://$path'))) {
      launchUrl(Uri.parse('file://$path'));
    } else {
      throw 'Could not launch file';
    }
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个按钮。当点击按钮时,它会调用_generatePdf函数来生成一个包含HTML内容的PDF文件。

解释关键部分:

  1. 依赖导入

    import 'package:html_pdf_widgets/html_pdf_widgets.dart';
    import 'package:printing/printing.dart';
    
  2. HTML数据

    final htmlData = """
      <h1>Hello, World!</h1>
      <p>This is a simple HTML to PDF conversion example.</p>
      <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    """;
    
  3. 生成PDF

    final pdf = await htmlToPdf(
      data: htmlData,
      format: PdfPageFormat.a4,
      margin: EdgeInsets.all(20),
    );
    
  4. 保存并打开PDF

    final String directory = (await getApplicationDocumentsDirectory()).path;
    final String path = '$directory/example.pdf';
    File file = File(path);
    await file.writeAsBytes(pdf.bytes);
    
    if (await canLaunchUrl(Uri.parse('file://$path'))) {
      launchUrl(Uri.parse('file://$path'));
    } else {
      throw 'Could not launch file';
    }
    

请确保你的Flutter环境配置正确,并且已经安装了所有必要的依赖。运行这个示例代码后,点击按钮应该会生成一个PDF文件并在设备的默认PDF查看器中打开它。

回到顶部