How can I parse the contents of a PDF file in dart? - flutter

Is there a way I can parse the contents of PDF files into widgets or something more understandable or perhaps into something that can be modified and again converted to PDF format?

You can use pdf library to achieve this task
import 'dart:io';
import 'package:pdf/pdf.dart' as pw;
Import like this and then use following method to extract text from pdf
String loadPdf({required String pdfPath}) {
String text = "";
// Load the PDF file
var file = File(pdfPath);
var bytes = file.readAsBytesSync();
// Decode the PDF file
var pdf = pw.PdfDocument.fromBytes(bytes);
// Extract the text from the PDF
for (var page in pdf.pages) {
var pageText = page.getText();
text += pageText;
}
return text;
}

Related

Convert base64 to pdf in flutter and open(without saving the file itself) in a modal window

I have a problem, I can't figure out how to convert. I have an entity (for a block). In the entity, I have a variable where I store a pdf file in base64 format. I want to convert a string (from base 64) into a PDF and display this PDF in a modal window. If someone has done this, I will be grateful for help.
My goal is to convert base 64, which is in pdfBase, into a file, in order to display this pdf file in the widget
I just want to say the file (but it is not necessary to save it).
My entity
import 'dart:convert';
import 'dart:typed_data';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'warranty_pdf_entity.freezed.dart';
#freezed
class WarrantyPdfEntity with _$WarrantyPdfEntity {
const WarrantyPdfEntity._();
const factory WarrantyPdfEntity({
#Default('') String? pdfBase,
final dynamic filePdf,
}) = _WarrantyPdfEntity;
PdfImage copyWithSelected() {
var pdfDataBytes = base64.decode(pdfgarranty!);
var img = decodeImage(pdfDataBytes);
PdfImage image = PdfImage(
pdf,
image: img!.data.buffer.asUint8List(),
width: img.width,
height: img.height);
return image;
}
}
I think this question is a dublicate. Here is the answer about how to convert base64 to pdf in flutter: https://stackoverflow.com/a/66997078/15776812

Get text content from an epub file flutter

I am trying to extract text content from an epub file but unable to do so. I have tried converting it to bytes and then read it but it's not returning a proper text. I can't find any library that helps me do so.
I only need the text file from the epub file so that I can read it with text to speech.
I did it using the epubx package
Here is the complete code
File _epubFile = File(file.path);
final contents = await _epubFile.readAsBytes();
EpubBookRef epub = await EpubReader.openBook(contents.toList());
var cont = await EpubReader.readTextContentFiles(epub.Content!.Html!);
List<String> htmlList = [];
for (var value in cont.values) {
htmlList.add(value.Content!);
}
var doc = parse(htmlList.join());
final String parsedString = parse(doc.body!.text).documentElement!.text;
return parsedString;

Dart: How to Encode Decode animated webp files?

I am trying to decode animated webp image file and encode it's frames to animated webp image file in Dart (cli)
Dart Code:
import 'dart:io';
import 'package:image/image.dart';
void main() {
final image = 'asset/test.webp';
File bytes = File(image);
List<int> list = bytes.readAsBytesSync();
var anim = decodeWebPAnimation(list)!;
var obj = WebPEncoder();
for (var frame in anim) {
obj.addFrame(frame, duration: 1);
}
var finished = obj.finish();
print(finished); // [] empty, no frames get added
// final encodedAnim = obj.encodeAnimation();
File('asset/output.webp').writeAsBytesSync(finished!,
flush: true); // pass something like encodeWebp(input)
}
pubspec.yaml
dependencies:
image: ^3.1.3
input file: https://raw.githubusercontent.com/WhatsApp/stickers/main/Android/app/src/main/assets/2/07_OK.webp
Output:
There is zero frame after calling finish(), so the output image file is invalid. i.e. file size: 0 byte
Ref of Dart APIs:
WebpEncoder:
https://pub.dev/documentation/image/latest/image/WebPEncoder-class.html
DecodeWebpAnimation: https://pub.dev/documentation/image/latest/image/decodeWebPAnimation.html
What went wrong? How to fix this?
Thank You!

How to save and download text file in Flutter web application

I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.
void getData() {
List<int> bytes = utf8.encode('this is the text file');
print(bytes); // Need to download this with txt file.
}
Can anyone help me to achieve this
This method is based on manipulations with an HTML document.
Some additional packages should be imported:
import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart
Code snippet:
final text = 'this is the text file';
// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
..href = url
..style.display = 'none'
..download = 'some_name.txt';
html.document.body.children.add(anchor);
// download
anchor.click();
// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);
Here is DartPad demo.
Got another way to do it, via popular JS library called FileSaver
First, update your ProjectFolder/web/index.html file to include the library and define the webSaveAs function like so:
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js">
</script>
<script>
function webSaveAs(blob, name) {
saveAs(blob, name);
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
...
Then you can call this function from Dart code like so:
import 'dart:js' as js;
import 'dart:html' as html;
...
js.context.callMethod("webSaveAs", [html.Blob([bytes]), "test.txt"])
If you are looking to simply save a text file, this method is more straight forward than having to deal with all those conversions:
import 'dart:convert' show utf8;
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' show AnchorElement;
void saveTextFile(String text, String filename) {
AnchorElement()
..href = '${Uri.dataFromString(text, mimeType: 'text/plain', encoding: utf8)}'
..download = filename
..style.display = 'none'
..click();
}
You can change the mimeType and encoding as you see fit. For instance, I had to generate CSV files in a recent project, so I used mimeType: 'text/csv'.
This solution uses FileSaver.js library and it should open the "saveAs" dialog.
I hope it works as intended:
import 'dart:js' as js;
import 'dart:html' as html;
...
final text = 'this is the text file';
final bytes = utf8.encode(text);
final script = html.document.createElement('script') as html.ScriptElement;
script.src = "http://cdn.jsdelivr.net/g/filesaver.js";
html.document.body.nodes.add(script);
// calls the "saveAs" method from the FileSaver.js libray
js.context.callMethod("saveAs", [
html.Blob([bytes]),
"testText.txt", //File Name (optional) defaults to "download"
"text/plain;charset=utf-8" //File Type (optional)
]);
// cleanup
html.document.body.nodes.remove(script);
I stumbled upon this and hardly found anything but this worked for me as of the latest flutter version 2.5.0.
you have to add this script in the body of your web/index.html file
<script src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>
and then just use this method to download any type of file
import 'dart:html' as html;
import 'dart:js' as js;
void save(Object bytes, String fileName) {
js.context.callMethod("saveAs", <Object>[
html.Blob(<Object>[bytes]),
fileName
]);
}
e.g I wanted to download a JSON response from the server so I called it like this.
save(json.encode(response.data), 'file.json');
With this method you can almost download any type of file, I did use this method to download images and JSON files and it is pretty straightforward.

How to convert a PDF file to an image with Flutter?

How can I convert a PDF file into an image with Flutter?
I want to print the image to an ESC/POS printer using esc_pos_printer. This package won't accept PDFImage, it needs to be a Flutter Image.
I see plenty of PHP plugins that do this but nothing for Flutter.
edit: There is an answer to another question here which shows some code to decode an image from "pdf64" but I can't figure out exactly what "pdf64" is.
I created a PDF from html using flutter_html_to_pdflike this:
Directory appDocDir = await getApplicationDocumentsDirectory();
var targetPath = appDocDir.path;
var generatedPdfFile = await FlutterHtmlToPdf.convertFromHtmlContent(
htmlContent, targetPath, targetFileName);
generatedPdfFilePath = generatedPdfFile.path;
Now I need to know how to create a Flutter Image from that PDF or the bytecode to send raw to the printer.
You can use https://pub.dev/packages/printing:
await for (var page in Printing.raster(document)) {
final image = page.asImage();
...
}
This plugin can also convert your Html to Pdf with this:
final pdf = await Printing.convertHtml(
format: PdfPageFormat.a4,
html: '<html><body><p>Hello!</p></body></html>',
));