Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/213.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android中创建PDF_Java_Android - Fatal编程技术网

Java 在Android中创建PDF

Java 在Android中创建PDF,java,android,Java,Android,我参考了这篇文章,我想用PDF打印名字和姓氏。在参考了本文之后,我对代码进行了修改,并在下面提供了我的代码 我主要是因为这些系统错误 java.lang.RuntimeException:未找到.document.is.not.open的消息 android中的com.itextpdf.text.pdf.pdfwriter.getdirectcontent(pdfwriter.java:742) 3.at.com.example.pdf.MainActivity.onClick(MainActi

我参考了这篇文章,我想用PDF打印名字和姓氏。在参考了本文之后,我对代码进行了修改,并在下面提供了我的代码

我主要是因为这些系统错误

  • java.lang.RuntimeException
    :未找到.document.is.not.open的
    消息
  • android中的com.itextpdf.text.pdf.pdfwriter.getdirectcontent(pdfwriter.java:742) 3.at.com.example.pdf.MainActivity.onClick(MainActivity.java:73)
  • 这是我在原代码中更改后的代码

            package com.example.pdf;
    
            import java.io.ByteArrayOutputStream;
            import java.io.File;
            import java.io.FileOutputStream;
            import java.io.IOException;
            import java.io.InputStream;
    
            import android.graphics.Bitmap;
            import android.graphics.BitmapFactory;
            import android.os.Bundle;
            import android.os.Environment;
            import android.support.v7.app.ActionBarActivity;
            import android.util.Log;
            import android.view.View;
            import android.view.View.OnClickListener;
            import android.widget.Button;
            import android.widget.EditText;
    
            import com.itextpdf.text.Document;
            import com.itextpdf.text.DocumentException;
            import com.itextpdf.text.PageSize;
            import com.itextpdf.text.Paragraph;
            import com.itextpdf.text.pdf.BaseFont;
            import com.itextpdf.text.pdf.PdfContentByte;
            import com.itextpdf.text.pdf.PdfWriter;
    
            public class MainActivity extends ActionBarActivity implements OnClickListener {
    
                EditText firstName_edt;
                EditText lastName_edt;
                Button preView_btn;
                private BaseFont bfBold;
                private String filepath = "MyInvoices";
                private String filename = "Sample.pdf";
                private File pdfFile;
                private static final String LOG_TAG = "GeneratePDF";
    
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
    
                    /*InputStream license = this.getResources().openRawResource(R.raw.itextkey);
                      LicenseKey.loadLicenseFile(license);*/
    
                    firstName_edt = (EditText) (findViewById(R.id.activity_main_firstname_edt));
    
                    lastName_edt = (EditText) (findViewById(R.id.activity_main_lastname_edt));
    
                    preView_btn = (Button) (findViewById(R.id.activity_main_preview_btn));
    
                    preView_btn.setOnClickListener(this);
                    if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
                        Log.v(LOG_TAG,
                                "External Storage not available or you don't have permission to write");
                    } else {
                        // path for the PDF file in the external storage
                        pdfFile = new File(getExternalFilesDir(filepath), filename);
                    }
    
                }
    
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
    
                    switch (v.getId()) {
                    case R.id.activity_main_preview_btn:
    
                        String firstaName_str = firstName_edt.getText().toString();
                        String lastName_str = lastName_edt.getText().toString();
                        createPdf(firstaName_str, lastName_str);
    
                        break;
                    default:
                        break;
                    }
                }
    
                private void createPdf(String firstNAME, String lastNAME) {
                    // TODO Auto-generated method stub
    
                    // create file
                    try {
    
                        // create document
                        Document document = new Document(PageSize.A4.rotate(), 50, 50, 50,
                                50);
    
                        PdfWriter docWriter = PdfWriter.getInstance(document,
                                new FileOutputStream(pdfFile));
    
                        PdfContentByte cb = docWriter.getDirectContent();
    
                        document.open();
    
                        // initialize fonts
                        initializeFonts();
    
                        // set logo image
                        InputStream input = getAssets().open("ic_launcher.png");
    
                        Bitmap bitmap = BitmapFactory.decodeStream(input);
    
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
    
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    
                        com.itextpdf.text.Image logo = com.itextpdf.text.Image
                                .getInstance(stream.toByteArray());
                        logo.setAbsolutePosition(25, 700);
                        logo.scalePercent(25);
                        document.add(logo);
    
                        // create paragraph
                        document.add(new Paragraph("Personal Details"));
                        document.add(new Paragraph("Name:Sachin Singh"));
                        document.add(new Paragraph("Address: Kolkata"));
                        document.add(new Paragraph("email: ash@gmail.com"));
                        document.add(new Paragraph("Gender:F"));
    
                        // set firstname and lastname from edittext
                        createHeadings(cb, 450, 135, firstNAME, lastNAME);
    
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
    
                }
    
                private static boolean isExternalStorageReadOnly() {
                    String extStorageState = Environment.getExternalStorageState();
                    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
                        return true;
                    }
                    return false;
                }
    
                private static boolean isExternalStorageAvailable() {
                    String extStorageState = Environment.getExternalStorageState();
                    if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
                        return true;
                    }
                    return false;
                }
    
                private void initializeFonts() {
                    // TODO Auto-generated method stub
                    try {
                        bfBold = BaseFont.createFont(BaseFont.HELVETICA_BOLD,
                                BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    
                    } catch (DocumentException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                // method for setting firstname and last name
                private void createHeadings(PdfContentByte cb, float x, float y,
                        String firstNAME, String lastNAME) {
                    // TODO Auto-generated method stub
                    cb.beginText();
                    cb.setFontAndSize(bfBold, 8);
                    cb.setTextMatrix(x, y);
                    cb.showText(firstNAME.trim());
                    cb.showText(lastNAME.trim());
                    cb.endText();
                }
            }
    
    Xml文件

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
    
            <EditText
                android:id="@+id/activity_main_firstname_edt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="enter first name"
                android:ems="10" >
    
                <requestFocus />
            </EditText>
    
            <EditText
                android:id="@+id/activity_main_lastname_edt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                 android:hint="enter last name"
                android:ems="10" />
    
            <Button
                android:id="@+id/activity_main_preview_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Preview" />
    
        </LinearLayout>
    
     logcat data
    
    02-18 00:38:10.789: I/eFrame(32423): pkgname_before:com.example.pdf  class:com.android.launcher2.Launcher
    02-18 00:39:45.171: I/eFrame(32423): pkgname_before:com.sec.android.app.launcher  class:com.example.pdf.MainActivity
    02-18 00:39:53.159: W/System.err(32410): com.itextpdf.text.DocumentException: No message found for 1.not.found.as.resource
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.Type1Font.<init>(Type1Font.java:192)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:699)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:622)
    02-18 00:39:53.159: W/System.err(32410):    at com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:457)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.initializeFonts(MainActivity.java:162)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.createPdf(MainActivity.java:101)
    02-18 00:39:53.159: W/System.err(32410):    at com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    02-18 00:39:53.169: W/System.err(32410):    at com.itextpdf.text.pdf.PdfWriter.addSimple(PdfWriter.java:2280)
    02-18 00:39:53.169: W/System.err(32410):    at com.itextpdf.text.pdf.PdfContentByte.setFontAndSize(PdfContentByte.java:1704)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.createHeadings(MainActivity.java:137)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.createPdf(MainActivity.java:119)
    02-18 00:39:53.169: W/System.err(32410):    at com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    
    
    logcat数据
    02-18 00:38:10.789:I/eFrame(32423):pkgname_before:com.example.pdf类:com.android.Launcher.Launcher
    02-18 00:39:45.171:I/eFrame(32423):pkgname_before:com.sec.android.app.launcher class:com.example.pdf.main活动
    02-18 00:39:53.159:W/System.err(32410):com.itextpdf.text.DocumentException:未找到1.not.found.as.resource的消息
    02-18 00:39:53.159:W/System.err(32410):位于com.itextpdf.text.pdf.Type1Font.(Type1Font.java:192)
    02-18 00:39:53.159:W/System.err(32410):位于com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:699)
    02-18 00:39:53.159:W/System.err(32410):位于com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:622)
    02-18 00:39:53.159:W/System.err(32410):位于com.itextpdf.text.pdf.BaseFont.createFont(BaseFont.java:457)
    02-18 00:39:53.159:W/System.err(32410):位于com.example.pdf.MainActivity.initializeFonts(MainActivity.java:162)
    02-18 00:39:53.159:W/System.err(32410):位于com.example.pdf.MainActivity.createPdf(MainActivity.java:101)
    02-18 00:39:53.159:W/System.err(32410):位于com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    02-18 00:39:53.169:W/System.err(32410):位于com.itextpdf.text.pdf.PdfWriter.addSimple(PdfWriter.java:2280)
    02-18 00:39:53.169:W/System.err(32410):位于com.itextpdf.text.pdf.PdfContentByte.setFontAndSize(PdfContentByte.java:1704)
    02-18 00:39:53.169:W/System.err(32410):位于com.example.pdf.MainActivity.CreateHeaders(MainActivity.java:137)
    02-18 00:39:53.169:W/System.err(32410):位于com.example.pdf.MainActivity.createPdf(MainActivity.java:119)
    02-18 00:39:53.169:W/System.err(32410):位于com.example.pdf.MainActivity.onClick(MainActivity.java:74)
    
    在调用方法“docWriter.getDirectContent()”之前调用方法“document.open()”:

    关于字体异常,我不使用BaseFont。请尝试以下操作:

    // colors
        private static final BaseColor colorFont = new BaseColor(51, 51, 51);
        private static final BaseColor colorBlue = new BaseColor(32, 119, 215);
    
            // fonts
            private static final Font fontDefault = new Font(FontFamily.HELVETICA, 10,
                    Font.NORMAL, colorFont);
            private static final Font fontBold = new Font(FontFamily.HELVETICA, 10,
                    Font.BOLD, colorFont);
            private static final Font fontTitle = new Font(FontFamily.HELVETICA, 10,
                    Font.BOLD, colorBlue);
    
        new Paragraph(new Chunk("Personal Details",
                            fontDefault))
    

    请指出错误将出现的行…@Opiatefuchs在第94行..当调用createpdf方法时..你能发布stacktrace吗?@Opiatefuchs我对Android非常陌生..如何发布堆栈跟踪..请帮助我..你是在eclipse中开发的吗?如果是的话,在你的编码窗口下面有一个带有一些选项卡的窗口。在这个窗口中,必须有成为LogCat。你可以选择不同的消息类型。使用“错误”并复制问题。复制粘贴这些内容…….thnx,,,我尝试了你的建议..一些错误被删除了…但仍然不起作用,,,我用LogCat打印编辑了我的帖子…@user3519331我编辑了关于你字体的答案issue@user3519331,有用吗?
    // colors
        private static final BaseColor colorFont = new BaseColor(51, 51, 51);
        private static final BaseColor colorBlue = new BaseColor(32, 119, 215);
    
            // fonts
            private static final Font fontDefault = new Font(FontFamily.HELVETICA, 10,
                    Font.NORMAL, colorFont);
            private static final Font fontBold = new Font(FontFamily.HELVETICA, 10,
                    Font.BOLD, colorFont);
            private static final Font fontTitle = new Font(FontFamily.HELVETICA, 10,
                    Font.BOLD, colorBlue);
    
        new Paragraph(new Chunk("Personal Details",
                            fontDefault))