android - 如何在 Android 中将图像文件转换为 pdf 文件

标签 android image pdf itextpdf

我正在尝试在我的 Adroid 应用程序中将图像文件 (jpeg) 转换为 pdf 文件。我用过itextpdf jar 和droidtext jar。都不适合我。下面是使用 itextpdf 时的代码。

Document document = new Document();

String directoryPath = Environment.getExternalStorageDirectory().toString();

File newPdfFile = new File(directoryPath, "textview8.pdf");

FileOutputStream fileOutputStream = null;

try {
    fileOutputStream = new FileOutputStream(newPdfFile);
} catch (FileNotFoundException fnfe) {
    Log.w(TAG, "# Exception caz of fileOutputStream : " + fnfe);
}

BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

try {
    PdfWriter.getInstance(document, bufferedOutputStream);
} catch (DocumentException de) {
    Log.w(TAG, "# Exception caz of PdfWriter.getInstance : " + de);
}

document.open(); 

Image image = null;

try {
    image = Image.getInstance(directoryPath + File.separator + "textview1.JPEG");
} catch (BadElementException bee) {
    Log.w(TAG, "# First exception caz of image : " + bee);
} catch (MalformedURLException mue) {
    Log.w(TAG, "# Second exception caz of image : " + mue);
} catch (IOException ioe) {
    Log.w(TAG, "# Third exception caz of image : " + ioe);
}

try {
    document.add(image);
} catch (DocumentException de) {
    Log.w(TAG, "# Exception caz of document.add : " + de);
}

try {
    bufferedOutputStream.flush();
    bufferedOutputStream.close();

    fileOutputStream.flush();
    fileOutputStream.close();

} catch (IOException ioe) {
    Log.w(TAG, "# Exception caz of bufferedOutputStream.flush : " + ioe);
}

document.close();

由于代码行 document.close();

,这给了我一个 NullPointerException 错误

当我注释掉该行并运行程序时,出现以下错误。

Could not find class 'com.itextpdf.awt.PdfPrinterGraphics2D', referenced from method com.itextpdf.text.pdf.PdfContentByte.createPrinterGraphicsShapes

但是他们说找不到的类已经在jar文件中了,也就是说com.itextpdf.awt.PdfPrinterGraphics2D已经存在于项目中了。

我也将 itextpdf-5.1.3.jar 添加到构建路径中。我在模拟器和真实设备上都试过了。

无法弄清楚我做错了什么。请帮助...

最佳答案

只要简单地这样做就可以了

Document document=new Document();
String dirpath=android.os.Environment.getExternalStorageDirectory().toString();
PdfWriter.getInstance(document,new FileOutputStream(dirpath+"/imagedemo.pdf"));
document.open();
Image im=Image.getInstance(dirpath+"/"+"logo.png");  // Replace logo.png with your image name with extension 
document.add(im);
document.close();

关于android - 如何在 Android 中将图像文件转换为 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12315037/

相关文章:

c# - 异步加载 BitmapSource 图像时内存泄漏

c# - 如何使用 asp.net 在印地语中创建 pdf

更新支持库后Android Bottom Sheet 崩溃

java - 刷新 ListView 数据库

android - "selectionArgs"在包含 "selection"的 "?"查询中不起作用

Android 将图库文件夹中的图像复制到 SD 卡替代文件夹中

css - 如何在图像代码中放置超链接?

pdf - 链接到 LaTeX Beamer 中的外部应用程序

ios - PDFKit 水印注释问题

android - 自定义 ListView 不会被填充