android图片没有出现在iText pdf中

时间:2015-07-30 22:07:02

标签: android image pdf

我试图通过Android平台中的iText库将图像转换为Pdf格式。我能够在所需的位置生成Pdf,但图像不在pdf中,即生成空白pdf。以下是我的代码。如果您发现任何错误,请纠正我。我包括了#itextg-5.5.4'在' libs'文件夹并包含在库中。代码中没有编译时错误。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    Bundle extras = data.getExtras();
    photo = extras.getParcelable("data");
    File outFile = new File(pdfFolder,imageName);//pdfFolder exists at a location and imageName=timestamp
     FileOutputStream fos = new FileOutputStream(outFile);
     photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);

    Date date = new Date() ;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

    File myFile = new File(pdfFolder , timeStamp + ".pdf");

    OutputStream output = new FileOutputStream(myFile);

    //Step 1
    Document document = new Document(PageSize.A4, 25, 25, 30, 30);;

    //Step 2
    PdfWriter writer=PdfWriter.getInstance(document, output);

    //Step 3
    document.open();

    //Step 4 Add content

    document.add(new Paragraph("Simple Image"));

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    Image image=Image.getInstance(stream.toByteArray());

    document.add(image);
    document.close();
    output.close();

2 个答案:

答案 0 :(得分:1)

我自己找到了一个解决方案,如下所示。取代

 Image image=Image.getInstance(stream.toByteArray());

 Image image=Image.getInstance(outFile.toString());

原因:Image.getInstance(" ImageName")。我正在使用ByteArray,它无法识别图像。

答案 1 :(得分:0)

以下是功能齐全的代码:

File myFile;
public void createpdf() throws DocumentException, IOException {

        //Create time stamp to name the pdf

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        myFile = new File(pdfFolder, timeStamp + ".pdf");

        OutputStream output = new FileOutputStream(myFile);

        //Step 1
        Document document = new Document(PageSize.A4, 25, 25, 30, 30);
        ;

        //Step 2
        PdfWriter.getInstance(document, output);

        //Step 3
        document.open();

        //Step 4 Add content

        Paragraph preface = new Paragraph("TITLE_GOES_HERE");
        preface.setAlignment(Element.ALIGN_CENTER);

        document.add(preface);


    for (int i=0;i<photoNames.size();i++) {
    //'photoNames' is an ArrayList<String> holding names of images captured
        Image image = Image.getInstance(photoNames.get(i));

        int indentation = 0;

        float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                - document.rightMargin() - indentation) / image.getWidth()) * 100;
        image.scalePercent(scaler);

        document.add(image);

    }
        //Step 5: Close the document
        document.close();
        output.close();