如何在PDFBox Android中添加图像作为页面

时间:2015-05-25 09:08:16

标签: android pdfbox

我在我的android项目中添加了PdfBox Android port

我写了以下代码

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)
{
}

当我执行它时,一直顺利到行

PDImageXObject img = new PDImageXObject(steam1, resource1);

我收到以下错误

  

java.io.IOException:未读取空流

如何解决?我想我错过了什么。请帮帮我!

1 个答案:

答案 0 :(得分:1)

使用JPEGFactory,而不是PDImageXObject:

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

使用PDResources和PDStream删除行。因此,您的代码将如下所示:

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)
{
}

(此答案仅适用于Android版本)