【问题标题】:How to capture a photo and immediately put it into an existing pdf?如何捕捉照片并立即将其放入现有的 pdf 中?
【发布时间】:2015-06-12 16:59:11
【问题描述】:

我找不到我的问题的解决方案。我的MainActivity 创建一个pdf 文件,用户通过EditText 添加一些文本并关闭它,没问题。然后我有一个次要活动是调用MediaStore.ACTION_IMAGE_CAPTURE 拍照。拍完照片后,我想知道如何将刚刚捕获的图像放入该 pdf 中。

我知道我必须重新打开 pdf,这没问题,因为我将 pdf 文件名保存在一个变量中。我看到的主要问题是我不知道如何以编程方式获取图片的文件名,一旦它自动命名为“yyyyMMdd_hhMMss.jpg”。那么如何从我的次要活动拍摄的图片中获取文件名呢?

*EDIT - 显示代码:

来自 MainActivity:

public class MainActivity extends Activity {

public String FILE = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf"; 

public static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
public static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL, BaseColor.RED);
public static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.BOLD);
public static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);

EditText estRep;
EditText sensRep;
EditText cabRep;

String estais;
String sensores;
String cabos;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    estRep = (EditText)findViewById(R.id.estaisRep);
    sensRep = (EditText)findViewById(R.id.sensoresRep);
    cabRep = (EditText)findViewById(R.id.cabosRep);
}

public void gerarPDF(View view) {

    estais = estRep.getText().toString();
    sensores = sensRep.getText().toString();
    cabos = cabRep.getText().toString();

    try {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(FILE));
        document.open();
        addMetaData(document);
        addTitlePage(document);
        addContent(document);
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("CoManut");
    alertDialog.setMessage("Picture?");

    alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            Intent intent = new Intent(MainActivity.this, PhotoActivity.class);
            startActivity(intent);
        }
    });

    alertDialog.setButton2("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            Toast.makeText(MainActivity.this, "Thanks for using this app!", Toast.LENGTH_LONG).show();
            MainActivity.this.finish();
        }
    });
    alertDialog.setIcon(R.mipmap.ic_launcher);
    alertDialog.show();
}

private static void addMetaData(Document document) {
    document.addTitle("Image and text to PDF");
    document.addSubject("Using iText");
    document.addKeywords("Java, PDF, iText");
    document.addAuthor("Ricardo Gramowski");
    document.addCreator("Ricardo Gramowski");
}

private static void addTitlePage(Document document)
        throws DocumentException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Maintenance report", catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(),
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("This doc is important", smallBold));
    addEmptyLine(preface, 8);
    preface.add(new Paragraph("This doc has been generated by Gramowski.",
            redFont));

    document.add(preface);
    // Start a new page
    document.newPage();
}

private void addContent(Document document) throws DocumentException {
    Anchor anchor = new Anchor("Chapter 1", catFont);
    anchor.setName("Chapter 1");

    Chapter catPart = new Chapter(new Paragraph(anchor), 1);

    Paragraph subPara = new Paragraph("Results", subFont);
    Section subCatPart = catPart.addSection(subPara);

    addEmptyLine(subPara, 1);
    createTable(subCatPart);
    document.add(catPart);  
}

private void createTable(Section subCatPart)
        throws BadElementException {
    PdfPTable table = new PdfPTable(2);
    PdfPCell c1 = new PdfPCell(new Phrase("Item"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    c1 = new PdfPCell(new Phrase("Is that good? (OK/Not OK)"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    table.setHeaderRows(1);

    table.addCell("Estais da Torrre ");
    table.addCell(estais);
    table.addCell("Sensores ");
    table.addCell(sensores);
    table.addCell("Cabos ");
    table.addCell(cabos);

    subCatPart.add(table);

}

private static void addEmptyLine(Paragraph paragraph, int number) {
    for (int i = 0; i < number; i++) {
        paragraph.add(new Paragraph(" "));
    }
}
}

还有我的 PhotoActivity:

public class PhotoActivity extends ActionBarActivity {

Button b1;
ImageView iv;
Bitmap bp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo);

    b1 = (Button) findViewById(R.id.button1);
    iv = (ImageView) findViewById(R.id.imageView);

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 0);
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap mImageBitmap = (Bitmap) extras.get("data");

        iv.setImageBitmap(mImageBitmap);

        String fpath = Environment.getExternalStorageDirectory() + "/CoManut/sample.pdf";

        File file = new File(fpath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Document document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(fpath));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (DocumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        document.open();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        Image myImg = null;
        try {
            myImg = Image.getInstance(stream.toByteArray());
        } 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();
        }
        myImg.setAlignment(Image.MIDDLE);

        try {
            document.add(myImg);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        document.close();

    }
}

//  Button to go back to the MainActivity
public void onclickButton2(View view) {

    PhotoActivity.this.finish();

 }

@Override
protected void onDestroy() {
    super.onDestroy();
    }
}

【问题讨论】:

  • 请出示您的意图代码。
  • 换句话说,向我们展示您创建和使用ACTION_IMAGE_CAPTURE Intent 的代码,并向我们展示您在其中获得对ACTION_IMAGE_CAPTURE 请求的响应的onActivityResult() 方法。
  • @CommonsWare:版本制作。

标签: android filenames image-capture


【解决方案1】:

覆盖Main Activity 中的 onActivitResult() 方法

在这里,您将从(Intent Data)获取图像位图

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap mImageBitmap = (Bitmap) extras.get("data");
    }
}

现在你有了位图。您可以使用 iText 库添加如下所示的位图图像

 try {
       ByteArrayOutputStream stream = new ByteArrayOutputStream();
       mImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // Try with Bitmap.CompressFormat.JPG also
       Image image = Image.getInstance(stream.toByteArray());
       document.add(image);

    }catch(IOException ex){
            ex.printStackTrace();
   }

更新1

您的 onActivityResult() 应该如下所示。

注意确保您在 menifest.xml 文件中有WRITE_EXTERNAL_STORAGE 权限。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap mImageBitmap = (Bitmap) extras.get("data");

        img.setImageBitmap(mImageBitmap);

        String fpath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/sample.pdf";
        File file = new File(fpath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        Document document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(fpath));
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (DocumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        document.open();

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        mImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        Image myImg = null;
        try {
            myImg = Image.getInstance(stream.toByteArray());
        } 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();
        }
        myImg.setAlignment(Image.MIDDLE);

        try {
            document.add(myImg);
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        document.close();

    }
}

这将在您的 sdcard 中创建一个 sample.pdf 文件,并将 Image 位图添加到其中。

希望这会有所帮助。 我在这里测试了它的工作原理。 :)

【讨论】:

  • @Quadir Hussain:谢谢,但是片段 Image.getInstance(stream.toByteArray());显示如下消息:未处理的异常:com.iTextpdf.text.BadElementException
  • @Quadir Hussain:不幸的是它对我不起作用,我不知道出了什么问题。我用我所有的 mainactivity 代码以及我的 photoactivity 代码更新了我的原始问题。希望你能指出我的错误。
  • @Quadir Hussain:编译没有错误,但是当我构建一个 APK 并在我的手机上执行它进行测试(API 16)时,它不会在我定义的那个位置生成任何 pdf “文件”变量。在执行过程中我也没有收到任何错误。
  • @Quadir Hussain:更新:代码正在生成 PDF 文件,但不包括其上的位图。只有输入到 editText 框中的文本才会打印到 pdf 中。知道会是什么吗?
  • @Gramowski 您是否收到任何警告或异常。现在在你的日志中吗?
猜你喜欢
  • 1970-01-01
  • 2019-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 2015-09-02
  • 1970-01-01
相关资源
最近更新 更多