Flutter网页内容转换插件webcontent_converter2的使用

Flutter网页内容转换插件webcontent_converter2的使用

webcontent_converter2

这是一个对 webcontent_converter 的分支。

该插件用于将任何网页内容或网页 URI 转换为图像位图或 PDF 文件。此插件在 Android 上使用 WebView,在 iOS 上使用 WKWebView,并在桌面端使用 Chromium。该插件已在 Android、iOS 和桌面端进行了测试。


支持

  • ✓ Android 最低 SDK 版本: 21
  • ✓ iOS 最低目标版本: 11
  • ✓ 桌面支持(Linux、Windows、macOS)
平台 Android iOS 桌面
渲染引擎 WebView WKWebView Puppeteer

方法

转换为图像

filePathToImage(String path, double duration)

  • path 是资产路径,duration 是延迟时间(单位秒)。此函数将返回 Uint8List 类型的图像数据。

示例:

var bytes = await WebcontentConverter2.filePathToImage(
  path: "assets/receipt.html", // HTML 文件路径
);
if (bytes.length > 0) _saveFile(bytes); // 保存文件

webUriToImage(String uri, double duration)

  • uri 是网页 URI(URL),duration 是延迟时间(单位秒)。此函数将返回 Uint8List 类型的图像数据。

示例:

var bytes = await WebcontentConverter2.webUriToImage(
  uri: "http://127.0.0.1:5500/example/assets/receipt.html", // 网页地址
);
if (bytes.length > 0) _saveFile(bytes); // 保存文件

contentToImage(String content, double duration)

  • content 是 HTML 或网页内容字符串,duration 是延迟时间(单位秒)。此函数将返回 Uint8List 类型的图像数据。

示例:

final content = Demo.getReceiptContent(); // 获取 HTML 内容
var bytes = await WebcontentConverter2.contentToImage(
  content: content,
);
if (bytes.length > 0) _saveFile(bytes); // 保存文件

用途:
上述三个函数可以帮助开发者获取 HTML 内容的截图并将其转换为 Uint8List 图像数据,然后推送到 ESC 打印机打印。

Receipt 截图


转换为 PDF

filePathToPdf(String path, double duration, String savedPath, PdfMargins margins, PaperFormat format)

  • path 是资产路径,duration 是延迟时间(单位秒),savedPath 是保存路径,margins 是页边距,format 是纸张格式。

示例:

var dir = await getApplicationDocumentsDirectory(); // 获取应用文档目录
var savedPath = join(dir.path, "sample.pdf"); // 设置保存路径
var result = await WebcontentConverter2.filePathToPdf(
  path: "assets/invoice.html", // HTML 文件路径
  savedPath: savedPath, // 保存路径
  format: PaperFormat.a4, // 纸张格式
  margins: PdfMargins.px(top: 35, bottom: 35, right: 35, left: 35), // 页边距
);

webUriToPdf(String uri, double duration, String savedPath, PdfMargins margins, PaperFormat format)

  • uri 是网页 URI(URL),duration 是延迟时间(单位秒),savedPath 是保存路径,margins 是页边距,format 是纸张格式。

示例:

var dir = await getApplicationDocumentsDirectory(); // 获取应用文档目录
var savedPath = join(dir.path, "sample.pdf"); // 设置保存路径
var result = await WebcontentConverter2.webUriToPdf(
  uri: "http://127.0.0.1:5500/example/assets/invoice.html", // 网页地址
  savedPath: savedPath, // 保存路径
  format: PaperFormat.a4, // 纸张格式
  margins: PdfMargins.px(top: 35, bottom: 35, right: 35, left: 35), // 页边距
);

contentToPDF(String content, double duration, String savedPath, PdfMargins margins, PaperFormat format)

  • content 是 HTML 或网页内容字符串,duration 是延迟时间(单位秒),savedPath 是保存路径,margins 是页边距,format 是纸张格式。

示例:

final content = Demo.getInvoiceContent(); // 获取 HTML 内容
var dir = await getApplicationDocumentsDirectory(); // 获取应用文档目录
var savedPath = join(dir.path, "sample.pdf"); // 设置保存路径
var result = await WebcontentConverter2.contentToPDF(
  content: content,
  savedPath: savedPath, // 保存路径
  format: PaperFormat.a4, // 纸张格式
  margins: PdfMargins.px(top: 55, bottom: 55, right: 55, left: 55), // 页边距
);

用途:
上述三个函数可以帮助开发者将 HTML 内容转换为 PDF 文件并保存到指定路径。转换成功时会返回保存路径,否则返回 null

Invoice 截图


完整示例代码

以下是一个完整的示例代码,展示如何使用 webcontent_converter2 插件来生成 PDF 文件。

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:webcontent_converter2/webcontent_converter2.dart';

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  [@override](/user/override)
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String _result = "";

  Future<void> _convertHtmlToPdf() async {
    final content = "<html><body><h1>Hello World</h1><p>This is an example of HTML content.</p></body></html>";
    var dir = await getApplicationDocumentsDirectory();
    var savedPath = join(dir.path, "example.pdf");

    try {
      var result = await WebcontentConverter2.contentToPDF(
        content: content,
        savedPath: savedPath,
        format: PaperFormat.a4,
        margins: PdfMargins.px(top: 35, bottom: 35, right: 35, left: 35),
      );

      if (result != null) {
        setState(() {
          _result = "PDF saved at: $result";
        });
      } else {
        setState(() {
          _result = "Failed to save PDF.";
        });
      }
    } catch (e) {
      setState(() {
        _result = "Error: ${e.toString()}";
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("webcontent_converter2 Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _convertHtmlToPdf,
              child: Text("Convert HTML to PDF"),
            ),
            SizedBox(height: 20),
            Text(_result),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter网页内容转换插件webcontent_converter2的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网页内容转换插件webcontent_converter2的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


webcontent_converter2 是一个 Flutter 插件,用于将网页内容转换为其他格式,比如图片或 PDF。这个插件特别适用于需要将网页内容保存为文件或进行进一步处理的场景。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  webcontent_converter2: ^latest_version

运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入插件:

import 'package:webcontent_converter/webcontent_converter.dart';

3. 使用插件

以下是一些常见的使用场景:

3.1 将网页转换为图片

你可以使用 WebcontentConverter 将网页内容转换为图片:

void convertWebToImage() async {
  try {
    // 提供网页的URL
    String url = 'https://example.com';

    // 将网页转换为图片
    String? imagePath = await WebcontentConverter.webToImage(
      url,
      imageName: 'web_image.png',
      width: 1024, // 可选: 图片宽度
      height: 768, // 可选: 图片高度
      timeout: Duration(seconds: 30), // 可选: 超时时间
    );

    if (imagePath != null) {
      print('Image saved at: $imagePath');
    } else {
      print('Failed to convert web to image');
    }
  } catch (e) {
    print('Error: $e');
  }
}

3.2 将网页转换为 PDF

你也可以将网页内容转换为 PDF:

void convertWebToPdf() async {
  try {
    // 提供网页的URL
    String url = 'https://example.com';

    // 将网页转换为PDF
    String? pdfPath = await WebcontentConverter.webToPdf(
      url,
      pdfName: 'web_page.pdf',
      width: 1024, // 可选: PDF宽度
      height: 768, // 可选: PDF高度
      timeout: Duration(seconds: 30), // 可选: 超时时间
    );

    if (pdfPath != null) {
      print('PDF saved at: $pdfPath');
    } else {
      print('Failed to convert web to PDF');
    }
  } catch (e) {
    print('Error: $e');
  }
}

4. 处理权限

在某些平台上(如 Android),你可能需要请求写入外部存储的权限。你可以在 AndroidManifest.xml 中添加以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

并在运行时请求权限:

import 'package:permission_handler/permission_handler.dart';

void requestPermissions() async {
  var status = await Permission.storage.status;
  if (!status.isGranted) {
    await Permission.storage.request();
  }
}
回到顶部