Home > Software engineering >  Not able to open pdf from localstorage by using PdfDocument.openFile(path) - Flutter
Not able to open pdf from localstorage by using PdfDocument.openFile(path) - Flutter

Time:09-22

I need to a open pdf file from the local storage, here i use native_pdf_renderer: ^3.1.0 package for this purpose. As per the documentation, using the method PdfDocument.openFile('path/to/file/on/device') will fetch file from local storage. But In my case it doesn't work, show's an error PlatformException (PlatformException(PDF_RENDER, Can't open file, null, null)). The other methods PdfDocument.openAsset('assets/sample.pdf') and PdfDocument.openData(uint8Data) work's fine. How can this be made to work?

 FilePickerResult result = await FilePicker.platform.pickFiles(
   allowMultiple: false,
 );

File doc = File(result.files.single.path);

PdfPageImage thePdfThumbNail = await getSinglePageImage(doc.path);
...
Future<PdfPageImage> getSinglePageImage(String path) async {
PdfDocument newDoc = await PdfDocument.openFile(path);
final page = await newDoc.getPage(1);
final pageImage = await page.render(
  width: page.width,
  height: page.height,
  format: PdfPageFormat.JPEG,
);
return pageImage;
}

CodePudding user response:

Try this!

import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:native_pdf_renderer/native_pdf_renderer.dart';

class Test extends StatefulWidget {
_Test createState() => _Test();
}

class _Test extends State<Test> {
bool? isLoaded = false;
Uint8List? theImage;
File? file;

@override
void initState() {
 super.initState();
}

    @override
    Widget build(BuildContext context) {
      return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
        centerTitle: true,
      ),
      body: Container(child: mainWid(context)),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          getFile();
        },
        child: Icon(Icons.add),
      ),
    );
  }

  Widget mainWid(BuildContext context) {
    return isLoaded == true
        ? Center(
            child: Image(
              image: MemoryImage(theImage!),
            ),
          )
        : CircularProgressIndicator();
  }

  Future<void> getFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    file = File(result!.files.single.path.toString());
    var fileType = file!.path.split(".").last;
    if (fileType == "pdf") {
      getImage(file);
    }
  }

  Future<void> getImage(File? file) async {
    final doc = await PdfDocument.openFile(file!.path);
    final page = await doc.getPage(1);
    final pageImage = await page.render(width: page.width, height: page.height);
    isLoaded = true;
    theImage = pageImage!.bytes;
    setState(() {});
  }
}
  • Related