Flutter HTML转PDF插件htmltopdfwidgets的使用

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

Flutter HTML转PDF插件htmltopdfwidgets的使用

HTMLtoPDFWidgets 是一个Flutter包,它允许您将HTML和Markdown内容转换为PDF文档,并支持各种富文本编辑器格式。通过这个包,您可以轻松地生成包含列表、段落、图像、引用和标题等元素的PDF文件。

Features

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

Installation

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

dependencies:
  htmltopdfwidgets: ^1.0.5

Usage

导入包

import 'package:htmltopdfwidgets/htmltopdfwidgets.dart';

将HTML转换为PDF

final htmlContent = '''
  <h1>Heading Example</h1>
  <p>This is a paragraph.</p>
  <img src="image.jpg" alt="Example Image" />
  <blockquote>This is a quote.</blockquote>
  <ul>
    <li>First item</li>
    <li>Second item</li>
    <li>Third item</li>
  </ul>
''';

var filePath = 'test/example.pdf';
var file = File(filePath);
final newpdf = Document();
List<Widget> widgets = await HTMLToPdf().convert(htmlContent);
newpdf.addPage(MultiPage(
    maxPages: 200,
    build: (context) {
      return widgets;
    }));
await file.writeAsBytes(await newpdf.save());

将Markdown转换为PDF

final markDown = '''
  # Basic Markdown Demo
---
The Basic Markdown Demo shows the effect of the four Markdown extension sets
on formatting basic and extended Markdown tags.

## Overview

The Dart [markdown](https://pub.dev/packages/markdown) package parses Markdown
into HTML. The flutter_markdown package builds on this package using the
abstract syntax tree generated by the parser to make a tree of widgets instead
of HTML elements.

The markdown package supports the basic block and inline Markdown syntax
specified in the original Markdown implementation as well as a few Markdown
extensions. The markdown package uses extension sets to make extension
management easy. There are four pre-defined extension sets; none, Common Mark,
GitHub Flavored, and GitHub Web. The default extension set used by the
flutter_markdown package is GitHub Flavored.

The Basic Markdown Demo shows the effect each of the pre-defined extension sets
has on a test Markdown document with basic and extended Markdown tags. Use the
Extension Set dropdown menu to select an extension set and view the Markdown
widget's output.

## Comments

Since GitHub Flavored is the default extension set, it is the initial setting
for the formatted Markdown view in the demo.
''';

final List<Widget> markdownWidgets = await HTMLToPdf().convertMarkdown(markDown);
final markdownPdf = Document();
markdownPdf.addPage(MultiPage(
  build: (context) => markdownWidgets,
));
await File('markdown_example.pdf').writeAsBytes(await markdownPdf.save());

示例Demo

下面是一个完整的示例代码,展示了如何创建HTML和Markdown内容的PDF文档:

import 'dart:io';

import 'package:htmltopdfwidgets/htmltopdfwidgets.dart';

void main() async {
  await createDocument();
}

const htmlText = '''<h1>AppFlowyEditor</h1>
<h2>👋 <strong>Welcome to</strong> <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>
''';

const String markDown = """
# Basic Markdown Demo
---
The Basic Markdown Demo shows the effect of the four Markdown extension sets
on formatting basic and extended Markdown tags.

## Overview

The Dart [markdown](https://pub.dev/packages/markdown) package parses Markdown
into HTML. The flutter_markdown package builds on this package using the
abstract syntax tree generated by the parser to make a tree of widgets instead
of HTML elements.

The markdown package supports the basic block and inline Markdown syntax
specified in the original Markdown implementation as well as a few Markdown
extensions. The markdown package uses extension sets to make extension
management easy. There are four pre-defined extension sets; none, Common Mark,
GitHub Flavored, and GitHub Web. The default extension set used by the
flutter_markdown package is GitHub Flavored.

The Basic Markdown Demo shows the effect each of the pre-defined extension sets
has on a test Markdown document with basic and extended Markdown tags. Use the
Extension Set dropdown menu to select an extension set and view the Markdown
widget's output.

## Comments

Since GitHub Flavored is the default extension set, it is the initial setting
for the formatted Markdown view in the demo.
""";

Future<void> createDocument() async {
  const filePath = 'html_example.pdf';
  const markDownfilePath = 'markdown_example.pdf';
  final file = File(filePath);
  final markdownfile = File(markDownfilePath);
  final newpdf = Document();
  final markdownNewpdf = Document();
  final List<Widget> widgets =
      await HTMLToPdf().convert(htmlText, wrapInParagraph: true);
  final List<Widget> markdownwidgets = await HTMLToPdf().convertMarkdown(
    markDown,
  );
  newpdf.addPage(MultiPage(
      maxPages: 200,
      build: (context) {
        return widgets;
      }));
  markdownNewpdf.addPage(MultiPage(
      maxPages: 200,
      build: (context) {
        return markdownwidgets;
      }));
  await file.writeAsBytes(await newpdf.save());
  await markdownfile.writeAsBytes(await markdownNewpdf.save());
}

以上代码展示了如何使用htmltopdfwidgets插件将HTML和Markdown内容转换为PDF文档。希望这些信息对您有所帮助!


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

1 回复

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


当然,以下是如何在Flutter项目中使用htmltopdfwidgets插件将HTML内容转换为PDF的示例代码。这个插件允许你直接在Flutter应用中生成PDF文件,其中可以包含HTML内容。

首先,确保你已经在pubspec.yaml文件中添加了htmltopdfwidgets依赖:

dependencies:
  flutter:
    sdk: flutter
  htmltopdfwidgets: ^最新版本号  # 请替换为实际可用的最新版本号

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

接下来是一个完整的示例,展示如何使用htmltopdfwidgets将HTML内容转换为PDF并保存到设备存储中:

import 'package:flutter/material.dart';
import 'package:htmltopdfwidgets/htmltopdfwidgets.dart';
import 'package:path_provider/path_provider.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String? pdfFilePath;

  Future<void> generatePdf() async {
    // 准备HTML内容
    String htmlContent = """
      <html>
        <head>
          <title>示例PDF</title>
          <style>
            body {
              font-family: Arial, sans-serif;
            }
            h1 {
              color: #333;
            }
          </style>
        </head>
        <body>
          <h1>这是一个示例PDF</h1>
          <p>这是使用Flutter插件htmltopdfwidgets生成的PDF。</p>
        </body>
      </html>
    """;

    // 获取应用文档目录路径
    final directory = await getApplicationDocumentsDirectory();
    final filePath = "${directory.path}/example.pdf";

    // 调用htmltopdfwidgets生成PDF
    await HtmlToPdfWidget.generatePdfFromHtml(
      htmlContent: htmlContent,
      filePath: filePath,
    ).then((_) {
      setState(() {
        pdfFilePath = filePath;
      });
      print("PDF生成成功: $filePath");
    }).catchError((error) {
      print("生成PDF时出错: $error");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HTML转PDF示例'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              pdfFilePath == null ? '点击按钮生成PDF' : 'PDF已生成: $pdfFilePath',
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: generatePdf,
              child: Text('生成PDF'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中:

  1. 我们定义了一个Flutter应用,其中包含一个按钮,用于触发PDF生成。
  2. 当按钮被点击时,generatePdf函数被调用。
  3. generatePdf函数准备HTML内容,并获取应用文档目录的路径。
  4. 使用HtmlToPdfWidget.generatePdfFromHtml方法将HTML内容转换为PDF,并保存到指定路径。
  5. 如果PDF生成成功,pdfFilePath状态被更新,并在UI中显示路径。

请注意,htmltopdfwidgets插件可能依赖于原生代码,因此在实际项目中,你可能需要按照插件的文档进行额外的配置,如添加原生依赖和权限等。

此外,由于插件的API和依赖可能会随时间变化,请务必查阅插件的官方文档和GitHub仓库以获取最新信息。

回到顶部