How to convert Assets Images & Icons to PdfImage in flutter using dart_pdf - pdf

Used Library: dart_pdf After searching I found the same issue in GITHUB but unable to resolve the issue. I tried this but blurry image appears. Please help!!
ByteData data = await rootBundle.load('assets/test.jpg');
var codec = await instantiateImageCodec(data.buffer.asUint8List());
var frame = await codec.getNextFrame();
var imageBytes = await frame.image.toByteData();
PdfImage assetImage = PdfImage(pdf.document,
image: imageBytes.buffer.asUint8List(), width: 86, height: 80);
Rendered Image:

Use this instead:
final PdfImage assetImage = await pdfImageFromImageProvider(
pdf: pdf.document,
image: const AssetImage('assets/test.jpg'),
);

This function will create your pdf with image and custom data
var pdf = new pw.Document();
Future<pw.Document> createPDF() async {
var assetImage = pw.MemoryImage(
(await rootBundle.load('assets/images/delivery.png'))
.buffer
.asUint8List(),
);
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
var width = MediaQuery.of(this.context).size.width;
var height = MediaQuery.of(this.context).size.height;
return pw.Container(
margin: pw.EdgeInsets.only(top: height * 0.1),
child: pw.ListView(
children: [
// your image here
pw.Container(
height: height * 0.25, child: pw.Image(assetImage)),
// other contents
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceAround,
children: [
pw.Text("order Id:"),
pw.Text(widget.doc['orderId']),
],
),
],
),
);
}));
return pdf;
}
use this function to save
Future savePdf(pw.Document pdfnew) async {
String pdfName;
File file;
try {
var documentDirectory = await AndroidPathProvider.downloadsPath; // for android downloads folder
// var localDirectory = await getApplicationDocumentsDirectory(); // for local directory
setState(() {
pdfName = "your_pdf_name";
});
file = File("$documentDirectory/$pdfName.pdf");
await file.writeAsBytes(await pdf.save());
return file.path;
} catch (e) {
print(e);
}
}

Related

html canvas - multiple svg images which all have different fillStyle colors

For a digital artwork I'm generating a canvas element in Vue which draws from an array of multiple images.
The images can be split in two categories:
SVG (comes with a fill-color)
PNG (just needs to be drawn as a regular image)
I came up with this:
const depict = (options) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const myOptions = Object.assign({}, options);
if (myOptions.ext == "svg") {
return loadImage(myOptions.uri).then((img) => {
ctx.drawImage(img, 0, 0, 100, 100);
ctx.globalCompositeOperation = "source-in";
ctx.fillStyle = myOptions.clr;
ctx.fillRect(0, 0, 100, 100);
ctx.globalCompositeOperation = "source-over";
});
} else {
return loadImage(myOptions.uri).then((img) => {
ctx.fillStyle = myOptions.clr;
ctx.drawImage(img, 0, 0, 100, 100);
});
}
};
this.inputs.forEach(depict);
for context:
myOptions.clr = the color
myOptions.uri = the url of the image
myOptions.ext = the extension of the image
While all images are drawn correctly I can't figure out why the last fillStyle overlays the whole image. I just want all the svg's to have the fillStyle which is attached to them.
I tried multiple globalCompositeOperation in different orders. I also tried drawing the svg between ctx.save and ctx.restore. No succes… I might be missing some logic here.
So! I figured it out myself in the meantime :)
I created an async loop with a promise. Inside this I created a temporary canvas per image which I then drew to one canvas. I took inspiration from this solution: https://stackoverflow.com/a/6687218/15289586
Here is the final code:
// create the parent canvas
let parentCanv = document.createElement("canvas");
const getContext = () => parentCanv.getContext("2d");
const parentCtx = getContext();
parentCanv.classList.add("grid");
// det the wrapper from the DOM
let wrapper = document.getElementById("wrapper");
// this function loops through the array
async function drawShapes(files) {
for (const file of files) {
await depict(file);
}
// if looped > append parent canvas to to wrapper
wrapper.appendChild(parentCanv);
}
// async image loading worked best
const loadImage = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error(`load ${url} fail`));
img.src = url;
});
};
// depict the file
const depict = (options) => {
// make a promise
return new Promise((accept, reject) => {
const myOptions = Object.assign({}, options);
var childCanv = document.createElement("canvas");
const getContext = () => childCanv.getContext("2d");
const childCtx = getContext();
if (myOptions.ext == "svg") {
loadImage(myOptions.uri).then((img) => {
childCtx.drawImage(img, 0, 0, 100, parentCanv.height);
childCtx.globalCompositeOperation = "source-in";
childCtx.fillStyle = myOptions.clr;
childCtx.fillRect(0, 0, parentCanv.width, parentCanv.height);
parentCtx.drawImage(childCanv, 0, 0);
accept();
});
} else {
loadImage(myOptions.uri).then((img) => {
// ctx.fillStyle = myOptions.clr;
childCtx.drawImage(img, 0, 0, 100, parentCanv.height);
parentCtx.drawImage(childCanv, 0, 0);
accept();
});
}
});
};
drawShapes(this.inputs);

how to upload multiple multipart images through API in flutter

I am new to app development & still learning flutter, I used multiple image picker package to pick multiple images from gallery, I am wondering how can I post the list of images to to server using API? I am using MongoDB with AWS. any help is appreciated.
Future<String> uploadImage(filename) async {
var request = http.MultipartRequest('POST', Uri.parse(serverReceiverPath));
request.files.add(await http.MultipartFile.fromPath('file', filename));
var res = await request.send();
print(res.statusCode);
var bodyResponse = await res.stream.bytesToString(); // response body
print(bodyResponse);
}
Below is code to pick images from gallery using multi image picker, I am able to pick images and show them on the screen.
class PickImages extends StatefulWidget {
#override
_PickImagesState createState() => _PickImagesState();
}
class _PickImagesState extends State<PickImages> {
List<Asset> images = List<Asset>();
// String _error = 'No Error Detected';
#override
void initState() {
super.initState();
}
Widget buildGridView() {
return GridView.count(
crossAxisCount: 3,
children: List.generate(images.length, (index) {
Asset asset = images[index];
return AssetThumb(
asset: asset,
width: 300,
height: 300,
);
}),
);
}
Future<void> loadAssets() async {
List<Asset> resultList = List<Asset>();
String error = 'No Error Dectected';
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 300,
enableCamera: true,
selectedAssets: images,
cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
materialOptions: MaterialOptions(
actionBarColor: "#abcdef",
actionBarTitle: "Example App",
allViewTitle: "All Photos",
useDetailsView: false,
selectCircleStrokeColor: "#000000",
),
);
} on Exception catch (e) {
error = e.toString();
}
if (!mounted) return;
setState(() {
images = resultList;
// _error = error;
});
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: height(context)*0.35,
width: 400,
child: buildGridView()),
RaisedButton(
child: Text("Pick images"),
onPressed: loadAssets,
),
],
);
}
}

How to upload multiple images to the Rest API in Flutter using HTTP?

I want to upload multiple images into the Rest API. I tried the below code to upload a single image to the rest API. That is working fine, for multiple image selection I'm using multi_image_picker link, how can I modified below code to upload multiple images? Thank you
Future<String> uploadSingleImage(File file,String userid) async
{
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
String fileName = file.path.split("/").last;
var stream =
new http.ByteStream(DelegatingStream.typed(file.openRead()));
// get file length
var length = await file.length(); //imageFile is your image file
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer $value"
}; // ignore this headers if there is no authentication
// string to uri
var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFileSign = new http.MultipartFile('photo',
stream,
length,
filename: fileName
);
// add file to multipart
request.files.add(multipartFileSign);
//add headers
request.headers.addAll(headers);
//adding params
request.fields['id'] = userid;
// request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
your Image list
List<String> photos = ["path of image1","path of image2", "path of image3",];
List<http.MultipartFile> newList = [];
for (var img in photos!) {
if (img != "") {
var multipartFile = await http.MultipartFile.fromPath(
'Photos',
File(img).path,
filename: img.split('/').last,
);
newList.add(multipartFile);
}
}
request.files.addAll(newList);
You could pass a list of files to your method, loop over to build each MultipartFile objects and add them to your MultipartRequest
Future<String> uploadMultipleImage(List<File> files, String userid) async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;
// string to uri
var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
for (var file in files) {
String fileName = file.path.split("/").last;
var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
// get file length
var length = await file.length(); //imageFile is your image file
// multipart that takes file
var multipartFileSign = new http.MultipartFile('photo', stream, length, filename: fileName);
request.files.add(multipartFileSign);
}
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer $value"
}; // ignore this headers if there is no authentication
//add headers
request.headers.addAll(headers);
//adding params
request.fields['id'] = userid;
// request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Well you are almost close to send multiple files at a time let me post some code
Future<String> uploadSingleImage(File file,File file2,String userid) async
{
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
String fileName = file.path.split("/").last;
var stream =
new http.ByteStream(DelegatingStream.typed(file.openRead()));
// get file length
var length = await file.length(); //imageFile is your image file
Map<String, String> headers = {
"Accept": "application/json",
"Authorization": "Bearer $value"
}; // ignore this headers if there is no authentication
// string to uri
var uri = Uri.parse(serverUrl + "/api/v1/upload_parent_image");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// multipart that takes file
var multipartFileSign = new http.MultipartFile('photo',
stream,
length,
filename: fileName
);
// add file to multipart
request.files.add(multipartFileSign);
// Now Adding file 2 in request
String fileName2 = file2.path.split("/").last;
var stream2 =
new http.ByteStream(DelegatingStream.typed(file2.openRead()));
var lengthOfFile2 = await file2.length();
// multipart that takes file
var multipartFile2 = new http.MultipartFile('file2_key_here',
stream2,
lengthOfFile2,
filename: fileName2
);
// add file2 to multipart
request.files.add(multipartFile2);
//add headers
request.headers.addAll(headers);
//adding params
request.fields['id'] = userid;
// request.fields['firstName'] = 'abc';
// request.fields['lastName'] = 'efg';
// send
var response = await request.send();
print(response.statusCode);
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
I have shared my code that i used to upload mutliple image with this packages
multi_image_picker: ^4.8.0
flutter_absolute_path: ^1.0.6
flutter_image_compress:
path_provider
http
flutter compress and path provider are used to compress the size
Http request code
static Future<String> uploadMultipleImage({List<File> files}) async {
// string to uri
var uri = Uri.parse("your api url");
print("image upload URL - $uri");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
for (var file in files) {
String fileName = file.path.split("/").last;
var stream = new http.ByteStream(DelegatingStream.typed(file.openRead()));
// get file length
var length = await file.length(); //imageFile is your image file
print("File lenght - $length");
print("fileName - $fileName");
// multipart that takes file
var multipartFileSign = new http.MultipartFile('images[]', stream, length,
filename: fileName);
request.files.add(multipartFileSign);
}
Map<String, String> headers = {
"Accept": "application/json",
"Authorization":
"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMiwiZXhwIjoxNjE3NTQyNDE0LCJpc3MiOiJsb2NhbGhvc3QiLCJpYXQiOjE2MTcxODI0MTR9.dGRbINOdx_tf417fpsjdQ5CR7uGULs98FjLGm2w4kRY"
}; // ignore this headers if there is no authentication
print("headers - $headers}");
//add headers
request.headers.addAll(headers);
//adding params
request.fields['heading'] = "heading";
request.fields['description'] = "description";
request.fields['mobile'] = "mobile";
request.fields['email'] = "email";
request.fields['category'] = "1";
request.fields['location_type'] = "1";
request.fields['location'] = "location";
request.fields['lat'] = "12";
request.fields['lng'] = "123";
request.fields['price'] = "1231";
request.fields['sub_category'] = "3";
// send
var response = await request.send();
print(response.statusCode);
var res = await http.Response.fromStream(response);
if (response.statusCode == 200 || response.statusCode == 201) {
print("Item form is statuscode 200");
print(res.body);
var responseDecode = json.decode(res.body);
if (responseDecode['status'] == true) {
return res.body;
} else {
return res.body;
}
}
}
My UI screen where I call the method
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_absolute_path/flutter_absolute_path.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:lookapt_olx_app/service/ApiService.dart';
import 'package:lookapt_olx_app/utils/Utils.dart';
import 'package:lookapt_olx_app/utils/colorUtils.dart';
import 'package:lookapt_olx_app/utils/fontUtils.dart';
import 'package:lookapt_olx_app/widgets/appbar_widget.dart';
import 'package:lookapt_olx_app/widgets/commonWidget.dart';
import 'package:lookapt_olx_app/widgets/textFieldWidget.dart';
import 'package:lookapt_olx_app/widgets/textWidgets.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:rounded_loading_button/rounded_loading_button.dart';
import 'addNewPostController.dart';
import 'multiImagePicker.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
class AddNewPostScreen extends StatefulWidget {
Map<String, dynamic> parameters;
String categoryId;
AddNewPostScreen({this.parameters, this.categoryId = ""});
#override
_AddNewPostScreenState createState() => _AddNewPostScreenState();
}
class _AddNewPostScreenState extends State<AddNewPostScreen> {
#override
void initState() {
super.initState();
print("add new post");
print(widget.parameters['name']);
print(widget.categoryId.toString());
}
List<Asset> images = [];
String _error = "";
Widget buildGridView() {
if (images != null)
return GridView.count(
crossAxisCount: 3,
crossAxisSpacing: 10,
children: List.generate(images.length, (index) {
Asset asset = images[index];
return AssetThumb(
asset: asset,
width: 300,
height: 300,
);
}),
);
else
return Container(color: Colors.white);
}
Future<void> loadAssets() async {
setState(() {
images = List<Asset>();
});
List<Asset> resultList;
String error;
try {
resultList = await MultiImagePicker.pickImages(
maxImages: 3,
);
} on Exception catch (e) {
error = e.toString();
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
images = resultList;
if (error == null) _error = 'Selected images';
});
}
/*
Usage
final dir = await path_provider.getTemporaryDirectory();
final targetPath = dir.absolute.path + "/temp.jpg";
File imgFile = await testCompressAndGetFile(
File(_capturedImage.path), targetPath);
* */
Future<File> testCompressAndGetFile(File file, String targetPath) async {
print("testCompressAndGetFile");
final result = await FlutterImageCompress.compressAndGetFile(
file.absolute.path,
targetPath,
quality: 30,
minWidth: 1024,
minHeight: 1024,
// rotate: 90,
);
print(file.lengthSync());
print(result.lengthSync());
return result;
}
_uploadImageFun() async {
print("Note - _getImagePaths called");
List<File> fileImageArray = [];
images.forEach((imageAsset) async {
final filePath =
await FlutterAbsolutePath.getAbsolutePath(imageAsset.identifier);
File tempFile = File(filePath);
print(filePath);
print("filePath.length - ${filePath.length}");
print(tempFile);
print("tempFile.length() - ${tempFile.lengthSync()}");
if (tempFile.existsSync()) {
DateTime now = DateTime.now();
final dir = await path_provider.getTemporaryDirectory();
final targetPath =
dir.absolute.path + "/lookaptPostImage${now.microsecond}.jpg";
File imgFile =
await testCompressAndGetFile(File(tempFile.path), targetPath);
print("Compressed image");
print(imgFile.lengthSync());
fileImageArray.add(imgFile); //with image compress
}
if (fileImageArray.length == images.length) {
var res = await ApiService.uploadMultipleImage(files: fileImageArray);
print("image upload response");
print(res);
var resp = json.decode(res);
if (resp['status'] == true) {
SuccessToastWidget(context, message: resp['message']);
} else {
FailedToastWidget(context, message: resp['message']);
}
}
});
print("Test Prints");
print(fileImageArray.length);
return fileImageArray;
}
final RoundedLoadingButtonController _loginBtnController =
new RoundedLoadingButtonController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: CommonAppBarWidget(title: widget.parameters['name'] ?? ""),
body: _body(),
);
}
AddNEwPostController _addNEwPostController = new AddNEwPostController();
Widget _body() {
return Padding(
padding: const EdgeInsets.only(left: 20, right: 20, top: 10),
child: ListView(
children: [
InkWell(
onTap: loadAssets,
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
color: Colors.grey.shade400,
child: ListTile(
leading: Icon(
Icons.add_box_outlined,
size: 30,
color: Colors.black,
),
trailing: MyTextWidgets.textWidgetSemiBold(
str: "Pick Images", fontSize: 20),
),
),
),
),
RoundedLoadingButton(
child: MyTextWidgets.textWidgetBold(
fontSize: 16, str: "Next", color: MyColors.white.redC),
controller: _loginBtnController,
onPressed: () {
_getImagePaths();
},
width: MediaQuery.of(context).size.width,
borderRadius: 10,
color: MyColors.appGreenColor.redC,
height: 44,
),
Center(
child: _error == ""
? Container()`enter code here`
: MyTextWidgets.textWidgetLight(str: _error)),
Container(
child: buildGridView(),
height: 100,
width: MediaQuery.of(context).size.width - 100,
),
],
),
);
}
}
NOTE:
My ui code may not run in your code so only copy the required code from the Screen code.
Http request code will work fine just copy and past it
Thank for you support!
I am posting this solution with dio and image_picker dependency. And it will definitely work. I have spent 2 days for this solution.
FormData formData = new FormData.fromMap({
"name": "Max",
"location": "Paris",
"age": 21,
"image[]": [
await MultipartFile.fromFile(
_imageFile.path,
),
await MultipartFile.fromFile(
_imageFile.path,
),
],
});
print(FormData1().then((value) {
print(value);
}));
response = await dio.post(
"http://143.110.244.110/radius/frontuser/eventsubmitbutton",
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + '%');
}
},
);
print(response);

Append Existing Pdf to Jspdf

I am using the jspdf library to create a pdf and its working out great. I am now trying to append to that pdf another existing pdf. At the moment when my user clicks the download button it fires off two separate downloads. I was thinking that a work around might be creating two images and adding them to my pdf created with Jspdf. Has anyone appended an existing pdf to a pdf generated using jspdf?
$(document).ready(function () {
var doc = new jsPDF('p', 'pt', 'letter');
var imgData = 'cats.jpg'
var specialElementHandlers = {
'#content': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.addImage(imgData, 'JPEG', 0, 250, 615, 200);
doc.fromHTML($('#content').get(0), 0, 0, {
'elementHandlers': specialElementHandlers
});
doc.save('TemporaryIdCard.pdf');
});
});
I ended up hacking an answer from here.
Not thrilled about it but it works. I created images from the content in the PDF I was trying to append and then added each as a page to my doc
var doc = new jsPDF('p', 'pt', 'letter');
var imgData = 'cats.jpeg';
var imgData2 = 'dogs.jpeg';
var imgData3 = 'kittens.jpeg';
var specialElementHandlers = {
'#content': function (element, renderer) {
return true;
}
};
var pageHeight = doc.internal.pageSize.height;
var y = 800;
var x = 800;
$('#cmd').click(function () {
doc.addImage(imgData, 'JPEG', 0, 250, 615, 200);
doc.fromHTML($('#content').get(0), 0, 0, {
'elementHandlers': specialElementHandlers
});
if (y >= pageHeight) {
doc.addPage();
doc.addImage(imgData3, 'JPEG', 45, 45, 500, 550);
y = 0;
}
if (x >= pageHeight) {
doc.addPage();
doc.addImage(imgData2, 'JPEG', 50, 70, 500, 500);
x = 0;
}
doc.save('TemporaryIdCard.pdf');
});

image in image (overlay image) with gm (GraphicsMagick)

I want to put a watermark picture (logo) on my resized pictures as you can see in the code below.
Can somebody help how to put a picture in the right low corner with a opacity of 50%?
var fs = require('fs')
, gm = require('gm');
function walk(currentDirPath, callback) {
var fs = require('fs'), path = require('path');
fs.readdirSync(currentDirPath).forEach(function(name) {
var filePath = path.join(currentDirPath, name);
var stat = fs.statSync(filePath);
if (stat.isFile()) {
callback(filePath, stat);
} else if (stat.isDirectory()) {
walk(filePath, callback);
}
});
}
var inputDir = "/Users/USER/Desktop/src/"
var outputDir = "/Users/USER/Desktop/target/"
walk(inputDir, function(filePath, stat) {
// match filename like IMG_1234.JPG
var filename = filePath.match(/IMG_\d{4}.JPG/gmi).toString();
console.log(filename);
var outputfile = outputDir + filename
var readStream = fs.createReadStream(filePath);
gm(readStream, filename)
.size({bufferStream: true}, function(err, size) {
this.resize(size.width / 2, size.height / 2)
this.write(outputfile, function (err) {
if (!err) console.log('done');
});
});
});
Here is the solution:
.draw(['image Over 0,0 0,0 /Users/USER/Desktop/target/nike-global-diversity-logo.png'])
put this line of code after gm call and before the resizing.