将图像插入PDF文档

时间:2019-10-04 06:33:31

标签: image android-studio android-intent itext

是否可以将图像添加到PDF文档?我的布局有一个(按钮)和一个(图像视图),我想当我单击(按钮)时,它将打开图库以选择图像,在(图像视图)中显示它并将其添加到PDF文档中,就像这是一门发电机课程,谢谢。

* Eu estou utilizando com.itextpdf:itextg:5.5.10

1 个答案:

答案 0 :(得分:0)

这是您想要的完整代码。试试这个,让我知道。

在onCreate方法中:

@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);
                }
            }
        });
    }

为PDF文件创建目录:

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;
    }

关于摄像机活动意图的结果:

@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");
            }
        }
    }

现在将代码转换为PDF并保存到目录的代码:

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();
    }