如何将图像转换为PDF?

我正在开发一个应用程序,我需要将图像转换为PDF。 我尝试了一些,但问题是,该PDF中的图像大小非常小。 我需要解决scheme来解决此问题。 另外我正在寻找将多个图像转换为单个PDF文档。 我会发布我试过的代码。

public void convertPDF(byte[] path) { String FILE = "mnt/sdcard/FirstPdf.pdf"; Document document=new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(FILE)); document.open(); try { image=Image.getInstance(path); document.add(new Paragraph("My Heading")); document.add(image); document.close(); } catch (IOException e) { e.printStackTrace(); } } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } 

当我将位图转换为字节数组时,我正在压缩图像,我想这就是原因。 如果不压缩图像,我无法将位图转换为字节数组。

  ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG,100,stream); byte[] byteArray=stream.toByteArray(); convertPDF(byteArray); 

有没有解决scheme?

更新

在这里我已经实现了@Burak Cakir在答案中提出的答案。 但是现在我正在用PDF获得更大的图像。 为了更好的理解,请find下面的图片。 在这里输入图像说明

其实图像是 在这里输入图像说明

Solutions Collecting From Web of "如何将图像转换为PDF?"

我build议你使用iText pdf库。 这是gradle依赖:

compile 'com.itextpdf:itextg:5.5.11'

对于android-studio 3.0使用:

implementation 'com.itextpdf:itextg:5.5.11'

  Document document=new Document(); String dirpath=android.os.Environment.getExternalStorageDirectory().toString(); PdfWriter.getInstance(document,new FileOutputStream(dirpath+"/example.pdf")); // Change pdf's name. document.open(); Image img =Image.getInstance(dirpath+"/"+"example.jpg"); // Change image's name and extension. float scaler = ((document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin() - 0) / img.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it. img.scalePercent(scaler); img.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP); //img.setAlignment(Image.LEFT| Image.TEXTWRAP); /* float width = document.getPageSize().width() - document.leftMargin() - document.rightMargin(); float height = document.getPageSize().height() - document.topMargin() - document.bottomMargin(); img.scaleToFit(width, height)*/ Or try this. document.add(img); document.close(); 

从这里下载源代码( 以编程方式将图像转换为PDF格式 )

MainActivity.java:

 package com.deepshikha.convertbitmap; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.pdf.PdfDocument; import android.net.Uri; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int GALLERY_PICTURE = 1; Button btn_select, btn_convert; ImageView iv_image; boolean boolean_permission; boolean boolean_save; Bitmap bitmap; public static final int REQUEST_PERMISSIONS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); listener(); fn_permission(); } private void init() { btn_select = (Button) findViewById(R.id.btn_select); btn_convert = (Button) findViewById(R.id.btn_convert); iv_image = (ImageView) findViewById(R.id.iv_image); } private void listener() { btn_select.setOnClickListener(this); btn_convert.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_select: Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, GALLERY_PICTURE); break; case R.id.btn_convert: if (boolean_save){ Intent intent1=new Intent(getApplicationContext(),PDFViewActivity.class); startActivity(intent1); }else { createPdf(); } break; } } private void createPdf(){ WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels ; float width = displaymetrics.widthPixels ; int convertHighet = (int) hight, convertWidth = (int) width; // Resources mResources = getResources(); // Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot); PdfDocument document = new PdfDocument(); PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create(); PdfDocument.Page page = document.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.drawBitmap(bitmap, 0, 0 , null); document.finishPage(page); // write the document content String targetPdf = "/sdcard/test.pdf"; File filePath = new File(targetPdf); try { document.writeTo(new FileOutputStream(filePath)); btn_convert.setText("Check PDF"); boolean_save=true; } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show(); } // close the document document.close(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) { if (resultCode == RESULT_OK) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); bitmap = BitmapFactory.decodeFile(filePath); iv_image.setImageBitmap(bitmap); btn_convert.setClickable(true); } } } private void fn_permission() { if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)|| (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) { if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) { } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS); } if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) { } else { ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS); } } else { boolean_permission = true; } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSIONS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { boolean_permission = true; } else { Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show(); } } } } 

谢谢!

通过使用此代码,您可以将图像转换为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(); } } 

对于PDF格式的图像,可能有类似iText,droidtext的库,所以你可以使用它。