Take multiple images from the gallery and make a pdf - java

I am trying to get multiple images from the gallery and make them a PDF here is the code. In the code, I can take multiple images from the user and also make them PDF. But the PDF contains only one image even though I selected multiple images it only shows one image in pdf. I have attached the code below.
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
bitmaps = new ArrayList < > ();
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
try {
Uri uri = clipData.getItemAt(i).getUri();
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmaps.add(bitmap);
pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), bitmaps.size())
.create();
for (int k = 0; k <= i; k++) {
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#FFFFFF"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
}
bitmap.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IndexOutOfBoundsException ex) {
ex.printStackTrace();
}
}
File root = new File(Environment.getExternalStorageDirectory(), "PDF Folder");
if (!root.exists()) {
root.mkdir();
}
File file = new File(root, "image" + ".pdf");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException io) {
io.printStackTrace();
} catch (NullPointerException n) {
n.printStackTrace();
}
}
}

Related

In Android how can I take multiple images through ImageReader class

I am trying to take multiple images but the ImageAvailabeListener function is not moving forward. I guess it is waiting for next image. I tried aquireNextImage() but it is also not working.
I'm taking images while MediaProjection.
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
FileOutputStream fos = null;
bitmap = null;
try {
image = mImageReader.acquireLatestImage();
if (image != null) {
Log.d("servicecheck", "not null image" + image);
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[counter].getBuffer();
int pixelStride = planes[counter].getPixelStride();
int rowStride = planes[counter].getRowStride();
counter++;
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
// fix the extra width from Image
Bitmap croppedBitmap;
try {
croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, mWidth, mHeight);
} catch (OutOfMemoryError e) {
croppedBitmap = bitmap;
}
if (croppedBitmap != bitmap) {
bitmap.recycle();
}
// write bitmap to a file
storeDirectory = new File(mStoreDir);
storeDirectory.mkdir();
fos = new FileOutputStream(storeDirectory.getAbsolutePath() + "/myscreen_" + Calendar.getInstance().getTime() + ".png");
croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//IMAGES_PRODUCED++;
fos.flush();
fos.close();
stopProjection();
stopSelf();
scanFile(getApplicationContext(), Uri.fromFile(storeDirectory));
} else {
Log.d("servicecheck", "null image" + image);
}
} catch (Exception e) {
if (bitmap != null) {
bitmap.recycle();
}
e.printStackTrace();
}
}
}
//In the below function I have created set maxImages to 5(more than 1)
#SuppressLint("WrongConstant")
private void createVirtualDisplay() {
mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 20);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight,
mDensity, getVirtualDisplayFlags(), mImageReader.getSurface(), null, null);
mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), null);
}

How to print document in Black and white using Monochrome option Mac OS?

I am unable to print pdf with MONOCHROME option on MAC, even
monochrome option is selected but still on MAC its printing in
COLOR but on windows its working fine for both options MONOCHROME and COLOR.
Plus, On MAC settings are disable even proper printer is connected.
but the same code running on windows its working fine in every
scenario.
I am using macOS High Sierra version 10.13.6
public boolean printFile(String fileUrl) {
PrintService[] printServicesAll = PrintServiceLookup.lookupPrintServices(null, null);
PrintService[] printServicesFiltered;
PrintRequestAttributeSet attrib = new HashPrintRequestAttributeSet();
Rectangle screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
String OS = System.getProperty("os.name").toLowerCase();
attrib.add(new Copies(1));
attrib.add(new sun.print.DialogOnTop());
attrib.add(Chromaticity.MONOCHROME);
attrib.add(DialogTypeSelection.NATIVE);
PrintService selectedPrintService = null;
if (OS.contains("win")) {
if (printServicesAll.length > 0) {
printServicesFiltered = removeLogicalPrinters(printServicesAll);
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesFiltered, printServicesFiltered[0], null, attrib);
}
} else if (OS.contains("mac")) {
if (printServicesAll.length > 0) {
selectedPrintService = ServiceUI.printDialog(null, screen.width / 3, screen.height / 3, printServicesAll, printServicesAll[0], null, attrib);
}
}
if (attrib.get(Destination.class) != null) {
JOptionPane.showMessageDialog(null, "Print to file option not allowed!");
return false;
} else {
if (selectedPrintService != null)
System.out.println("selected printer: " + selectedPrintService.getName());
else
return false;
try {
DocPrintJob job = selectedPrintService.createPrintJob();
job.addPrintJobListener(new PrintJobAdapter() {
public void printDataTransferCompleted(PrintJobEvent event) {
System.out.println("data transfer complete");
}
public void printJobNoMoreEvents(PrintJobEvent event) {
System.out.println("received no more events");
}
});
print(selectedPrintService, fileUrl, attrib);
/*File file = new File(filePath);
Desktop.getDesktop().print(file);*/
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Main Print File Method
private boolean print(PrintService printService, String fileUrl, PrintRequestAttributeSet attributes)
throws PrintException {
try {
PDDocument pdf = null;
String fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
if (fileType.equalsIgnoreCase("bmp") || fileType.equalsIgnoreCase("gif") || fileType.equalsIgnoreCase("jpg") || fileType.equalsIgnoreCase("png")) {
try {
InputStream in = new URL(fileUrl).openStream();
PDDocument document = new PDDocument();
BufferedImage bImg = ImageIO.read(in);
float width = bImg.getWidth();
float height = bImg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDImageXObject img = LosslessFactory.createFromImage(document, bImg);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();
pdf = document;
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
} catch (Exception e) {
e.printStackTrace();
}
} else if (fileType.equalsIgnoreCase("txt")) {
JEditorPane jEditorPane = new JEditorPane(fileUrl);
jEditorPane.print(null, null, false, printService, null, false);
} else if (fileType.equalsIgnoreCase("pdf")) {
pdf = PDDocument.load(new URL(fileUrl).openStream());
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printService);
job.setPageable(new PDFPageable(pdf));
job.print(attributes);
pdf.close();
}
} catch (Exception e) {
throw new PrintException("Printer exception", e);
}
return true;
}

How to split Html String Based on Html tag

I have String with Html format. My Html can contains any tags like image , video , ...
I can now handle image and text like this correctly :
I have a textView in my xml:
TextView textView = new TextView(DetailActivity.this);
textView.setText(Html.fromHtml(content, new Html.ImageGetter() {
#Override
public Drawable getDrawable(String source) {
try {
URI uri = new URI(source);
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
filename = tempFile.getName();
} catch (Exception e) {
}
Drawable drawable = null;
ContextWrapper cw1 = new ContextWrapper(DetailActivity.this);
File directory1 = cw1.getDir("multiImage", Context.MODE_PRIVATE);
final File myImageFile1 = new File(directory1, filename);
File f = new File(myImageFile1.getAbsolutePath());
Log.i("multiImage", filename);
final ImageView imageView = new ImageView(DetailActivity.this);
if (f.exists()) {
drawable = Drawable.createFromPath(myImageFile1.getAbsolutePath());
//drawable.setBounds(0, 0, drawable.getIntrinsicHeight(), drawable.getIntrinsicWidth());
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} else {
Picasso.with(DetailActivity.this)
.load(source)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File outFile = new File(myImageFile1.getAbsolutePath());
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError() {
}
});
URL sourceURL;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
sourceURL = new URL(source);
URLConnection urlConnection = sourceURL.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream =
new BufferedInputStream(inputStream);
Bitmap bm = BitmapFactory.decodeStream(bufferedInputStream);
// convert Bitmap to Drawable
drawable = new BitmapDrawable(getResources(), bm);
int imgH = drawable.getIntrinsicHeight();
int imgW = drawable.getIntrinsicWidth();
int padding = 20;
int realWidth = ScreenW - (2 * padding);
int realHeight = imgH * realWidth / imgW;
drawable.setBounds(padding, 0, realWidth, realHeight);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return drawable;
}
}, new UlTagHandler()));
But I can not show video using above code.
I want to split my string --> from the first until the video tag and then video tag at the end of video tag and the rest of string .

Android render pdf to bitmap with itext library

I am trying to convert a pdf stored in my assets folder into bitmap using PdfViewer.jar.
This is my code:
public static Bitmap renderToBitmap(InputStream inStream) {
Bitmap bitmap = null;
try {
byte[] bArray = IOUtils.toByteArray(inStream);
ByteBuffer buf = ByteBuffer.wrap(bArray);
PDFPage mPdfPage = new PDFFile(buf).getPage(0, true);
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
bitmap = mPdfPage.getImage((int) (width), (int) (height), null);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bitmap;
}
This code is doing what I need. But the resulting bitmap quality is very poor.
How can I increase the quality of bitmap created ?

jpegs are corrupted when resampled with java imageIO

The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.
How do I use ImageIO without corrupting the resamples?
The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.
some of my code. in this snippet, I tried adding Jui library, but still the same issue.
public static BufferedImage imageistream;
public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException
{
String imagePath = "";
if(this.is_mac_unix == true)
{
imagePath = this.path+"/"+child;
}
else
{
imagePath = this.path+"\\"+child;
}
PixelImage bmp = null;
try {
bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Resample resample = new Resample();
resample.setInputImage(bmp);
double fixedRatio = width/height;
if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio)
{
resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width)));
}
else
{
resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));
}
resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
resample.process();
PixelImage scaledImage = resample.getOutputImage();
Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage);
bmp = null;
Runtime rt = Runtime.getRuntime();
rt.gc();
}
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(Processor.imageistream, "jpg", baos);
// ImageIO.write(Processor.imageistream, "png", baos); Works!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte bytes[] = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
OutputStream os = (OutputStream)obj[1];
OutputStreamWriter writer = (OutputStreamWriter)obj[0];
byte[] buf= new byte[4096];
int c;
try {
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
writer.close();
os.close();
is.close();
I've been successfully using:
BufferedImage bufferedImage = ImageIO.read(..);
Image img = bufferedImage.getScaledInstance(..);
BufferedImage result = // transform Image to BufferedImage
ImageIO.write(result, "image/jpeg", response.getOutputStream());
transformation is simply writing the contents of the image to a new BufferedImage

Categories