Out Sider
Out Sider

Reputation: 37

how to add image as page in PDFBox Android

I have add PdfBox Android port in my android project.

I have wrote the following code

try
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    // page.set
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myapp");
    File phone = new File(mediaStorageDir.getPath() + File.separator + "image.jpg");
    FileInputStream mInput = new FileInputStream(phone);   
             PDStream steam1 = new PDStream(document, mInput);
    PDResources resource1 = new PDResources();
    PDImageXObject img = new PDImageXObject(steam1, resource1);
    PDPageContentStream contentStream = new PDPageContentStream(
    document, page);
    contentStream.drawImage(img, 100, 100);
    contentStream.close();
    document.save("Hello World.pdf");
    document.close();
}
catch(Exception e)
{
}

when I execute it goes well until following line

PDImageXObject img = new PDImageXObject(steam1, resource1);

I get following error

java.io.IOException: null stream was not read

how to solve it? I think I am missing something. please help me!

Upvotes: 2

Views: 1856

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18906

use the JPEGFactory, not PDImageXObject:

PDImageXObject img = JPEGFactory.createFromStream(document, mInput);

delete the lines with PDResources and with PDStream. Thus your code would look like this:

try
{
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    // page.set
    document.addPage(page);

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myapp");
    File phone = new File(mediaStorageDir.getPath() + File.separator + "image.jpg");
    FileInputStream mInput = new FileInputStream(phone);   
    PDImageXObject img = JPEGFactory.createFromStream(document, mInput);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.drawImage(img, 100, 100);
    contentStream.close();
    document.save(mediaStorageDir.getPath() + File.separator + "Hello World.pdf");
    document.close();
}
catch(Exception e)
{
}

(This answer applies only to the Android version)

Upvotes: 1

Related Questions