create pdfviewer with pdf.js by javascript and add in flutter
- User
create pdfviewer with pdf.js by javascript and add in flutter
- Assistant
- User
NoSuchMethodError: tried to call a non-function, such as null: 't0.onLoaded'
- Assistant
create pdfviewer with pdf.js by javascript and add in flutter
NoSuchMethodError: tried to call a non-function, such as null: 't0.onLoaded'
To create a PDF viewer using pdf.js in JavaScript and integrate it into a Flutter app, you can follow these steps:
Setup the Flutter project:
flutter create my_pdf_viewer.Create a new Flutter plugin:
flutter create --template=plugin my_pdf_viewer_plugin to create a new plugin called my_pdf_viewer_plugin.Integrate pdf.js into the plugin:
build and web folders from the extracted contents into the my_pdf_viewer_plugin directory.Modify the plugin files:
my_pdf_viewer_plugin/lib/my_pdf_viewer_plugin.dart file, replace the default content with the following code:import 'dart:async';
import 'package:flutter/services.dart';
class MyPdfViewerPlugin {
static const MethodChannel _channel =
const MethodChannel('my_pdf_viewer_plugin');
static Future<void> loadPdf(String pdfPath) async {
await _channel.invokeMethod('loadPdf', {'pdfPath': pdfPath});
}
}
my_pdf_viewer_plugin/android/src/main/kotlin/com/example/my_pdf_viewer_plugin/MyPdfViewerPlugin.kt file, replace the default content with the following code:package com.example.my_pdf_viewer_plugin
import android.content.Intent
import android.net.Uri
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MyPdfViewerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {
private lateinit var channel: MethodChannel
private var activityBinding: ActivityPluginBinding? = null
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "my_pdf_viewer_plugin")
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "loadPdf") {
val pdfPath = call.argument<String>("pdfPath")
if (pdfPath != null) {
loadPdf(pdfPath)
result.success(null)
} else {
result.error("INVALID_ARGUMENT", "PDF path cannot be null", null)
}
} else {
result.notImplemented()
}
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activityBinding = binding
}
override fun onDetachedFromActivity() {
activityBinding = null
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
private fun loadPdf(pdfPath: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(pdfPath))
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activityBinding?.activity?.startActivity(intent)
}
}
my_pdf_viewer_plugin/ios/Classes/MyPdfViewerPlugin.swift file, replace the default content with the following code:import Flutter
import UIKit
public class MyPdfViewerPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "my_pdf_viewer_plugin", binaryMessenger: registrar.messenger())
let instance = MyPdfViewerPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "loadPdf" {
if let pdfPath = call.arguments as? [String: Any]? {
loadPdf(pdfPath: (pdfPath?["pdfPath"] as? String)!)
result(nil)
} else {
result(FlutterError(code: "INVALID_ARGUMENT", message: "PDF path cannot be null", details: nil))
}
} else {
result(FlutterMethodNotImplemented)
}
}
private func loadPdf(pdfPath: String) {
if let url = URL(string: pdfPath) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
}
my_pdf_viewer_plugin/pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.6
my_pdf_viewer_plugin/android/build.gradle file:
dependencies {
implementation 'com.github.barteksc:android-pdf-viewer:3.1.0-beta.1'
}
my_pdf_viewer_plugin/ios/Classes/MyPdfViewerPlugin.swift file:
import path_provider statement at the top of the file.loadPdf method with the following:private func loadPdf(pdfPath: String) {
let tempDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let tempFilePath = (tempDir as NSString).appendingPathComponent("temp.pdf")
if FileManager.default.fileExists(atPath: tempFilePath) {
try? FileManager.default.removeItem(atPath: tempFilePath)
}
if FileManager.default.copyItem(atPath: pdfPath, toPath: tempFilePath) {
let controller = UIDocumentInteractionController(url: URL(fileURLWithPath: tempFilePath))
controller.presentPreview(animated: true)
}
}
my_pdf_viewer_plugin/ios/Classes/MyPdfViewerPlugin.swift file:
import path_provider
import PDFKit
my_pdf_viewer_plugin/ios/Classes/MyPdfViewerPlugin.swift file:
loadPdf method with the following code:private func loadPdf(pdfPath: String) {
let fileURL = URL(fileURLWithPath: pdfPath)
if let document = PDFDocument(url: fileURL) {
let viewController = PDFViewController(document: document)
if let navigationController = UIApplication.shared.delegate?.window??.rootViewController as? UINavigationController {
navigationController.pushViewController(viewController, animated: true)
}
}
}
my_pdf_viewer_plugin/lib/my_pdf_viewer_plugin.dart file, replace the default content with the following code:library my_pdf_viewer_plugin;
import 'dart:async';
import 'package:flutter/services.dart';
class MyPdfViewerPlugin {
static const MethodChannel _channel =
const MethodChannel('my_pdf_viewer_plugin');
static Future<void> loadPdf(String pdfPath) async {
await _channel.invokeMethod('loadPdf', {'pdfPath': pdfPath});
}
}
my_pdf_viewer_plugin package:example/lib/main.dart file with the following code:import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:my_pdf_viewer_plugin/my_pdf_viewer_plugin.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PDF Viewer',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _pdfPath;
@override
void initState() {
super.initState();
_loadPdf();
}
Future<void> _loadPdf() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
String pdfPath = appDocDir.path + "/sample.pdf";
if (await File(pdfPath).exists()) {
setState(() {
_pdfPath = pdfPath;
});
} else {
await File(pdfPath).writeAsBytes(<int>[]);
setState(() {
_pdfPath = pdfPath;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PDF Viewer'),
),
body: Center(
child: ElevatedButton(
child: Text('Open PDF'),
onPressed: () {
if (_pdfPath != null) {
MyPdfViewerPlugin.loadPdf(_pdfPath!);
}
},
),
),
);
}
}
flutter run. The app should now open in an emulator or connected device.Note: This solution assumes you have a sample PDF file named "sample.pdf" in the /my_pdf_viewer_plugin/example/assets directory. You can replace it with your own PDF file or modify the code to load a PDF file from a different location.
The error NoSuchMethodError: tried to call a non-function, such as null: 't0.onLoaded' indicates that there is an issue with the onLoaded function callback in your code.
To fix this issue, you need to ensure that the onLoaded function is defined and properly implemented. Here's an example of how you can modify your code to handle the onLoaded callback:
my_pdf_viewer_plugin/pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
# Add the pdf_render plugin
pdf_render: ^3.2.0
my_pdf_viewer_plugin/lib/my_pdf_viewer_plugin.dart file, replace the default content with the following code:import 'dart:async';
import 'package:flutter/services.dart';
import 'package:pdf_render/pdf_render.dart';
import 'package:pdf_render/pdf_render_widgets.dart';
class MyPdfViewerPlugin {
static const MethodChannel _channel =
const MethodChannel('my_pdf_viewer_plugin');
static Future<void> loadPdf(String pdfPath) async {
await _channel.invokeMethod('loadPdf', {'pdfPath': pdfPath});
}
}
my_pdf_viewer_plugin package:
example/lib/main.dart file with the following code:import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:my_pdf_viewer_plugin/my_pdf_viewer_plugin.dart';
import 'package:pdf_render/pdf_render.dart';
void main() async {
// Ensure that the Flutter framework initializes properly
WidgetsFlutterBinding.ensureInitialized();
// Load the PDF render library
await ui.initializePdf();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PDF Viewer',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _pdfPath;
bool _isLoading = false;
late PdfDocument _document;
late PdfPageImageProvider _pageImageProvider;
@override
void initState() {
super.initState();
_loadPdf();
}
Future<void> _loadPdf() async {
setState(() {
_isLoading = true;
});
// Get the path to the PDF file
Directory appDocDir = await getApplicationDocumentsDirectory();
String pdfPath = appDocDir.path + "/sample.pdf";
if (await rootBundle.load(pdfPath).isEmpty) {
// If the PDF file does not exist, copy the asset file to the document directory
ByteData data = await rootBundle.load('assets/sample.pdf');
await File(pdfPath).writeAsBytes(data.buffer.asUint8List());
}
setState(() {
_pdfPath = pdfPath;
_document = PdfDocument.openFile(pdfPath);
_pageImageProvider = PdfPageImageProvider(pdfDocument: _document, pageNumber: 1);
_isLoading = false;
});
}
@override
void dispose() {
_document.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return Scaffold(
appBar: AppBar(
title: Text('PDF Viewer'),
),
body: Center(
child: CircularProgressIndicator(),
),
);
} else {
return Scaffold(
appBar: AppBar(
title: Text('PDF Viewer'),
),
body: Center(
child: PdfDocumentLoader(
document: _document,
pageBuilder: (BuildContext context, PdfPage? page, int pageIndex) {
return Container(
child: page != null
? Image(
image: _pageImageProvider(pageNumber: pageIndex + 1),
)
: null,
);
},
),
),
);
}
}
}
flutter run. The app should now open in an emulator or connected device.Make sure to replace the sample.pdf file with your own PDF file or modify the code to load a PDF file from a different location.