如何从Android以编程方式创建pdf

时间:2016-11-04 13:33:09

标签: android itext

我正在使用Android Studio构建应用。在我的活动中,我想创建一个PDF文件,所以我从互联网上复制了这段代码,以创建并打开一个简单的PDF文件。

public void createandDisplayPdf(String text) {

        Document doc = new Document();

        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Dir";

            File dir = new File(path);
            if(!dir.exists())
                dir.mkdirs();

            File file = new File(dir, "newFile.pdf");
            FileOutputStream fOut = new FileOutputStream(file);

            PdfWriter.getInstance(doc, fOut);

            //open the document
            doc.open();

            Paragraph p1 = new Paragraph(text);
            Font paraFont= new Font(Font.COURIER);
            p1.setAlignment(Paragraph.ALIGN_CENTER);
            p1.setFont(paraFont);

            //add paragraph to document
            doc.add(p1);

        } catch (DocumentException de) {
            Log.e("PDFCreator", "DocumentException:" + de);
        } catch (IOException e) {
            Log.e("PDFCreator", "ioException:" + e);
        }
        finally {
            doc.close();
        }

        viewPdf("newFile.pdf", "Dir");
    }

// Method for opening a pdf file
    private void viewPdf(String file, String directory) {

        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/" + directory + "/" + file);
        Uri path = Uri.fromFile(pdfFile);

        // Setting the intent for pdf reader
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try {
            startActivity(pdfIntent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(creaOrdine.this, "Can't read pdf file", Toast.LENGTH_SHORT).show();
        }
    }

这是我的Grandle档案:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.mcsolution.easymanagementandroid"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile files('libs/gson-2.2.4.jar')
    compile 'com.itextpdf:itextg:5.5.9'
}

但是,如果我尝试执行此代码,我收到了这个奇怪的错误。

11-04 14:21:11.014 10336-10336/com.mcsolution.easymanagementandroid.easymanagementandroid E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mcsolution.easymanagementandroid.easymanagementandroid, PID: 10336
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;
at com.lowagie.text.pdf.PdfChunk.color(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.writeLineToContent(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.flushLines(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.close(Unknown Source)
at com.lowagie.text.Document.close(Unknown Source)
at com.mcsolution.easymanagementandroid.ordine.creaOrdine.createandDisplayPdf(creaOrdine.java:710)
at com.mcsolution.easymanagementandroid.ordine.creaOrdine.onCreate(creaOrdine.java:99)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2760)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.Color" on path: 
DexPathList[[dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-support-annotations-23.3.0_469f8f3ca3f9e0c059b9c6f2d04acc51933988a6-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_9-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_8-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_7-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_6-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_5-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_4-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_3-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_2-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_1-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-slice_0-classes.dex",
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-lowagie-2.1.7_6c71a44cd1fb2c264f7135848cfb4fd4358dd002-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-itextg-5.5.9_cd19495ec54a0d85948e5ccfd0ef953b783cde4e-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-internal_impl-23.3.0_459b0ff04633a2c5ffc128ab96df15303edb9d39-classes.dex", 
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-gson-2.2.4_e859ceafcaa49a8708d05a8e64ce9bdc0fd2e6a0-classes.dex",
dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-com.android.support-support-vector-drawable-23.3.0_32569b030fbf7638ea

这个错误很奇怪,因为我不使用awt.Color。

2 个答案:

答案 0 :(得分:5)

您正在使用iText for Java,而您应该使用iTextG for Android和GoogleAppEngine。见http://itextgroup.com/product/itextg

在iText for Java中,您依赖于Java包java.awtjavax.nio等中的类。这些类在Android上被禁止,这就解释了为什么会出现这个错误。

在iTextG中,我们删除了所有这些类,保持大部分功能不变。

更新:查看您的依赖项,我看到'com.itextpdf:itextg:5.5.9'表示您已经在使用iTextG。尽管如此,你在某处使用java.awt.Color是禁止的。

当我查看您的错误消息时,我看到了

dex file "/data/data/com.mcsolution.easymanagementandroid.easymanagementandroid/files/instant-run/dex/slice-lowagie-2.1.7

Lowagie,我是你,你正在使用iText 2.1.7(不再使用的库)以及iTextG(你需要的库)。你应该检查你如何介绍旧的iText版本,因为它不应该在Android上使用。

<强>解决方案:

  • 确保您不会导入com.lowagie课程。仅导入com.itextpdf个类。一般规则是:如果您在代码中看到我的名字,那么您就会做错事。
  • 确保删除对iText 2.1.7的所有引用。你不应该将两个不同版本的iText彼此相邻使用。
  • 请确保您未在​​代码中引入任何禁用类(java.awt.*javax.nio.*)。

答案 1 :(得分:0)

您正在使用专为纯Java设计的库。 Java API和Android API之间存在一些细微但仍然显着的差异,主要与gfx有关。正如您所看到的,Java Color类在Android上没有严格的等效类。这就是导致你的错误的原因。

您可以找到支持Android的PDF库,也可以使用远程服务转换文档并直接以PDF格式下载。

您可能会对此线程感兴趣:适用于Android的PDF库 - PDFBox?