首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PDFBox Android中添加图像作为页面

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

Stack Overflow用户
提问于 2015-05-25 09:08:16
回答 1查看 1.7K关注 0票数 2

我在我的安卓项目中添加了PdfBox安卓端口

我写了以下代码

代码语言:javascript
复制
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)
{
}

当我执行时,它执行得很好,直到下面一行

代码语言:javascript
复制
PDImageXObject img = new PDImageXObject(steam1, resource1);

我得到跟随错误

java.io.IOException:空流未被读取

如何解决这个问题?我想我漏掉了什么。请帮帮我!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-05-25 10:14:09

使用JPEGFactory,而不是PDImageXObject:

代码语言:javascript
复制
PDImageXObject img = JPEGFactory.createFromStream(document, mInput);

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

代码语言:javascript
复制
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版本)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30434748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档