Convert PDF to png file with transparency (keep alpha) - java

I have been trying to convert PDF to png file with transparency without success.
I tried to solve it with many ways but I didn't succeed.
I'm writing my ways hoping someone will find where it went wrong:
1.
try (final PDDocument document = PDDocument.load(new File(srcpath))){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
String fileName = imageConverted;
boolean hasAlpha = bim.getColorModel().hasAlpha();
System.out.println(hasAlpha);
ImageIOUtil.writeImage(bim, fileName, 300);
}
document.close();
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
int num=pdffile.getNumPages();
for(int i=0;i<num;i++)
{
PDFPage page = pdffile.getPage(i);
//get the width and height for the doc at the default zoom
int width=(int)page.getBBox().getWidth();
int height=(int)page.getBBox().getHeight();
Rectangle rect = new Rectangle(0,0,width,height);
int rotation=page.getRotation();
Rectangle rect1=rect;
if(rotation==90 || rotation==270)
rect1=new Rectangle(0,0,rect.height,rect.width);
//generate the image
BufferedImage img = (BufferedImage)page.getImage(
rect.width, rect.height, //width & height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
Graphics2D graphics = (Graphics2D)img.getGraphics();
graphics.setBackground( new Color( 255, 255, 255, 0 ) );
ImageIO.write(img, "png", new File(imageConverted));
}
}
catch (FileNotFoundException e1) {
System.err.println(e1.getLocalizedMessage());
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
3.
// Instantiating the PDFRenderer class
PDFRenderer renderer = new PDFRenderer(document);
// Rendering an image from the PDF document
BufferedImage image = null;
try {
image= renderer.renderImage(0);
} catch (IOException e1) {
return "N/A";
}
// Writing the image to a file
try {
ImageIO.write(image, "png", new File(imageConverted));
} catch (IOException e) {
return "N/A";
}
But I get the png with white background...
Any idea?
Thanks in advance!!!

change this line
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
to
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGBA);
this will get you a transparent image.

Related

how convert multiple images to single PDF from folder in android?

I want to make android app to merge multiple image from single folder into single pdf file.
ex :
folder name :
- images
- 1.jpg
- 2.jpg
- 3.jpg
- 4.jpg
- 5.jpg
there are 5 images are in folder named images
how can i make pdf of that images?
if anyone have possible solution then please comment answer :)
Try this after 4.4 version it will work.
private void createPDF() {
final File file = new File(uploadFolder, "AnswerSheet_" + queId + ".pdf");
final ProgressDialog dialog = ProgressDialog.show(this, "", "Generating PDF...");
dialog.show();
new Thread(() -> {
Bitmap bitmap;
PdfDocument document = new PdfDocument();
// int height = 842;
//int width = 595;
int height = 1010;
int width = 714;
int reqH, reqW;
reqW = width;
for (int i = 0; i < array.size(); i++) {
// bitmap = BitmapFactory.decodeFile(array.get(i));
bitmap = Utility.getCompressedBitmap(array.get(i), height, width);
reqH = width * bitmap.getHeight() / bitmap.getWidth();
Log.e("reqH", "=" + reqH);
if (reqH < height) {
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
} else {
reqH = height;
reqW = height * bitmap.getWidth() / bitmap.getHeight();
Log.e("reqW", "=" + reqW);
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
}
// Compress image by decreasing quality
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.WEBP, 50, out);
// bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
//bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
//Create an A4 sized page 595 x 842 in Postscript points.
//PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(reqW, reqH, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Log.e("PDF", "pdf = " + bitmap.getWidth() + "x" + bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
}
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(() -> {
dismissDialog(dialog);
});
}).start();
}
If you want to create a pdf file with multiple images you can use PdfDocument from Android. Here is a demo:
private void createPDFWithMultipleImage(){
File file = getOutputFile();
if (file != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < images.size(); i++){
Bitmap bitmap = BitmapFactory.decodeFile(images.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile(){
File root = new File(this.getExternalFilesDir(null),"My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()){
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
}
else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
Here images is the ArrayList of the images with path.
Break your problem down into smaller problems. It's a fairly simple application.
Get the folder name from the user. See the native file open dialog to find a folder. See here.
Search its files for images
Create a pdf of the images. Use a library such as apache pdfbox.
Use this iText library
Create a document
String FILE = "{folder-path}/FirstPdf.pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
Add image in the document
try {
// get input stream
String fileName = "OfflineMap/abc.jpg";
String path =
Environment.getExternalStorageDirectory()+"/"+fileName;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream ims = getAssets().open("myImage.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
document.close();
}
catch(IOException ex)
{
return;
}

Combining PNG Images Java

I am trying to loop through a file of png images and stitch them together to form one image. I have gotten it to work without using a for loop and just combining two images from the file. So I am assuming it is the looping that isn't working. The images are located in a file called "images".
I would appreciate your input!
File file = new File("images");
File [] moreFile = file.listFiles();
String [] images = new String [moreFile.length];
for(int i =0; i <images.length; i++)
{images[i] = moreFile[i].getName();
}
int x = 0;
int y = 0;
BufferedImage result = new BufferedImage(
controller.getSize().width*2, controller.getSize().height, //work these out
BufferedImage.TYPE_INT_RGB);
Graphics g = result.getGraphics();
for(String image : images){
System.out.println(image);
File path = new File("images");
try{ImageIO.read(new File(path, image));
System.out.println("it definitely goes here");
BufferedImage bi = new BufferedImage((2*510),(2*439),BufferedImage.TYPE_INT_ARGB);
bi =ImageIO.read(new File(path, image));
g.drawImage(bi, x, y, null);
g.dispose();
/// System.out.println(dafuck);
x += bi.getWidth();
if(x > result.getWidth()){
x = 0;
y += bi.getHeight();
}
}catch (Exception e) {
System.out.println("is it an exception>?");
}
}
try {
ImageIO.write(result,"png",new File("results"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

PDF Document is only half in width when converted a png image to pdf using PDFBox

I have used PDFBox to convert a png image to pdf document and i am successfully able to do that.
But i am encountering an issue in which the the pdf document only shows 50% width of the image (height is shown full).Please help me with this.
The code i am using is as follows:
public static void createPDFFromImage( String file, String image) throws IOException, COSVisitorException
{
PDDocument doc = null;
try
{
doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage( page );
PDXObjectImage ximage = null;
if( image.toLowerCase().endsWith( ".jpg" ) || image.toLowerCase().endsWith( ".jpeg" ))
{
BufferedImage awtImage = ImageIO.read( new File( image ) );
ximage = new PDJpeg(doc, awtImage, 0 );
}
else
{
BufferedImage awtImage = new BufferedImage(250,250, BufferedImage.TYPE_INT_RGB);
awtImage = ImageIO.read(new FileImageInputStream(new File( image )));
ximage = new PDPixelMap(doc, awtImage);
}
System.out.println(" Width of the image.... " + ximage.getWidth());
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
contentStream.drawImage( ximage, 20, 20);
//contentStream.drawImage( ximage, 20, 20 );
contentStream.close();
doc.save( file );
}
finally
{
if( doc != null )
{
doc.close();
}
}
}
NOTE:everytime the dimension of the image gets changed while saving
Please help.
Thanks
These code may be hepful to you.
public void createPDFFromImage(String pdfFile,
List<String> imgList,int x, int y, float scale) throws IOException, COSVisitorException {
// the document
PDDocument doc = null;
try {
doc = new PDDocument();
Iterator iter = imgList.iterator();
int imgIndex=0;
while(iter.hasNext()) {
PDPage page = new PDPage();
doc.addPage(page);
BufferedImage tmp_image = ImageIO.read(new File(iter.next().toString()));
BufferedImage image = new BufferedImage(tmp_image.getWidth(), tmp_image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
image.createGraphics().drawRenderedImage(tmp_image, null);
PDXObjectImage ximage = new PDPixelMap(doc, image);
imgIndex++;
PDPageContentStream contentStream = new PDPageContentStream(
doc, page,true,true);
contentStream.drawXObject(ximage, x, y, ximage.getWidth()*scale, ximage.getHeight()*scale);
contentStream.close();
}
doc.save(pdfFile);
} finally {
if (doc != null) {
doc.close();
}
}
}

Zoom option in PDF-Renderer library

I am checking the api of https://pdf-renderer.dev.java.net/
I want to convert the PDF to image at zoom level 100%.
Does any one tried that?
int widthPage = (int)page.getBBox().getWidth();
int heightPage = (int)page.getBBox().getHeight();
if(page.getAspectRatio()<1){
widthPage = (int)(widthPage / page.getAspectRatio() );
heightPage = (int)(heightPage / page.getAspectRatio() );
}
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) widthPage, (int) heightPage);
// generate the image
Image img = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
// save it as a file
I would suggest iText for PDF viewing. It has been pretty good for me so far.
Just change the Image dimensions. When you zoom the Image all the characters appeared in clear view if the image dimensions are high. Download 04-Request-Headers.pdf file and paste it in C drive, converted files are saved in PDFConvertedFiles folder. Jars Required PDFRenderer-0.9.0
package com.pdfrenderer.examples;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.imageio.ImageIO;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class ConvertAllPDFPagesToImageWithDimenstions {
public static void main(String[] args) {
try {
String sourceDir = "C:/04-Request-Headers.pdf";// PDF file must be placed in DataGet folder
String destinationDir = "C:/PDFConvertedFiles/";//Converted PDF page saved in this folder
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
String fileName = sourceFile.getName().replace(".pdf", "");
if (sourceFile.exists()) {
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder created in: "+ destinationFile.getCanonicalPath());
}
RandomAccessFile raf = new RandomAccessFile(sourceFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
System.out.println("Total Pages: "+ pdf.getNumPages());
int pageNumber = 1;
for (int i = 0; i < pdf.getNumPages(); i++) {
PDFPage page = pdf.getPage(i);
// image dimensions
int width = 1200;
int height = 1400;
// create the image
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// width & height, // clip rect, // null for the ImageObserver, // fill background with white, // block until drawing is done
Image image = page.getImage(width, height, rect, null, true, true );
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
File imageFile = new File( destinationDir + fileName +"_"+ pageNumber +".png" );// change file format here. Ex: .png, .jpg, .jpeg, .gif, .bmp
ImageIO.write(bufferedImage, "png", imageFile);
pageNumber++;
System.out.println(imageFile.getName() +" File created in Folder: "+ destinationFile.getCanonicalPath());
}
} else {
System.err.println(sourceFile.getName() +" File not exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Java: Splitting .GIF image in BufferedImages Gives Malformed Images

So I have a very small piece of code, which takes a .gif image as input, and then it splits this .gif image into an array of BufferedImage. After that, it stores the images in the array on the disk. When I do this, the output images contain heavy white-pixel noise which isn't visible in the input .gif image.
Example of the input gif:
Example of malformed output image (the 3rd frame in the gif):
The code I am using to split the gif is as follows:
public static void main(String[] args) throws Exception {
splitGif(new File("C:\\test.gif"));
}
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next(); reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
for(int i = 0; i < reader.getNumImages(true); i++) {
BufferedImage image = reader.read(i);
ImageIO.write(image, "PNG", new File(i + ".png"));
}
}
Can anyone help me out?
So the problem was that when reading .gif files into java, then all pixels in a given frame that did not change color compared to their previous frame will be fully transparent. If you want to read a .gif and split it in an array of properly rendered BufferedImages, then you have to fill the transparent pixels of the current frame with the last non-transparent pixel of one of the previous frames.
Code:
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
BufferedImage lastImage = reader.read(0);
ImageIO.write(lastImage, "PNG", new File(0 + ".png"));
for (int i = 1; i < reader.getNumImages(true); i++) {
BufferedImage image = makeImageForIndex(reader, i, lastImage);
ImageIO.write(image, "PNG", new File(i + ".png"));
}
}
private static BufferedImage makeImageForIndex(ImageReader reader, int index, BufferedImage lastImage) throws IOException {
BufferedImage image = reader.read(index);
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
if(lastImage != null) {
newImage.getGraphics().drawImage(lastImage, 0, 0, null);
}
newImage.getGraphics().drawImage(image, 0, 0, null);
return newImage;
}
You solved it yourself, but for good order: every next frame is the accumulation of all prior frames filling up the transparent pixels in the current frame.
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
BufferedImage outImage = null;
Graphics2D g = null;
for (int i = 0; i < reader.getNumImages(true); i++) {
BufferedImage image = reader.read(i);
if (g == null) {
BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
g = (Graphics2D) outImage.getGraphics();
}
g.drawImage(lastImage, 0, 0, null);
ImageIO.write(outImage, "PNG", new File(i + ".png"));
}
if (g != null) {
g.dispose();
}
}
getGraphics==createGraphics should be balanced be a dispose as documented.

Categories

Resources