Flutter网页内容转换插件webcontent_converter的使用
Flutter网页内容转换插件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 WebcontentConverter.filePathToImage(path: "assets/receipt.html");
if (bytes.length > 0) _saveFile(bytes);
webUriToImage(String uri, double duration)
uri
是网页的URI(URL)。duration
是延迟时间。- 此函数将返回
Uint8List
类型的图像。
示例:
var bytes = await WebcontentConverter.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();
var bytes = await WebcontentConverter.contentToImage(content: content);
if (bytes.length > 0) _saveFile(bytes);
目的:上述三个函数可以帮助开发者获取HTML内容的屏幕截图作为 Uint8List
图像,并将其推送到ESC打印机。
转换为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 WebcontentConverter.filePathToPdf(
path: "assets/invoice.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 WebcontentConverter.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();
var dir = await getApplicationDocumentsDirectory();
var savedPath = join(dir.path, "sample.pdf");
var result = await WebcontentConverter.contentToPDF(
content: content,
savedPath: savedPath,
format: PaperFormat.a4,
margins: PdfMargins.px(top: 55, bottom: 55, right: 55, left: 55),
);
目的:上述三个函数可以帮助开发者获取HTML内容的PDF文件。成功保存后,它将返回一个保存路径;否则返回null。
桌面支持
flutter pub run webcontent_converter:install_desktop download
此命令会根据当前操作系统下载相应版本的Chrome,并保存到 assets/.local-chromium/
目录下的zip文件中。
flutter pub run webcontent_converter:install_desktop extract
此命令会根据当前操作系统解压Chrome zip文件,并保存到 assets/.local-chromium/
目录下。
在Flutter应用中添加以下代码,可以将Chromium zip文件从资源目录打包到生产构建中,以便桌面部署。
var executablePath = await ChromeDesktopDirectoryHelper.saveChromeFromAssetToApp();
WebViewHelper.customBrowserPath = [executablePath];
await WebcontentConverter.ensureInitialized(executablePath: executablePath);
示例代码
以下是完整的示例代码,展示了如何使用该插件。
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:webcontent_converter/webcontent_converter.dart';
import 'package:window_manager/window_manager.dart';
import 'route.dart';
void main() async {
/// 确保小部件在其他配置之前构建
WidgetsFlutterBinding.ensureInitialized();
if (WebViewHelper.isDesktop) {
await windowManager.ensureInitialized();
/// 确保浏览器初始化
var executablePath = await ChromeDesktopDirectoryHelper.saveChromeFromAssetToApp();
WebViewHelper.customBrowserPath = [executablePath];
print("executablePath $executablePath");
await WebcontentConverter.ensureInitialized(executablePath: executablePath);
}
runApp(MyApp());
}
class MyApp extends StatefulWidget {
[@override](/user/override)
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with WindowListener {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
title: "webcontent converter",
initialRoute: "/",
routes: routes,
onGenerateRoute: onGenerateRoute,
);
}
[@override](/user/override)
void initState() {
if (WebViewHelper.isDesktop) {
windowManager.addListener(this);
}
super.initState();
}
[@override](/user/override)
void onWindowClose() {
log("onWindowClose");
/// 自动关闭浏览器
if (WebViewHelper.isDesktop && windowBrower != null) {
WebcontentConverter.deinitWebcontentConverter();
}
super.onWindowClose();
}
[@override](/user/override)
void dispose() {
if (WebViewHelper.isDesktop) {
windowManager.removeListener(this);
}
super.dispose();
}
}
更多关于Flutter网页内容转换插件webcontent_converter的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网页内容转换插件webcontent_converter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用 webcontent_converter
插件将 Flutter 中的网页内容转换的示例代码。请注意,webcontent_converter
并不是 Flutter 官方或广泛认可的插件,因此这里假设它是一个虚构的插件,用于说明如何集成和使用类似的插件。
假设 webcontent_converter
插件提供了以下功能:
- 加载网页内容。
- 将网页内容转换为特定格式(例如,纯文本、PDF、HTML等)。
以下是一个示例代码,展示了如何在 Flutter 应用中使用这个插件:
首先,确保在 pubspec.yaml
文件中添加该插件依赖项(假设插件名为 webcontent_converter
):
dependencies:
flutter:
sdk: flutter
webcontent_converter: ^1.0.0 # 假设版本号为1.0.0
然后,运行 flutter pub get
以获取依赖项。
接下来,在你的 Dart 文件中使用该插件:
import 'package:flutter/material.dart';
import 'package:webcontent_converter/webcontent_converter.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String convertedContent = '';
bool isLoading = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Web Content Converter Example'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async {
setState(() {
isLoading = true;
});
// 假设插件提供了一个loadAndConvert方法
String result = await WebContentConverter.loadAndConvert(
url: 'https://example.com',
format: ConversionFormat.plainText, // 假设这是一个枚举,指定转换格式
);
setState(() {
convertedContent = result;
isLoading = false;
});
},
child: Text('Convert Web Content'),
),
if (isLoading) CircularProgressIndicator(),
if (!isLoading && convertedContent.isNotEmpty)
Text(
'Converted Content:\n$convertedContent',
style: TextStyle(fontSize: 16),
),
],
),
),
),
);
}
}
在这个示例中,我们创建了一个简单的 Flutter 应用,其中包含一个按钮,用于加载并转换指定网页的内容。假设 WebContentConverter
类提供了一个静态方法 loadAndConvert
,它接受一个 URL 和一个转换格式作为参数,并返回转换后的内容。
注意:
ConversionFormat
是一个假设的枚举,用于指定转换格式。实际插件可能使用不同的方式指定格式。WebContentConverter.loadAndConvert
方法是假设的,实际插件可能有不同的方法签名和功能。
由于 webcontent_converter
插件不是实际存在的,你需要根据你实际使用的插件文档进行相应的调整。通常,插件的 README 文件会提供详细的安装和使用指南,包括方法签名和示例代码。