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

how to add image as page in PDFBox Android

我在我的 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: null stream was not read

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

使用 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版本)