'Image to pdf convertion in flutter

I am currently working on a photo scanner app in flutter and searching for a way to convert images to pdf. It would be great if anyone helps me



Solution 1:[1]

You can embed an image in pdf using below code.

Package : pdf: ^3.8.0

configure above package in flutter app.
then,

final pdf = Document();

** make global variable which is given below.

Uint8List? logobytes;

PdfImage? logoImage;


 Future fetch() async {
  //set your image path
    ByteData _bytes = await rootBundle.load('assets/profile.png');

    logobytes = _bytes.buffer.asUint8List();

    try {
      logoImage = PdfImage.file(
        pdf.document,
        bytes: logobytes!,
      );
    } catch (e) {
      print("catch-- $e");
      logobytes = null;
      logoImage = null;
    }
  }

then, use it.

 Widget logo(Uint8List? logobytes, PdfImage? _logoImage){

    return Container(

      child: logobytes != null

          ? Image(MemoryImage(logobytes)):

      Container(child: Text('Null')),

      decoration:const BoxDecoration(

          color: PdfColors.white,

          //border: BoxBorder(width: 0.5)

      ),

      height: 120,

      padding:const  EdgeInsets.all(10),

    );
 
  }`

*** make sure use ***
 pdf.addPage(MultiPage(
      build: (context) => [
        PdfHelper().logo(logobytes,logoImage),
 
      ],
    ));
    return PdfApi.saveDocument(name: '${data.fullNamePD}.pdf', pdf: pdf);
  }

Solution 2:[2]

Use pdf package:

dependencies:
  pdf: ^1.9.0

Load an image from a file:

final pdf = pw.Document();
final image = PdfImage.file(
  pdf.document,
  bytes: File('test.webp').readAsBytesSync(),
);

pdf.addPage(pw.Page(
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Image(image),
      ); // Center
    })); 

and then create the pdf:

final file = File("example.pdf");
await file.writeAsBytes(pdf.save());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 K Scandrett
Solution 2 Payam Asefi