How to convert Image to PDF?
I would suggest you to use iText
pdf library. Here is the gradle
dependency:
implementation 'com.itextpdf:itextg:5.5.10'
Document document = new Document();
String directoryPath = android.os.Environment.getExternalStorageDirectory().toString();
PdfWriter.getInstance(document, new FileOutputStream(directoryPath + "/example.pdf")); // Change pdf's name.
document.open();
Image image = Image.getInstance(directoryPath + "/" + "example.jpg"); // Change image's name and extension.
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 0) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP);
document.add(image);
document.close();
how convert multiple images to single PDF from folder in android?
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();
}
How to convert Image to PDF in Android
Use pdfbox it is a open source lib
use this to insert image in pdf
PDDocument document = new PDDocument();
InputStream in = new FileInputStream(someImage);
BufferedImage bimg = ImageIO.read(in);
float width = bimg.getWidth();
float height = bimg.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
PDXObjectImage img = new PDJpeg(document, new FileInputStream(someImage));
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(img, 0, 0);
contentStream.close();
in.close();
document.save("test.pdf");
document.close();
Convert image to PDF in Android
I think you are using iText Library to convert the text to pdf. Use this to convert image to pdf.
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class imagesPDF
{
public static void main(String arg[])throws Exception
{
Document document=new Document();
PdfWriter.getInstance(document,new FileOutputStream("YourPDFHere.pdf"));
document.open();
Image image = Image.getInstance ("yourImageHere.jpg");
document.add(new Paragraph("Your Heading for the Image Goes Here"));
document.add(image);
document.close();
}
}
How I can convert a bitmap into PDF format in android
you can do by this way...you have to download itextpdf-5.3.2.jar file and attach in your project..
public class WritePdfActivity extends Activity
{
private static String FILE = "mnt/sdcard/FirstPdf.pdf";
static Image image;
static ImageView img;
Bitmap bmp;
static Bitmap bt;
static byte[] bArray;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img=(ImageView)findViewById(R.id.imageView1);
try
{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
addImage(document);
document.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void addImage(Document document)
{
try
{
image = Image.getInstance(bArray); ///Here i set byte array..you can do bitmap to byte array and set in image...
}
catch (BadElementException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// image.scaleAbsolute(150f, 150f);
try
{
document.add(image);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Insert Image into PDF Document
here is the complete code of what you wanted. Try this and let me know.
In the onCreate method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_to_pdf);
imageView = findViewById(R.id.imageView);
galleryBtn = findViewById(R.id.gallery);
convertBtn = findViewById(R.id.convert);
galleryBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "PDF_" + timeStamp + "_";
File storageDir = getAlbumDir();
try {
pdfPath = File.createTempFile(
imageFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, GALLERY_INTENT);
}
});
convertBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
} else {
convertToPDF(pdfPath);
}
}
});
}
Create a directory for PDF file:
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "Image to pdf");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
On camera activity intent result:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
cursor.close();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Canceled", "Image not selected");
}
}
}
Now code to convert image to PDF and save to the directory:
private void convertToPDF(File pdfPath) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
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, width, height, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(pdfPath));
Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}
how we can convert image and text in pdf when button click?
You do the following code to create pdf -
implement these following libraries in your build.gradle app section:
implementation 'com.itextpdf:itextg:5.5.10'
implementation 'com.itextpdf:io:7.0.0'
implementation 'com.itextpdf:layout:7.0.0'
Then you need to write the following code on button click -
Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
createPDF();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Then create method createPDF()
private void createPDF() throws Exception{
File docsFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "AppName" + File.separator + "FolderName");
boolean success = true;
if (!docsFolder.exists()) {
success = docsFolder.mkdirs();
}
if (success) {
String randCode = new SimpleDateFormat("dd MM yyyy HH:mm:ss a", Locale.getDefault()).format(new Date()); //used for unique file name eveytime
randCode = randCode.replaceAll(":", "");
randCode = randCode.replaceAll(" ", "");
pdfFile = new File(docsFolder.getAbsolutePath(), randCode + ".pdf");
OutputStream outputStream = new FileOutputStream(pdfFile);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.setPageSize(PageSize.A4); //Page Size
document.setMargins(30,30,30,30); //here you can put any margin numbers as you wish
document.open();
imageView.setDrawingCacheEnabled(true);
imageView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
imageView.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
Image image = Image.getInstance(stream.toByteArray());
image.scaleToFit(document.getPageSize().getWidth(), document.getPageSize().getHeight());
image.setAlignment(Element.ALIGN_CENTER);//Center,Left,Right another options
document.add(image);
document.newPage(); //used for creating new page
Font f = new Font(Font.FontFamily.TIMES_ROMAN, 18f, Font.BOLD, BaseColor.RED);
document.add(new Paragraph("HeadingIfNeeded", f));
Font f1 = new Font(Font.FontFamily.TIMES_ROMAN, 15f, Font.NORMAL, BaseColor.BLACK);
document.add(new Paragraph("\n\n" + TextView.getText().toString(), f1));
document.close();
}else {
showToastRed("Error");
}
}
You can use the above code to createPDF.
Add a Bitmap image in a PDF document in Android
I just solve it:
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.add(myImg);
in the FileOperations class
Related Topics
Sethinttextcolor() in Edittext
How to Detect Android Listview Scrolling Stopped
Audio Format for iOS and Android
Crop Square Image to Circle - Programmatically
How to Hide The System/Navigation Bar in Android Ics
Does Android Studio Have a Hierarchy Viewer or Layout Inspector
Should The Call to The Superclass Method Be The First Statement
Android Imagegetter Images Overlapping Text
How to Get My Android Device Internal Download Folder Path
How to Execute Background Task When Android App Is Closed/Set to Background
Notification Passes Old Intent Extras
View Pager + Imageview +Pinch Zoom + Rotation
Syncadapter Without a Contentprovider
Retain The Fragment Object While Rotating
Items Inside Gridview Getting Repeated When Screen Scrolls
How to Set The Rounded Corner Radius of a Color Drawable Using Xml