「flutter_pdfview」は、FlutterアプリでPDFファイルを表示するためのパッケージです。ネイティブのPDFビューアを活用し、パフォーマンスの高いPDFレンダリングを提供します。
このパッケージは Android および iOS の両方で動作します。
基本的な使い方
「flutter_pdfview」を使って、ローカルの PDF ファイルを表示する方法を説明します。
権限の設定
・android
AndroidManifest.xml
に以下を追加します。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
・iOS
ios/Runner/Info.plist
に以下を追加します。
<key>NSPhotoLibraryUsageDescription</key>
<string>PDFファイルへのアクセスが必要です。</string>
サンプルコード
以下のコードは、アプリの assets
フォルダに保存された PDF を表示する例です。
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:flutter/services.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: PDFViewerScreen(),
);
}
}
class PDFViewerScreen extends StatefulWidget {
const PDFViewerScreen({super.key});
@override
_PDFViewerScreenState createState() => _PDFViewerScreenState();
}
class _PDFViewerScreenState extends State<PDFViewerScreen> {
String? localPath;
@override
void initState() {
super.initState();
preparePDF();
}
Future<void> preparePDF() async {
final ByteData data = await rootBundle.load("assets/sample.pdf");
final Directory tempDir = await getApplicationDocumentsDirectory();
final File file = File("${tempDir.path}/sample.pdf");
await file.writeAsBytes(data.buffer.asUint8List(), flush: true);
setState(() {
localPath = file.path;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("PDF Viewer")),
body: localPath == null
? const Center(child: CircularProgressIndicator())
: PDFView(
filePath: localPath!,
enableSwipe: true,
swipeHorizontal: true,
autoSpacing: true,
pageFling: true,
onRender: (pages) => debugPrint("PDF loaded with $pages pages"),
onError: (error) => debugPrint(error.toString()),
onPageError: (page, error) =>
debugPrint("Error on page $page: $error"),
),
);
}
}
解説
rootBundle.load("assets/sample.pdf")
を使用して、assets
内の PDF を読み込みます。path_provider
を使い、一時ディレクトリへ PDF を保存。PDFView
を使って PDF を表示。enableSwipe: true
→ スワイプでページ移動を有効化swipeHorizontal: true
→ 水平方向にスワイプ可能autoSpacing: true
→ ページ間の間隔を自動調整onRender
,onError
,onPageError
で状態を取得
応用: ネットワークから PDF を取得
以下のように、URL からダウンロードした PDF を表示することもできます。
import 'package:http/http.dart' as http;
Future<void> fetchPDF() async {
final response = await http.get(Uri.parse("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"));
final Directory tempDir = await getApplicationDocumentsDirectory();
final File file = File("${tempDir.path}/downloaded.pdf");
await file.writeAsBytes(response.bodyBytes, flush: true);
setState(() {
localPath = file.path;
});
}
このように「flutter_pdfview」は、簡単に PDF を表示できる便利なパッケージです。
ぜひ一度使ってみてください!