【问题标题】:Insert Image into PDF Document将图像插入 PDF 文档
【发布时间】:2019-10-04 06:33:31
【问题描述】:

是否可以在 PDF 文档中添加图像?我的布局有一个(Button)和一个(ImageView),我希望当我单击(Button)时,它会打开Gallery以选择图像,将其显示在(ImageView)中并将其添加到PDF文档中,就好像这是一个生成器课程,提前谢谢你。

*Eu estou utilizando com.itextpdf:itextg:5.5.10

【问题讨论】:

  • 试试这篇文章how-to-convert-image-to-pdf
  • 感谢您的回答!我看过你评论的这个问题,但我看到在他的情况下他已经有了图像的正确路径,我想从图库中选择它
  • 那么您可能应该只询问您还不知道该怎么做的部分,即从图库中选择图像并检索其路径。
  • 没错!很抱歉我无法正确解释

标签: image android-studio android-intent itext


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!我会尝试这种方式,我会回来回答!
  • 很遗憾这种方法不适用于我的项目,无论如何非常感谢您的关注!
  • 嘿,如果你喜欢我的努力,你可以点赞我的回答吗
猜你喜欢
  • 2016-03-03
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
相关资源
最近更新 更多